CWE
Home > CWE List > VIEW SLICE: CWE-630: Weaknesses Examined by SAMATE (1.6)  

CWE-630: Weaknesses Examined by SAMATE

 
Weaknesses Examined by SAMATE
Definition in a New Window Definition in a New Window
View ID: 630 (View: Explicit Slice)Status: Draft
+ View Data

View Objective

CWE nodes in this view (slice) are being focused on by SAMATE.

+ View Metrics
CWEs in this viewTotal CWEs
Total21out of791
Views0out of22
Categories1out of106
Weaknesses20out of651
Compound_Elements0out of12
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
HasMemberWeakness BaseWeakness Base78Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant80Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base89Improper Sanitization of Special Elements used in an SQL Command ('SQL Injection')
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base99Improper Control of Resource Identifiers ('Resource Injection')
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant121Stack-based Buffer Overflow
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant122Heap-based Buffer Overflow
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base134Uncontrolled Format String
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base170Improper Null Termination
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant244Failure to Clear Heap Memory Before Release ('Heap Inspection')
Weaknesses Examined by SAMATE (primary)630
HasMemberCategoryCategory251Often Misused: String Management
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base259Hard-Coded Password
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base367Time-of-check Time-of-use (TOCTOU) Race Condition
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base391Unchecked Error Condition
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base401Failure to Release Memory Before Removing Last Reference ('Memory Leak')
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base412Unrestricted Externally Accessible Lock
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant415Double Free
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base416Use After Free
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness VariantWeakness Variant457Use of Uninitialized Variable
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base468Incorrect Pointer Scaling
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base476NULL Pointer Dereference
Weaknesses Examined by SAMATE (primary)630
HasMemberWeakness BaseWeakness Base489Leftover Debug Code
Weaknesses Examined by SAMATE (primary)630
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Relationships, References, View Structure
View Components
View Components
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z
 
Double Free
Definition in a New Window Definition in a New Window
Weakness ID: 415 (Weakness Variant)Status: Draft
+ 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
Access Control

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

+ Likelihood of Exploit

Low to Medium

+ Demonstrative Examples

Example 1

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

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

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

Error conditions and other exceptional circumstances

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

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

Example 2

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

(Bad Code)
C
#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
CVE-2004-0642Double free resultant from certain error conditions.
CVE-2004-0772Double free resultant from certain error conditions.
CVE-2005-1689Double free resultant from certain error conditions.
CVE-2003-0545Double free from invalid ASN.1 encoding.
CVE-2003-1048Double free from malformed GIF.
CVE-2005-0891Double free from malformed GIF.
CVE-2002-0059Double free from malformed compressed data.
+ Potential Mitigations
PhaseDescription
Architecture and Design

Choose a language that provides automatic memory management.

Implementation

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

Implementation

Use a static analysis tool to find double free instances.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
PeerOfWeakness BaseWeakness Base123Write-what-where Condition
Research Concepts1000
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory399Resource Management Errors
Development Concepts (primary)699
PeerOfWeakness BaseWeakness Base416Use After Free
Development Concepts (primary)699
Research Concepts1000
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfWeakness BaseWeakness Base666Operation on Resource in Wrong Phase of Lifetime
Research Concepts (primary)1000
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
PeerOfWeakness BaseWeakness Base364Signal Handler Race Condition
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ 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
+ White Box Definitions

A weakness where code path has:

1. start statement that relinquishes a dynamically allocated memory resource

2. end statement that relinquishes the dynamically allocated memory resource

+ Maintenance Notes

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

+ Content History
Submissions
Submission 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
 
Failure to Clear Heap Memory Before Release ('Heap Inspection')
Definition in a New Window Definition in a New Window
Weakness ID: 244 (Weakness Variant)Status: Draft
+ Description

Description Summary

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

Extended Description

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

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Confidentiality

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

+ Demonstrative Examples

Example 1

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

(Bad Code)
C
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 Class227Failure to Fulfill API Contract ('API Abuse')
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
CanPrecedeWeakness ClassWeakness Class669Incorrect Resource Transfer Between Spheres
Research Concepts1000
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ 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
+ 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
 
Failure to Release Memory Before Removing Last Reference ('Memory Leak')
Definition in a New Window Definition in a New Window
Weakness ID: 401 (Weakness Base)Status: Draft
+ Description

Description Summary

The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.

Extended Description

This is often triggered by improper handling of malformed data or unexpectedly interrupted sessions.

+ Terminology Notes

"memory leak" has sometimes been used to describe other kinds of issues, e.g. for information leaks in which the contents of memory are inadvertently leaked (CVE-2003-0400 is one such example of this terminology conflict).

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

Languages

C

C++

+ Modes of Introduction

Memory leaks 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

+ Common Consequences
ScopeEffect
Availability

Most memory leaks result in general software reliability problems, but if an attacker can intentionally trigger a memory leak, the attacker might be able to launch a denial of service attack (by crashing or hanging the program) or take advantage of other unexpected program behavior resulting from a low memory condition.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

The following C function leaks a block of allocated memory if the call to read() fails to return the expected number of bytes:

(Bad Code)
C
char* getBlock(int fd) {
char* buf = (char*) malloc(BLOCK_SIZE);
if (!buf) {
return NULL;
}
if (read(fd, buf, BLOCK_SIZE) != BLOCK_SIZE) {
return NULL;
}
return buf;
}

Example 2

Here the problem is that every time a connection is made, more memory is allocated. So if one just opened up more and more connections, eventually the machine would run out of memory.

(Bad Code)
C
bar connection(){
foo = malloc(1024);
return foo;
}
endConnection(bar foo) {
free(foo);
}
int main() {
while(1) //thread 1
//On a connection
foo=connection(); //thread 2
//When the connection ends
endConnection(foo)
}
+ Observed Examples
ReferenceDescription
CVE-2005-3119Memory leak because function does not free() an element of a data structure.
CVE-2004-0427Memory leak when counter variable is not decremented.
CVE-2002-0574Memory leak when counter variable is not decremented.
CVE-2005-3181Kernel uses wrong function to release a data structure, preventing data from being properly tracked by other code.
CVE-2004-0222Memory leak via unknown manipulations as part of protocol test suite.
CVE-2001-0136Memory leak via a series of the same command.
+ Potential Mitigations
PhaseDescription

Pre-design: Use a language or compiler that performs automatic bounds checking.

Architecture and Design

Use an abstraction library to abstract away risky APIs. Not a complete solution.

Pre-design through Build: The Boehm-Demers-Weiser Garbage Collector or valgrind can be used to detect leaks in code. This is not a complete solution as it is not 100% effective.

+ 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
ChildOfWeakness BaseWeakness Base404Improper Resource Shutdown or Release
Research Concepts (primary)1000
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
Weaknesses in OWASP Top Ten (2004) (primary)711
CanFollowWeakness ClassWeakness Class390Detection of Error Condition Without Action
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Relationship Notes

This is often a resultant weakness due to improper handling of malformed data or early termination of sessions.

+ Affected Resources
  • Memory
+ Functional Areas
  • Memory management
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERMemory leak
7 Pernicious KingdomsMemory Leak
CLASPFailure to deallocate data
OWASP Top Ten 2004A9CWE More SpecificDenial of Service
+ White Box Definitions

A weakness where the code path has:

1. start statement that allocates dynamically allocated memory resource

2. end statement that loses identity of the dynamically allocated memory resource creating situation where dynamically allocated memory resource is never relinquished

Where "loses" is defined through the following scenarios:

1. identity of the dynamic allocated memory resource never obtained

2. the statement assigns another value to the data element that stored the identity of the dynamically allocated memory resource and there are no aliases of that data element

3. identity of the dynamic allocated memory resource obtained but never passed on to function for memory resource release

4. the data element that stored the identity of the dynamically allocated resource has reached the end of its scope at the statement and there are no aliases of that data element

+ References
J. Whittaker and H. Thompson. "How to Break Software Security". Addison Wesley. 2003.
+ 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 Applicable Platforms, Common Consequences, Relationships, Other Notes, References, Relationship Notes, Taxonomy Mappings, Terminology Notes
2008-10-14CWE Content TeamMITREInternal
updated Description
2009-03-10CWE Content TeamMITREInternal
updated Other Notes
2009-05-27CWE Content TeamMITREInternal
updated Name
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
2009-10-29CWE Content TeamMITREInternal
updated Modes of Introduction, Other Notes
 
Hard-Coded Password
Definition in a New Window Definition in a New Window
Weakness ID: 259 (Weakness Base)Status: Draft
+ Description

Description Summary

The software contains a hard-coded password, which it uses for its own inbound authentication or for outbound communication to external components.

Extended Description

A hard-coded password typically leads to a significant authentication failure that can be difficult for the system administrator to detect. Once detected, it can be difficult to fix, so the administrator maybe forced into disabling the product entirely. There are two main variations:

Inbound: the software contains an authentication mechanism that checks for a hard-coded password.

Outbound: the software connects to another system or component, and it contains hard-coded password for connecting to that component.

In the Inbound variant, a default administration account is created, and a simple password is hard-coded into the product and associated with that account. This hard-coded password is the same for each installation of the product, and it usually cannot be changed or disabled by system administrators without manually modifying the program, or otherwise patching the software. If the password is ever discovered or published (a common occurrence on the Internet), then anybody with knowledge of this password can access the product. Finally, since all installations of the software will have the same password, even across different organizations, this enables massive attacks such as worms to take place.

The Outbound variant applies to front-end systems that authenticate with a back-end service. The back-end service may require a fixed password which can be easily discovered. The programmer may simply hard-code those back-end credentials into the front-end software. Any user of that program may be able to extract the password. Client-side systems with hard-coded passwords pose even more of a threat, since the extraction of a password from a binary is usually very simple.

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

Languages

All

+ Common Consequences
ScopeEffect
Authentication

If hard-coded passwords are used, it is almost certain that malicious users will gain access through the account in question.

+ Likelihood of Exploit

Very High

+ Demonstrative Examples

Example 1

The following code uses a hard-coded password to connect to a database:

(Bad Code)
Java
...
DriverManager.getConnection(url, "scott", "tiger");
...

This is an example of an external hard-coded password on the client-side of a connection. This code will run successfully, but anyone who has access to it will have access to the password. Once the program has shipped, there is no going back from the database user "scott" with a password of "tiger" unless the program is patched. A devious employee with access to this information can use it to break into the system. Even worse, if attackers have access to the bytecode for application, they can use the javap -c command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for the example above:

(Attack)
javap -c ConnMngr.class
22: ldc #36; //String jdbc:mysql://ixne.com/rxsql
24: ldc #38; //String scott
26: ldc #17; //String tiger

Example 2

The following code is an example of an internal hard-coded password in the back-end:

(Bad Code)
C and C++
int VerifyAdmin(char *password) {
if (strcmp(password, "Mew!")) {
printf("Incorrect Password!\n");
return(0)
}
printf("Entering Diagnostic Mode...\n");
return(1);
}
(Bad Code)
Java
int VerifyAdmin(String password) {
if (passwd.Equals("Mew!")) {
return(0)
}
//Diagnostic Mode
return(1);
}

Every instance of this program can be placed into diagnostic mode with the same password. Even worse is the fact that if this program is distributed as a binary-only distribution, it is very difficult to change that password or disable this "functionality."

+ Potential Mitigations
PhaseDescription
Architecture and Design

For outbound authentication: store passwords outside of the code in a strongly-protected, encrypted configuration file or database that is protected from access by all outsiders, including other local users on the same system. Properly protect the key (CWE-320). If you cannot use encryption to protect the file, then make sure that the permissions are as restrictive as possible.

Architecture and Design

For inbound authentication: Rather than hard-code a default username and password for first time logins, utilize a "first login" mode that requires the user to enter a unique strong password.

Architecture and Design

Perform access control checks and limit which entities can access the feature that requires the hard-coded password. For example, a feature might only be enabled through the system console instead of through a network connection.

Architecture and Design

For inbound authentication: apply strong one-way hashes to your passwords and store those hashes in a configuration file or database with appropriate access control. That way, theft of the file/database still requires the attacker to try to crack the password. When handling an incoming password during authentication, take the hash of the password and compare it to the hash that you have saved.

Use randomly assigned salts for each separate hash that you generate. This increases the amount of computation that an attacker needs to conduct a brute-force attack, possibly limiting the effectiveness of the rainbow table method.

Architecture and Design

For front-end to back-end connections: Three solutions are possible, although none are complete.

The first suggestion involves the use of generated passwords which are changed automatically and must be entered at given time intervals by a system administrator. These passwords will be held in memory and only be valid for the time intervals.

Next, the passwords used should be limited at the back end to only performing actions valid for the front end, as opposed to having full access.

Finally, the messages sent should be tagged and checksummed with time sensitive values so as to prevent replay style attacks.

Testing

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

Testing

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

Attach the monitor to the process and perform a login. Using disassembled code, look at the associated instructions and see if any of them appear to be comparing the input to a fixed string or value.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory254Security Features
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory255Credentials Management
Development Concepts (primary)699
PeerOfWeakness BaseWeakness Base257Storing Passwords in a Recoverable Format
Research Concepts1000
PeerOfWeakness BaseWeakness Base321Use of Hard-coded Cryptographic Key
Research Concepts1000
ChildOfWeakness BaseWeakness Base344Use of Invariant Value in Dynamically Changing Context
Research Concepts (primary)1000
ChildOfWeakness ClassWeakness Class671Lack of Administrator Control over Security
Research Concepts1000
ChildOfCategoryCategory724OWASP Top Ten 2004 Category A3 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory753Porous Defenses
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
CanFollowWeakness BaseWeakness Base656Reliance on Security through Obscurity
Research Concepts1000
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsPassword Management: Hard-Coded Password
CLASPUse of hard-coded password
OWASP Top Ten 2004A3CWE More SpecificBroken Authentication and Session Management
+ White Box Definitions

Definition: A weakness where code path has:

1. end statement that passes a data item to a password function

2. value of the data item is a constant

+ Maintenance Notes

This entry should probably be split into multiple variants: an inbound variant (as seen in the second demonstrative example) and an outbound variant (as seen in the first demonstrative example). These variants are likely to have different consequences, detectability, etc. See extended description.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally 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 Common Consequences, Relationships, Other Notes, Taxonomy Mappings, Weakness Ordinalities
2008-10-14CWE Content TeamMITREInternal
updated Description, Potential Mitigations
2008-11-13CWE Content TeamMITREInternal
Significant description modifications to emphasize different variants.
2008-11-24CWE Content TeamMITREInternal
updated Demonstrative Examples, Description, Maintenance Notes, Other Notes, Potential Mitigations
2009-01-12CWE Content TeamMITREInternal
updated Demonstrative Examples, Description, Maintenance Notes, Potential Mitigations, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential Mitigations
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative Examples, Related Attack Patterns, White Box Definitions
 
Heap-based Buffer Overflow
Definition in a New Window Definition in a New Window
Weakness ID: 122 (Weakness Variant)Status: Draft
+ Description

Description Summary

A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc().
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Availability

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

Access Control

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

Besides important user data, heap-based overflows can be used to overwrite function pointers that may be living in memory, pointing it to the attacker's code. Even in applications that do not explicitly use function pointers, the run-time will usually leave many in memory. For example, object methods in C++ are generally implemented using function pointers. Even in C programs, there is often a global offset table used by the underlying runtime.

Other

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

+ Likelihood of Exploit

High to Very High

+ Demonstrative Examples

Example 1

(Bad Code)
C
#define BUFSIZE 256
int main(int argc, char **argv) {
char *buf;
buf = (char *)malloc(BUFSIZE);
strcpy(buf, argv[1]);
}
+ Observed Examples
ReferenceDescription
CVE-2007-4268Chain: integer signedness passes signed comparison, leads to heap overflow
+ Potential Mitigations
PhaseDescription

Pre-design: Use a language or compiler that performs automatic bounds checking.

Architecture and Design

Use an abstraction library to abstract away risky APIs. Not a complete solution.

Pre-design through Build: Canary style bounds checking, library changes which ensure the validity of chunk data, and other such fixes are possible, but should not be relied upon.

Implement and perform bounds checking on input.

Do not use dangerous functions such as gets. Look for their safe equivalent, which checks for the boundary.

Operational: Use OS-level preventative functionality. This is not a complete solution, but it provides some defense in depth.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfWeakness BaseWeakness Base787Out-of-bounds Write
Development Concepts699
Research Concepts1000
ChildOfWeakness BaseWeakness Base788Access of Memory Location After End of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Relationship Notes

Heap-based buffer overflows are usually just as dangerous as stack-based buffer overflows.

+ Affected Resources
  • Memory
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPHeap overflow
+ White Box Definitions

A buffer overflow where the buffer from the Buffer Write Operation is dynamically allocated

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally 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, Relationships, Other Notes, Taxonomy Mappings, Weakness Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Common Consequences, Other Notes, Relationship Notes
2009-01-12CWE Content TeamMITREInternal
updated Common Consequences, Relationships
2009-10-29CWE Content TeamMITREInternal
updated Relationships
 
Improper Control of Resource Identifiers ('Resource Injection')
Definition in a New Window Definition in a New Window
Weakness ID: 99 (Weakness Base)Status: Draft
+ Description

Description Summary

The software receives input from an upstream component, but it does not restrict or incorrectly restricts the input before it is used as an identifier for a resource that may be outside the intended sphere of control.

Extended Description

This may enable an attacker to access or modify otherwise protected system resources.

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

Languages

All

+ Likelihood of Exploit

High

+ Demonstrative Examples

Example 1

The following Java 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.

(Bad Code)
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 the command line to determine which file to open and echo back to the user. If the program runs with privileges and malicious users can create soft links to the file, they can use the program to read the first part of any file on the system.

(Bad Code)
C++
ifstream ifs(argv[0]);
string s;
ifs >> s;
cout << s;

The kind of resource the data affects indicates the kind of content that may be dangerous. For example, data containing special characters like period, slash, and backslash, are risky when used in methods that interact with the file system. (Resource injection, when it is related to file system resources, sometimes goes by the name "path manipulation.") Similarly, data that contains URLs and URIs is risky for functions that create remote connections.

+ Potential Mitigations
PhaseDescription

Assume all input is malicious. Use an appropriate combination of black lists and white lists to ensure only valid and expected input is processed by the system.

+ Other Notes

A resource injection issue occurs when the following two conditions are met: 1. An attacker can specify the identifier used to access a system resource. For example, an attacker might be able to specify part of the name of a file to be opened or a port number to be used. 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, run with a configuration controlled by the attacker, or transmit sensitive information to a third-party server. Note: Resource injection that involves resources stored on the filesystem goes by the name path manipulation and is reported in separate category. See the path manipulation description for further details of this vulnerability.

+ 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
Seven Pernicious Kingdoms (primary)700
CanAlsoBeWeakness ClassWeakness Class73External Control of File Name or Path
Research Concepts1000
ChildOfWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
PeerOfWeakness ClassWeakness Class706Use of Incorrectly-Resolved Name or Reference
Research Concepts1000
PeerOfWeakness BaseWeakness Base621Variable Extraction Error
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
ParentOfWeakness VariantWeakness Variant641Insufficient Filtering of File and Other Resource Names for Executable Content
Development Concepts (primary)699
Research Concepts (primary)1000
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsResource Injection
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input followed by

2. a statement that allocates a System Resource using name where the input is part of the name

3. end statement that accesses the System Resource where

a. the name of the System Resource violates protection

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other Notes, Taxonomy Mappings, Weakness Ordinalities
2009-05-27CWE Content TeamMITREInternal
updated Description, Name
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
 
Improper Null Termination
Definition in a New Window Definition in a New Window
Weakness ID: 170 (Weakness Base)Status: Incomplete
+ Description

Description Summary

The software does not terminate or incorrectly terminates a string or array with a null character or equivalent terminator.

Extended Description

Null termination errors frequently occur in two different ways. An off-by-one error could cause a null to be written out of bounds, leading to an overflow. Or, a program could use a strncpy() function call incorrectly, which prevents a null terminator from being added at all. Other scenarios are possible.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Platform Notes

Conceptually, this does not just apply to the C language; any language or representation that involves a terminator could have this type of problem.

+ Common Consequences
ScopeEffect
Confidentiality
Integrity

The case of an omitted null character is the most dangerous of the possible issues. This will almost certainly result in information disclosure, and possibly a buffer overflow condition, which may be exploited to execute arbitrary code.

Confidentiality
Integrity
Availability

If a null character is omitted from a string, then most string-copying functions will read data until they locate a null character, even outside of the intended boundaries of the string. This could:

cause a crash due to a segmentation fault

cause sensitive adjacent memory to be copied and sent to an outsider

trigger a buffer overflow when the copy is bering written to a fixed-size buffer

Integrity
Availability

Misplaced null characters may result in any number of security problems. The biggest issue is a subset of buffer overflow, and write-what-where conditions, where data corruption occurs from the writing of a null character over valid data, or even instructions. A randomly placed null character may put the system into an undefined state, and therefore make it prone to crashing. A misplaced null character may corrupt other data in memory

Access Control

Should the null character corrupt the process flow, or affect a flag controlling access, it may lead to logical errors which allow for the execution of arbitrary code.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

The following code reads from cfgfile and copies the input into inputbuf using strcpy(). The code mistakenly assumes that inputbuf will always contain a NULL terminator.

(Bad Code)
C
#define MAXLEN 1024
...
char *pathbuf[MAXLEN];
...
read(cfgfile,inputbuf,MAXLEN); //does not null terminate
strcpy(pathbuf,input_buf); //requires null terminated input
...

The code above will behave correctly if the data read from cfgfile is null terminated on disk as expected. But if an attacker is able to modify this input so that it does not contain the expected NULL character, the call to strcpy() will continue copying from memory until it encounters an arbitrary NULL character. This will likely overflow the destination buffer and, if the attacker can control the contents of memory immediately following inputbuf, can leave the application susceptible to a buffer overflow attack.

Example 2

In the following code, readlink() expands the name of a symbolic link stored in the buffer path so that the buffer filename contains the absolute path of the file referenced by the symbolic link. The length of the resulting value is then calculated using strlen().

(Bad Code)
C
char buf[MAXPATH];
...
readlink(path, buf, MAXPATH);
int length = strlen(filename);
...

The code above will not behave correctly because the value read into buf by readlink() will not be null terminated. In testing, vulnerabilities like this one might not be caught because the unused contents of buf and the memory immediately following it may be NULL, thereby causing strlen() to appear as if it is behaving correctly. However, in the wild strlen() will continue traversing memory until it encounters an arbitrary NULL character on the stack, which results in a value of length that is much larger than the size of buf and may cause a buffer overflow in subsequent uses of this value. Buffer overflows aside, whenever a single call to readlink() returns the same value that has been passed to its third argument, it is impossible to know whether the name is precisely that many bytes long, or whether readlink() has truncated the name to avoid overrunning the buffer. Traditionally, strings are represented as a region of memory containing data terminated with a NULL character. Older string-handling methods frequently rely on this NULL character to determine the length of the string. If a buffer that does not contain a NULL terminator is passed to one of these functions, the function will read past the end of the buffer. Malicious users typically exploit this type of vulnerability by injecting data with unexpected size or content into the application. They may provide the malicious input either directly as input to the program or indirectly by modifying application resources, such as configuration files. In the event that an attacker causes the application to read beyond the bounds of a buffer, the attacker may be able use a resulting buffer overflow to inject and execute arbitrary code on the system.

Example 3

While the following example is not exploitable, it provides a good example of how nulls can be omitted or misplaced, even when "safe" functions are used:

(Bad Code)
C
#include <stdio.h>
#include <string.h>
int main() {
char longString[] = "String signifying nothing";
char shortString[16];
strncpy(shortString, longString, 16);
printf("The last character in shortString is: %c %1$x\n", shortString[15]);
return (0);
}

The above code gives the following output: The last character in shortString is: l 6c So, the shortString array does not end in a NULL character, even though the "safe" string function strncpy() was used.

+ Observed Examples
ReferenceDescription
CVE-2000-0312Attacker does not null-terminate argv[] when invoking another program.
CVE-2003-0777Interrupted step causes resultant lack of null termination.
CVE-2004-1072Fault causes resultant lack of null termination, leading to buffer expansion.
CVE-2001-1389Multiple vulnerabilities related to improper null termination.
CVE-2003-0143Product does not null terminate a message buffer after snprintf-like call, leading to overflow.
+ Potential Mitigations
PhaseDescription
Requirements

Use a language that is not susceptible to these issues. However, be careful of null byte interaction errors (CWE-626) with lower-level constructs that may be written in a language that is susceptible..

Implementation

Ensure that all string functions used are understood fully as to how they append null characters. Also, be wary of off-by-one errors when appending nulls to the end of strings.

Implementation

If performance constraints permit, special code can be added that validates null-termination of string buffers, this is a rather naive and error-prone solution.

Implementation

Switch to bounded string manipulation functions. Inspect buffer lengths involved in the buffer overrun trace reported with the defect.

Implementation

Add code that fills buffers with nulls (however, the length of buffers still needs to be inspected, to ensure that the non null-terminated string is not written at the physical end of the buffer).

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class20Improper Input Validation
Seven Pernicious Kingdoms (primary)700
CanPrecedeCompound Element: CompositeCompound Element: Composite120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Research Concepts1000
CanPrecedeWeakness VariantWeakness Variant126Buffer Over-read
Research Concepts1000
CanAlsoBeWeakness VariantWeakness Variant147Improper Sanitization of Input Terminators
Research Concepts1000
ChildOfCategoryCategory169Technology-Specific Special Elements
Development Concepts (primary)699
PeerOfWeakness BaseWeakness Base463Deletion of Data Structure Sentinel
Research Concepts1000
PeerOfWeakness BaseWeakness Base464Addition of Data Structure Sentinel
Research Concepts1000
ChildOfWeakness ClassWeakness Class707Improper Enforcement of Message or Data Structure
Research Concepts (primary)1000
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
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
ChildOfCategoryCategory748CERT C Secure Coding Section 50 - POSIX (POS)
Weaknesses Addressed by the CERT C Secure Coding Standard734
CanFollowWeakness BaseWeakness Base193Off-by-one Error
Research Concepts1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
CanFollowWeakness ClassWeakness Class682Incorrect Calculation
Research Concepts1000
+ Relationship Notes

Factors: this is usually resultant from other weaknesses such as off-by-one errors, but it can be primary to boundary condition violations such as buffer overflows. In buffer overflows, it can act as an expander for assumed-immutable data.

Overlaps missing input terminator.

+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERImproper Null Termination
7 Pernicious KingdomsString Termination Error
CLASPMiscalculated null termination
OWASP Top Ten 2004A9CWE More SpecificDenial of Service
CERT C Secure CodingPOS30-CUse the readlink() function properly
CERT C Secure CodingSTR03-CDo not inadvertently truncate a null-terminated byte string
CERT C Secure CodingSTR32-CNull-terminate byte strings as required
+ White Box Definitions

A weakness where the code path has:

1. end statement that passes a data item to a null-terminated string function

2. start statement that produces the improper null-terminated data item

Where "produces" is defined through the following scenarios:

1. data item never ended with null-terminator

2. null-terminator is re-written

+ Maintenance Notes

As currently described, this entry is more like a category than a weakness.

+ 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-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Causal Nature, Common Consequences, Description, Likelihood of Exploit, Maintenance Notes, Relationships, Other Notes, Relationship Notes, Taxonomy Mappings, Weakness Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-03-10CWE Content TeamMITREInternal
updated Common Consequences
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated Common Consequences, Other Notes, Potential Mitigations, White Box Definitions
2009-10-29CWE Content TeamMITREInternal
updated Description
 
Improper Sanitization of Script-Related HTML Tags in a Web Page (Basic XSS)
Definition in a New Window Definition in a New Window
Weakness ID: 80 (Weakness Variant)Status: Incomplete
+ Description

Description Summary

The software receives input from an upstream component, but it does not sanitize or incorrectly sanitizes special characters such as "<", ">", and "&" that could be interpreted as web-scripting elements when they are sent to a downstream component that processes web pages.

Extended Description

This may allow such characters to be treated as control characters, which are executed client-side in the context of the user's session. Although this can be classified as an injection problem, the more pertinent issue is the failure to convert such special characters to respective context-appropriate entities before displaying them to the user.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Likelihood of Exploit

High to Very High

+ Demonstrative Examples

Example 1

In the following example, a guestbook comment isn't properly sanitized for script-related tags before being displayed in a client browser.

(Bad Code)
JSP
<% for (Iterator i = guestbook.iterator(); i.hasNext(); ) {
Entry e = (Entry) i.next(); %>
<p>Entry #<%= e.getId() %></p>
<p><%= e.getText() %></p>
<%
} %>
+ Observed Examples
ReferenceDescription
CVE-2002-0938XSS in parameter in a link.
CVE-2002-1495XSS in web-based email product via attachment filenames.
CVE-2003-1136HTML injection in posted message.
CVE-2004-2171XSS not quoted in error page.
+ Potential Mitigations
PhaseDescription

Carefully check each input parameter against a rigorous positive specification (white list) defining the specific characters and format allowed. All input should be sanitized, not just parameters that the user is supposed to specify, but all data in the request, including hidden fields, cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected to be redisplayed by the site. We often encounter data from the request that is reflected by the application server or the application that the development team did not anticipate. Also, a field that is not currently reflected may be used by a future developer. Therefore, validating ALL parts of the HTTP request is recommended.

This involves "HTML Entity Encoding" all non-alphanumeric characters from data that was received from the user and is now being written to the request.

With Struts, you should write all data from form beans with the bean's filter attribute set to true.

Additionally, to help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as Internet Explorer), this attribute prevents the user's session cookie from being accessed by client-side scripts, including scripts inserted due to a XSS attack.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base79Failure to Preserve Web Page Structure ('Cross-site Scripting')
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERBasic XSS
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input from HTML page

2. end statement that publishes a data item to HTML where

a. the input is part of the data item and

b. the input contains XSS syntax

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings, Weakness Ordinalities
2008-10-14CWE Content TeamMITREInternal
updated Description
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples, Description, Name
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
 
Improper Sanitization of Special Elements used in an OS Command ('OS Command Injection')
Definition in a New Window Definition in a New Window
Weakness ID: 78 (Weakness Base)Status: Draft
+ Description

Description Summary

The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not sanitize or incorrectly sanitizes special elements that could modify the intended OS command when it is sent to a downstream component.

Extended Description

This could allow attackers to execute unexpected, dangerous commands directly on the operating system. This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process fails to follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.

There are at least two subtypes of OS command injection:

1) The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing.

2) The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line.

From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input.

+ Alternate Terms
Shell injection
Shell metacharacters
+ Terminology Notes

The "OS command injection" phrase carries different meanings to different people. For some, it refers to any type of attack that can allow the attacker to execute OS commands of his or her choosing. This usage could include untrusted search path weaknesses (CWE-426) that cause the application to find and execute an attacker-controlled program. For others, it only refers to the first variant, in which the attacker injects command separators into arguments for an application-controlled program that is being invoked. Further complicating the issue is the case when argument injection (CWE-88) allows alternate command-line switches or options to be inserted into the command line, such as an "-exec" switch whose purpose may be to execute the subsequent argument as a command (this -exec switch exists in the UNIX "find" command, for example). In this latter case, however, CWE-88 could be regarded as the primary weakness in a chain with CWE-78.

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

Languages

All

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability
Non-Repudiation

Attackers could execute unauthorized commands, which could then be used to disable the software, or read and modify data for which the attacker does not have permissions to access directly. Since the targeted application is directly executing the commands instead of the attacker, any malicious activities may appear to come from the application or the application's owner.

+ Likelihood of Exploit

High

+ Demonstrative Examples

Example 1

This example is a web application that intends to perform a DNS lookup of a user-supplied domain name. It is subject to the first variant of OS command injection.

(Bad Code)
Perl
use CGI qw(:standard);
$name = param('name');
$nslookup = "/path/to/nslookup";
print header;
if (open($fh, "$nslookup $name|")) {
while (<$fh>) {
print escapeHTML($_);
print "<br>\n";
}
close($fh);
}

Suppose an attacker provides a domain name like this:

(Attack)
cwe.mitre.org%20%3B%20/bin/ls%20-l

The "%3B" sequence decodes to the ";" character, and the %20 decodes to a space. The open() statement would then process a string like this:

/path/to/nslookup cwe.mitre.org ; /bin/ls -l

As a result, the attacker executes the "/bin/ls -l" command and gets a list of all the files in the program's working directory. The input could be replaced with much more dangerous commands, such as installing a malicious program on the server.

Example 2

The example below reads the name of a shell script to execute from the system properties. It is subject to the second variant of OS command injection.

(Bad Code)
Java
String script = System.getProperty("SCRIPTNAME");
if (script != null)
System.exec(script);

If an attacker has control over this property, then he or she could modify the property to point to a dangerous program.

+ Observed Examples
ReferenceDescription
CVE-1999-0067Canonical example. CGI program does not sanitize "|" metacharacter when invoking a phonebook program.
CVE-2001-1246Language interpreter's mail function accepts another argument that is concatenated to a string used in a dangerous popen() call. Since there is no sanitization against this argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are possible.
CVE-2002-0061Web server allows command execution using "|" (pipe) character.
CVE-2003-0041FTP client does not filter "|" from filenames returned by the server, allowing for OS command injection.
CVE-2008-2575Shell metacharacters in a filename in a ZIP archive
CVE-2002-1898Shell metacharacters in a telnet:// link are not properly handled when the launching application processes the link.
CVE-2008-4304OS command injection through environment variable.
CVE-2008-4796OS command injection through https:// URLs
CVE-2007-3572Chain: incomplete blacklist for OS command injection
+ Potential Mitigations
PhaseDescription
Architecture and Design

If at all possible, use library calls rather than external processes to recreate the desired functionality.

Architecture and Design

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

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

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

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

Architecture and Design

For any data that will be used to generate a command to be executed, keep as much of that data out of external control as possible. For example, in web applications, this may require storing the command locally in the session's state instead of sending it out to the client in a hidden form field.

Architecture and Design

Use languages, libraries, or frameworks that make it easier to generate properly encoded output.

Examples include the ESAPI Encoding control.

Implementation

Properly quote arguments and escape any special characters within those arguments. If some special characters are still needed, wrap the arguments in quotes, and escape all other characters that do not pass a strict whitelist. Be careful of argument injection (CWE-88).

Implementation

If the program to be executed allows arguments to be specified within an input file or from standard input, then consider using that mode to pass arguments instead of the command line.

Implementation

If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.

Some languages offer multiple functions that can be used to invoke commands. Where possible, identify any function that invokes a command shell using a single string, and replace it with a function that requires individual arguments. These functions typically perform appropriate quoting and filtering of arguments. For example, in C, the system() function accepts a string that contains the entire command to be executed, whereas execl(), execve(), and others require an array of strings, one for each argument. In Windows, CreateProcess() only accepts one command at a time. In Perl, if system() is provided with an array of arguments, then it will quote each of the arguments.

Implementation

Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use a whitelist). Reject any input that does not strictly conform to specifications, or transform it into something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks.

Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the input for further processing. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue."

When constructing OS command strings, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping.

Note that proper output encoding, escaping, and quoting is the most effective solution for preventing OS command injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent OS command injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, when invoking a mail program, you might need to allow the subject field to contain otherwise-dangerous inputs like ";" and ">" characters, which would need to be escaped or otherwise handled. In this case, stripping the character might reduce the risk of OS command injection, but it would produce incorrect behavior because the subject field would not be recorded as the user intended. This might seem to be a minor inconvenience, but it could be more important when the program relies on well-structured subject lines in order to pass messages to other components.

Even if you make a mistake in your validation (such as forgetting one out of 100 input fields), appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not done in isolation, input validation is still a useful technique, since it may significantly reduce your attack surface, allow you to detect some attacks, and provide other security benefits that proper encoding does not address.

Testing
Implementation

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

Testing

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

Operation

Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force you to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).

Operation

Use runtime policy enforcement to create a whitelist of allowable commands, then prevent use of any command that does not appear in the whitelist. Technologies such as AppArmor are available to do this.

System Configuration

Assign permissions to the software system that prevent the user from accessing/opening privileged files. Run the application with the lowest privileges possible (CWE-250).

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

More investigation is needed into the distinction between the OS command injection variants, including the role with argument injection (CWE-88). Equivalent distinctions may exist in other injection-related problems such as SQL injection.

+ Affected Resources
  • System Process
+ Functional Areas
  • Program invocation
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVEROS Command Injection
OWASP Top Ten 2007A3CWE More SpecificMalicious File Execution
OWASP Top Ten 2004A6CWE More SpecificInjection Flaws
CERT C Secure CodingENV03-CSanitize the environment when invoking external programs
CERT C Secure CodingENV04-CDo not call system() if you do not need a command processor
CERT C Secure CodingSTR02-CSanitize data passed to complex subsystems
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input

2. end statement that executes an operating system command where

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

b. the operating system command is undesirable

Where "undesirable" is defined through the following scenarios:

1. not validated

2. incorrectly validated

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

Description Summary

The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not sanitize or incorrectly sanitizes special elements that could modify the intended SQL command when it is sent to a downstream component.

Extended Description

Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data. This can be used to alter query logic to bypass security checks, or to insert additional statements that modify the back-end database, possibly including execution of system commands.

SQL injection has become a common issue with database-driven web sites. The flaw is easily detected, and easily exploited, and as such, any site or software package with even a minimal user base is likely to be subject to an attempted attack of this kind. This flaw depends on the fact that SQL makes no real distinction between the control and data planes.

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

Languages

All

Technology Classes

Database-Server

+ Modes of Introduction

This weakness typically appears in data-rich applications that save user inputs in a database.

+ Common Consequences
ScopeEffect
Confidentiality

Since SQL databases generally hold sensitive data, loss of confidentiality is a frequent problem with SQL injection vulnerabilities.

Authentication

If poor SQL commands are used to check user names and passwords, it may be possible to connect to a system as another user with no previous knowledge of the password.

Authorization

If authorization information is held in a SQL database, it may be possible to change this information through the successful exploitation of a SQL injection vulnerability.

Integrity

Just as it may be possible to read sensitive information, it is also possible to make changes or even delete this information with a SQL injection attack.

+ Likelihood of Exploit

Very High

+ Enabling Factors for Exploitation

The application dynamically generates queries that contain user input.

+ Demonstrative Examples

Example 1

In 2008, a large number of web servers were compromised using the same SQL injection attack string. This single string worked against many different programs. The SQL injection was then used to modify the web sites to serve malicious code. [1]

Example 2

The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user.

(Bad Code)
C#
...
string userName = ctx.getAuthenticatedUserName();
string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + ItemName.Text + "'";
sda = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
...

The query that this code intends to execute follows:

SELECT * FROM items WHERE owner = <userName> AND itemname = <itemName>;

However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string:

(Attack)
name' OR 'a'='a

for itemName, then the query becomes the following:

(Attack)
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';

The addition of the:

(Attack)
OR 'a'='a'

condition causes the WHERE clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query:

(Attack)
SELECT * FROM items;

This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the items table, regardless of their specified owner.

Example 3

This example examines the effects of a different malicious value passed to the query constructed and executed in the previous example.

If an attacker with the user name wiley enters the string:

(Attack)
name'; DELETE FROM items; --

for itemName, then the query becomes the following two queries:

(Attack)
SQL
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';
DELETE FROM items;
--'

Many database servers, including Microsoft(R) SQL Server 2000, allow multiple SQL statements separated by semicolons to be executed at once. While this attack string results in an error on Oracle and other database servers that do not allow the batch-execution of statements separated by semicolons, on databases that do allow batch execution, this type of attack allows the attacker to execute arbitrary commands against the database.

Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder of the statement is to be treated as a comment and not executed. In this case the comment character serves to remove the trailing single-quote left over from the modified query. On a database where comments are not allowed to be used in this way, the general attack could still be made effective using a trick similar to the one shown in the previous example.

If an attacker enters the string

(Attack)
name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a

Then the following three valid statements will be created:

(Attack)
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';
DELETE FROM items;
SELECT * FROM items WHERE 'a'='a';

One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. Whitelisting can be a very effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:

- Target fields that are not quoted

- Find ways to bypass the need for certain escaped meta-characters

- Use stored procedures to hide the injected meta-characters.

Manually escaping characters in input to SQL queries can help, but it will not make your application secure from SQL injection attacks.

Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to protect against many others. For example, the following PL/SQL procedure is vulnerable to the same SQL injection attack shown in the first example.

(Bad Code)
procedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm in varchar2)
is open itm_cv for
' SELECT * FROM items WHERE ' || 'owner = '|| usr || ' AND itemname = ' || itm || ';
end get_item;

Stored procedures typically help prevent SQL injection attacks by limiting the types of statements that can be passed to their parameters. However, there are many ways around the limitations and many interesting statements that can still be passed to stored procedures. Again, stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks.

Example 4

MS SQL has a built in function that enables shell command execution. An SQL injection in such a context could be disastrous. For example, a query of the form:

(Bad Code)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='$user_input' ORDER BY PRICE

Where $user_input is taken from the user and unfiltered.

If the user provides the string:

(Attack)
' exec master..xp_cmdshell 'vol' --

The query will take the following form: "

(Attack)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='' exec master..xp_cmdshell 'vol' --' ORDER BY PRICE

Now, this query can be broken down into:

[1] a first SQL query: SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=''

[2] a second SQL query, which executes a shell command: exec master..xp_cmdshell 'vol'

[3] an MS SQL comment: --' ORDER BY PRICE

As can be seen, the malicious input changes the semantics of the query into a query, a shell command execution and a comment.

Example 5

This code intends to print a message summary given the message ID.

(Bad Code)
PHP
$id = $_COOKIE["mid"];
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'");

The programmer may have skipped any input validation on $id under the assumption that attackers cannot modify the cookie. However, this is easy to do with custom client code or even in the web browser.

While $id is wrapped in single quotes in the call to mysql_query(), an attacker could simply change the incoming mid cookie to:

1432' or '1' = '1

This would produce the resulting query:

SELECT MessageID, Subject FROM messages WHERE MessageID = '1432' or '1' = '1'

Not only will this retrieve message number 1432, it will retrieve all other messages.

In this case, the programmer could apply a simple modification to the code to eliminate the SQL injection:

(Good Code)
PHP
$id = intval($_COOKIE["mid"]);
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'");

However, if this code is intended to support multiple users with different message boxes, the code would need an access control check (CWE-285) to ensure that the application user has the permission to see that message.

Example 6

This example attempts to take a last name provided by a user and enter it into a database.

(Bad Code)
Perl
$userKey = getUserID();
$name = getUserInput();
# ensure only letters, hyphens and apostrophe are allowed
$name = whiteList($name, "^a-zA-z'-$");
$query = "INSERT INTO last_names VALUES('$userKey', '$name')";

While the programmer applies a whitelist to the user input, it has shortcomings. First of all, the user is still allowed to provide hyphens which are used as comment structures in SQL. If a user specifies -- then the remainder of the statement will be treated as a comment, which may bypass security logic. Furthermore, the whitelist permits the apostrophe which is also a data / command separator in SQL. If a user supplies a name with an apostrophe, they may be able to alter the structure of the whole statement and even change control flow of the program, possibly accessing or modifying confidential information. In this situation, both the hyphen and apostrophe are legitimate characters for a last name and permitting them is required. Instead, a programmer may want to use a prepared statement or apply an encoding routine to the input to prevent any data / directive misinterpretations.

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

Use languages, libraries, or frameworks that make it easier to generate properly encoded output.

For example, consider using persistence layers such as Hibernate or Enterprise Java Beans, which can provide significant protection against SQL injection if used properly.

Architecture and Design

If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.

Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using "exec" or similar functionality, since you may re-introduce the possibility of SQL injection.

Architecture and Design

Follow the principle of least privilege when creating user accounts to a SQL database. The database users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data. Use the strictest permissions possible on all database objects, such as execute-only for stored procedures.

Architecture and Design

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

Implementation

If you need to use dynamically-generated query strings in spite of the risk, use proper encoding and escaping of inputs. Instead of building your own implementation, such features may be available in the database or programming language. For example, the Oracle DBMS_ASSERT package can check or enforce that parameters have certain properties that make them less vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C and PHP.

Implementation

Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use a whitelist). Reject any input that does not strictly conform to specifications, or transform it into something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks.

Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the input for further processing. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue."

When constructing SQL query strings, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping.

Note that proper output encoding, escaping, and quoting is the most effective solution for preventing SQL injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent SQL injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, the name "O'Reilly" would likely pass the validation step, since it is a common last name in the English language. However, it cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded.

When feasible, it may be safest to disallow meta-characters entirely, instead of escaping them. This will provide some defense in depth. After the data is entered into the database, later processes may neglect to escape meta-characters before use, and you may not have control over those processes.

Testing
Implementation

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

Testing

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

Operation

Use an application firewall that can detect attacks against this weakness. This might not catch all attacks, and it might require some effort for customization. However, it can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth.

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

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

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

A weakness where the code path has:

1. start statement that accepts input and

2. end statement that performs an SQL command where

a. the input is part of the SQL command and

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

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

Description Summary

In C and C++, one may often accidentally refer to the wrong memory due to the semantics of when math operations are implicitly scaled.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability

Incorrect pointer scaling will often result in buffer overflow conditions. Confidentiality can be compromised if the weakness is in the context of a buffer over-read or under-read.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

(Bad Code)
C
int *p = x;
char * second_char = (char *)(p + 1);

In this example, second_char is intended to point to the second byte of p. But, adding 1 to p actually adds sizeof(int) to p, giving a result that is incorrect (3 bytes off on 32-bit platforms). If the resulting memory address is read, this could potentially be an information leak. If it is a write, it could be a security-critical write to unauthorized memory-- whether or not it is a buffer overflow. Note that the above code may also be wrong in other ways, particularly in a little endian environment.

+ Potential Mitigations
PhaseDescription
Architecture and Design

Use a platform with high-level memory abstractions.

Implementation

Always use array indexing instead of direct pointer manipulation.

Other: Use technologies for preventing buffer overflows.

+ Other Notes

Programmers will often try to index from a pointer by adding a number of bytes, even though this is wrong, since C and C++ implicitly scale the operand by the size of the data type.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory465Pointer Issues
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class682Incorrect Calculation
Research Concepts (primary)1000
ChildOfCategoryCategory737CERT C Secure Coding Section 03 - Expressions (EXP)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPUnintentional pointer scaling
CERT C Secure CodingEXP08-CEnsure pointer arithmetic is used correctly
+ White Box Definitions

A weakness where code path has a statement that performs a pointer arithmetic operation on a pointer to datatype1 and casts the result of the operation to a pointer type to datatype2 where datatype2 has different length than the datatype1 and the datatype1 has different length than a character type.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Relationships, Other Notes, Taxonomy Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
2009-10-29CWE Content TeamMITREInternal
updated Common Consequences
 
Leftover Debug Code
Definition in a New Window Definition in a New Window
Weakness ID: 489 (Weakness Base)Status: Draft
+ Description

Description Summary

The application can be deployed with active debugging code that can create unintended entry points.
+ Time of Introduction
  • Implementation
  • Operation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability

The severity of the exposed debug application will depend on the particular instance. At the least, it will give an attacker sensitive information about the settings and mechanics of web applications on the server. At worst, as is often the case, the debug application will allow an attacker complete control over the web application and server, as well as confidential information that either of these access.

+ Demonstrative Examples

Example 1

Debug code can be used to bypass authentication. For example, suppose an application has a login script that receives a username and a password. Assume also that a third, optional, parameter, called "debug", is interpreted by the script as requesting a switch to debug mode, and that when this parameter is given the username and password are not checked. In such a case, it is very simple to bypass the authentication process if the special behavior of the application regarding the debug parameter is known. In a case where the form is:

(Bad Code)
HTML
<FORM ACTION="/authenticate_login.cgi">
<INPUT TYPE=TEXT name=username>
<INPUT TYPE=PASSWORD name=password>
<INPUT TYPE=SUBMIT>
</FORM>

Then a conforming link will look like:

http://TARGET/authenticate_login.cgi?username=...&password=...

An attacker can change this to:

(Attack)
http://TARGET/authenticate_login.cgi?username=&password=&debug=1

Which will grant the attacker access to the site, bypassing the authentication process.

+ Potential Mitigations
PhaseDescription

Remove debug code before deploying the application.

+ Other Notes

A common development practice is to add "back door" code specifically designed for debugging or testing purposes that is not intended to be shipped or deployed with the application. In web-based applications, debug code is used to test and modify web application properties, configuration information, and functions. If a debug application is left on a production server, an attacker may be able to use it to perform these tasks. When this sort of debug code is left in the application, the application is open to unintended modes of interaction. These back door entry points create security risks because they are not considered during design or testing and fall outside of the expected operating conditions of the application.

While it is possible to leave debug code in an application in any language, in J2EE a main method may be a good indicator that debug code has been left in the application, although there may not be any direct security impact.

+ 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
ChildOfCategoryCategory731OWASP Top Ten 2004 Category A10 - Insecure Configuration Management
Weaknesses in OWASP Top Ten (2004) (primary)711
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsLeftover Debug Code
OWASP Top Ten 2004A10CWE More SpecificInsecure Configuration Management
+ White Box Definitions

A weakness where code path has a statement that defines an entry point into an application which exposes additional state and control information

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally 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 Common Consequences, Relationships, Other Notes, Taxonomy Mappings
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-10-29CWE Content TeamMITREInternal
updated Common Consequences
 
NULL Pointer Dereference
Definition in a New Window Definition in a New Window
Weakness ID: 476 (Weakness Base)Status: Draft
+ Description

Description Summary

A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Java

.NET

+ Common Consequences
ScopeEffect
Availability

NULL pointer dereferences usually result in the failure of the process.

In very rare circumstances and environments, code execution is possible.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

NULL pointer dereference issue can occur through a number of flaws, including race conditions, and simple programming omissions. While there are no complete fixes aside from conscientious programming, the following steps will go a long way to ensure that NULL pointer dereferences do not occur. Before using a pointer, ensure that it is not equal to NULL:

(Good Code)
C
if (pointer1 != NULL) {
/* make use of pointer1 */
/* ... */
}

When freeing pointers, ensure they are not set to NULL, and be sure to set them to NULL once they are freed:

(Good Code)
C
if (pointer1 != NULL) {
free(pointer1);
pointer1 = NULL;
}

If you are working with a multi-threaded or otherwise asynchronous environment, ensure that proper locking APIs are used to lock before the if statement; and unlock when it has finished.

Example 2

In the following code, the programmer assumes that the system always has a property named "cmd" defined. If an attacker can control the program's environment so that "cmd" is not defined, the program throws a NULL pointer exception when it attempts to call the trim() method.

(Bad Code)
Java
String cmd = System.getProperty("cmd");
cmd = cmd.trim();
+ Observed Examples
ReferenceDescription
CVE-2005-3274race condition causes a table to be corrupted if a timer activates while it is being modified, leading to resultant NULL dereference; also involves locking.
CVE-2002-1912large number of packets leads to NULL dereference
CVE-2005-0772packet with invalid error status value triggers NULL dereference
CVE-2004-0079
CVE-2004-0365
CVE-2003-1013
CVE-2003-1000
CVE-2004-0389
CVE-2004-0119
CVE-2004-0458
CVE-2002-0401
+ Potential Mitigations
PhaseDescription

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

Implementation

If all pointers that could have been modified are sanity-checked previous to use, nearly all NULL pointer dereferences can be prevented.

+ Other Notes

NULL pointer dereferences, while common, can generally be found and corrected in a simply way. They will always result in the crash of the process unless exception handling (on some platforms) is invoked, and even then, little can be done to salvage the process.

NULL pointer dereferences are frequently resultant from rarely encountered error conditions, since these are most likely to escape detection during the testing phases.

+ Weakness Ordinalities
OrdinalityDescription
Resultant
(where the weakness is typically related to the presence of some other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)Named Chain(s) this relationship pertains toChain(s)
PeerOfWeakness BaseWeakness Base373State Synchronization Error
Research Concepts1000
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
Research Concepts (primary)1000
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory737CERT C Secure Coding Section 03 - Expressions (EXP)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory742CERT C Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C Secure Coding Standard734
CanFollowWeakness BaseWeakness Base252Unchecked Return Value
Research Concepts1000
Unchecked Return Value to NULL Pointer Dereference690
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
CanFollowWeakness VariantWeakness Variant789Uncontrolled Memory Allocation
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsNull Dereference
CLASPNull-pointer dereference
PLOVERNull Dereference (Null Pointer Dereference)
OWASP Top Ten 2004A9CWE More SpecificDenial of Service
CERT C Secure CodingEXP34-CEnsure a null pointer is not dereferenced
CERT C Secure CodingMEM32-CDetect and handle memory allocation errors
+ White Box Definitions

A weakness where the code path has:

1. start statement that assigns a null value to the pointer

2. end statement that dereferences a pointer

3. the code path does not contain any other statement that assigns value to the pointer

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time of Introduction
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Relationships, Other Notes, Taxonomy Mappings, Weakness Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-10-29CWE Content TeamMITREInternal
updated Relationships
 
Often Misused: String Management
Definition in a New Window Definition in a New Window
Category ID: 251 (Category)Status: Incomplete
+ Description

Description Summary

Functions that manipulate strings encourage buffer overflows.
+ Applicable Platforms

Languages

C

C++

+ Demonstrative Examples

Example 1

Windows provides the _mbs family of functions to perform various operations on multibyte strings. When these functions are passed a malformed multibyte string, such as a string containing a valid leading byte followed by a single null byte, they can read or write past the end of the string buffer causing a buffer overflow. The following functions all pose a risk of buffer overflow: _mbsinc _mbsdec _mbsncat _mbsncpy _mbsnextc _mbsnset _mbsrev _mbsset _mbsstr _mbstok _mbccpy _mbslen

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory133String Errors
Development Concepts699
ChildOfWeakness ClassWeakness Class227Failure to Fulfill API Contract ('API Abuse')
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsOften Misused: Strings
+ White Box Definitions

Definition: A weakness where code path has:

1. end statement that passes the string item to a string function

2. start statement that malformed the string item

Where "malformed" is defined through the following scenarios:

1. changed to unexpected value

2. incorrect syntactical structure

+ 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, Relationships, Taxonomy Mappings
 
Stack-based Buffer Overflow
Definition in a New Window Definition in a New Window
Weakness ID: 121 (Weakness Variant)Status: Draft
+ Description

Description Summary

A stack-based buffer overflow condition is a condition where the buffer being overwritten is allocated on the stack (i.e., is a local variable or, rarely, a parameter to a function).
+ Alternate Terms
Stack Overflow:

"Stack Overflow" is often used to mean the same thing as stack-based buffer overflow, however it is also used on occasion to mean stack exhaustion, usually a result from an excessively recursive function call. Due to the ambiguity of the term, use of stack overflow to describe either circumstance is discouraged.

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

Languages

C

C++

+ Common Consequences
ScopeEffect
Availability

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

Access Control

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

Other

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

+ Likelihood of Exploit

Very High

+ Demonstrative Examples

Example 1

While buffer overflow examples can be rather complex, it is possible to have very simple, yet still exploitable, stack-based buffer overflows:

(Bad Code)
C
#define BUFSIZE 256
int main(int argc, char **argv) {
char buf[BUFSIZE];
strcpy(buf, argv[1]);
}
+ Potential Mitigations
PhaseDescription
Requirements

Use a language or compiler that performs automatic bounds checking.

Architecture and Design

Use an abstraction library to abstract away risky APIs. Not a complete solution.

Build and Compilation

Compiler-based canary mechanisms such as StackGuard, ProPolice and the Microsoft Visual Studio /GS flag. Unless this provides automatic bounds checking, it is not a complete solution.

Implementation

Implement and perform bounds checking on input.

Implementation

Do not use dangerous functions such as gets. Use safer, equivalent functions which check for boundary errors.

Operation

Use OS-level preventative functionality, such as ASLR. This is not a complete solution.

+ Background Details

There are generally several security-critical data on an execution stack that can lead to arbitrary code execution. The most prominent is the stored return address, the memory address at which execution should continue once the current function is finished executing. The attacker can overwrite this value with some memory address to which the attacker also has write access, into which he places arbitrary code to be run with the full privileges of the vulnerable program. Alternately, the attacker can supply the address of an important call, for instance the POSIX system() call, leaving arguments to the call on the stack. This is often called a return into libc exploit, since the attacker generally forces the program to jump at return time into an interesting routine in the C standard library (libc). Other important data commonly on the stack include the stack pointer and frame pointer, two values that indicate offsets for computing memory addresses. Modifying those values can often be leveraged into a "write-what-where" condition.

+ Other Notes

Stack-based buffer overflows can instantiate in return address overwrites, stack pointer overwrites or frame pointer overwrites. They can also be considered function pointer overwrites, array indexer overwrites or write-what-where condition, etc.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base787Out-of-bounds Write
Development Concepts699
Research Concepts1000
ChildOfWeakness BaseWeakness Base788Access of Memory Location After End of Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPStack overflow
+ White Box Definitions

A stack-based buffer overflow is a weakness where the code path includes a buffer write operation such that:

1. stack allocation of a buffer

2. data is written to the buffer where

3. the expected size of the buffer is greater than the actual size of the buffer where

expected size is equal to size of data added to position from which writing operation starts

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally 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 Alternate Terms, Applicable Platforms, Background Details, Common Consequences, Relationships, Other Notes, Taxonomy Mappings, Weakness Ordinalities
2009-01-12CWE Content TeamMITREInternal
updated Common Consequences, Relationships
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated Potential Mitigations, White Box Definitions
2009-10-29CWE Content TeamMITREInternal
updated Relationships
 
Time-of-check Time-of-use (TOCTOU) Race Condition
Definition in a New Window Definition in a New Window
Weakness ID: 367 (Weakness Base)Status: Incomplete
+ Description

Description Summary

The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.

Extended Description

This weakness can be security-relevant when an attacker can influence the state of the resource between check and use. This can happen with shared resources such as files, memory, or even variables in multi-threaded programs.

+ Alternate Terms
TOCTTOU:

The TOCCTOU acronym expands to "Time Of Check To Time Of Use". Usage varies between TOCTOU and TOCTTOU.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control

The attacker can gain access to otherwise unauthorized resources.

Access Control
Authorization

Race conditions such as this kind may be employed to gain read or write access to resources which are not normally readable or writable by the user in question.

Integrity

The resource in question, or other resources (through the corrupted one), may be changed in undesirable ways by a malicious user.

Accountability

If a file or other resource is written in this method, as opposed to in a valid way, logging of the activity may not occur.

Non-Repudiation

In some cases it may be possible to delete files a malicious user might not otherwise have access to, such as log files.

+ Likelihood of Exploit

Low to Medium

+ Demonstrative Examples

Example 1

(Bad Code)
C and C++
struct stat *sb;
...
lstat("...",sb); // it has not been updated since the last time it was read
printf("stated file\n");
if (sb->st_mtimespec==...){
print("Now updating things\n");
updateThings();
}

Potentially the file could have been updated between the time of the check and the lstat, especially since the printf has latency.

Example 2

The following code is from a program installed setuid root. The program performs certain file operations on behalf of non-privileged users, and uses access checks to ensure that it does not use its root privileges to perform operations that should otherwise be unavailable the current user. The program uses the access() system call to check if the person running the program has permission to access the specified file before it opens the file and performs the necessary operations.

(Bad Code)
C
if(!access(file,W_OK)) {
f = fopen(file,"w+");
operate(f);
...
}
else {
fprintf(stderr,"Unable to open file %s.\n",file);
}

The call to access() behaves as expected, and returns 0 if the user running the program has the necessary permissions to write to the file, and -1 otherwise. However, because both access() and fopen() operate on filenames rather than on file handles, there is no guarantee that the file variable still refers to the same file on disk when it is passed to fopen() that it did when it was passed to access(). If an attacker replaces file after the call to access() with a symbolic link to a different file, the program will use its root privileges to operate on the file even if it is a file that the attacker would otherwise be unable to modify. By tricking the program into performing an operation that would otherwise be impermissible, the attacker has gained elevated privileges. This type of vulnerability is not limited to programs with root privileges. If the application is capable of performing any operation that the attacker would not otherwise be allowed perform, then it is a possible target.

+ Observed Examples
ReferenceDescription
CVE-2003-0813
CVE-2004-0594
CVE-2008-2958chain: time-of-check time-of-use (TOCTOU) race condition in program allows bypass of protection mechanism that was designed to prevent symlink attacks.
CVE-2008-1570chain: time-of-check time-of-use (TOCTOU) race condition in program allows bypass of protection mechanism that was designed to prevent symlink attacks.
+ Potential Mitigations
PhaseDescription

The most basic advice for TOCTOU vulnerabilities is to not perform a check before the use. This does not resolve the underlying issue of the execution of a function on a resource whose state and identity cannot be assured, but it does help to limit the false sense of security given by the check.

Implementation

When the file being altered is owned by the current user and group, set the effective gid and uid to that of the current user and group when executing this statement.

Do not rely on user-specified input to determine what path to format.

Architecture and Design

Limit the interleaving of operations on files from multiple processes.

Limit the spread of time (cycles) between the check and use of a resource.

Implementation

Recheck the resource after the use call to verify that the action was taken appropriately.

Architecture and Design

Ensure that some environmental locking mechanism can be used to protect resources effectively.

Implementation

Ensure that locking occurs before the check, as opposed to afterwards, such that the resource, as checked, is the same as it is when in use.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class362Race Condition
Development Concepts (primary)699
Research Concepts (primary)1000
PeerOfWeakness BaseWeakness Base373State Synchronization Error
Research Concepts1000
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ParentOfWeakness BaseWeakness Base363Race Condition Enabling Link Following
Development Concepts (primary)699
Research Concepts (primary)1000
PeerOfWeakness BaseWeakness Base386Symbolic Name not Mapping to Correct Object
Research Concepts1000
ParentOfWeakness BaseWeakness Base609Double-Checked Locking
Research Concepts (primary)1000
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Relationship Notes

TOCTOU issues do not always involve symlinks, and not every symlink issue is a TOCTOU problem.

+ Research Gaps

Non-symlink TOCTOU issues are not reported frequently, but they are likely to occur in code that attempts to be secure.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERTime-of-check Time-of-use race condition
7 Pernicious KingdomsFile Access Race Conditions: TOCTOU
CLASPTime of check, time of use race condition
CERT C Secure CodingFIO01-CBe careful using functions that use file names for identification
+ White Box Definitions

A weakness where code path has:

1. start statement that validates a system resource by name rather than by reference

2. end statement that accesses the system resource by the name

+ References
Dan Tsafrir, Tomer Hertz, David Wagner and Dilma Da Silva. "Portably Solving File TOCTTOU Races with Hardness Amplification". 2008-02-28. <http://www.usenix.org/events/fast08/tech/tsafrir.html>.
+ 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-09-08CWE Content TeamMITREInternal
updated Common Consequences, Relationships, Other Notes, Taxonomy Mappings
2008-10-14CWE Content TeamMITREInternal
updated Description, Name, Relationships
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-01-12CWE Content TeamMITREInternal
updated Alternate Terms, Observed Examples, Other Notes, References, Relationship Notes, Relationships, Research Gaps
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
 
Unchecked Error Condition
Definition in a New Window Definition in a New Window
Weakness ID: 391 (Weakness Base)Status: Incomplete
+ Description

Description Summary

Ignoring exceptions and other error conditions may allow an attacker to induce unexpected behavior unnoticed.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

The following code excerpt ignores a rarely-thrown exception from doExchange().

(Bad Code)
Java
try {
doExchange();
}
catch (RareException e) {
// this can never happen
}

If a RareException were to ever be thrown, the program would continue to execute as though nothing unusual had occurred. The program records no evidence indicating the special situation, potentially frustrating any later attempt to explain the program's behavior.

+ Potential Mitigations
PhaseDescription

Requirements Specification: The choice between a language which has named or unnamed exceptions needs to be done. While unnamed exceptions exacerbate the chance of not properly dealing with an exception, named exceptions suffer from the up call version of the weak base class problem.

Requirements Specification: A language can be used which requires, at compile time, to catch all serious exceptions. However, one must make sure to use the most current version of the API as new exceptions could be added.

Implementation

Catch all relevant exceptions. 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.

+ Other Notes

Just about every serious attack on a software system begins with the violation of a programmer's assumptions. After the attack, the programmer's assumptions seem flimsy and poorly founded, but before an attack many programmers would defend their assumptions well past the end of their lunch break. Two dubious assumptions that are easy to spot in code are "this method call can never fail" and "it doesn't matter if this call fails". When a programmer ignores an exception, they implicitly state that they are operating under one of these assumptions.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory388Error Handling
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory389Error Conditions, Return Values, Status Codes
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class703Failure to Handle Exceptional Conditions
Research Concepts (primary)1000
ChildOfCategoryCategory728OWASP Top Ten 2004 Category A7 - Improper Error Handling
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory746CERT C Secure Coding Section 12 - Error Handling (ERR)
Weaknesses Addressed by the CERT C Secure Coding Standard734
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUnchecked Return Value
7 Pernicious KingdomsEmpty Catch Block
CLASPUncaught exception
OWASP Top Ten 2004A7CWE More SpecificImproper Error Handling
CERT C Secure CodingERR00-CAdopt and implement a consistent and comprehensive error-handling policy
CERT C Secure CodingFIO04-CDetect and handle input and output errors
CERT C Secure CodingFIO33-CDetect and handle input output errors resulting in undefined behavior
+ White Box Definitions

A weakness where code path has:

1. start statement that changes a state of the system resource

2. end statement that accesses the system resource, where the changed and the assumed state of the system resource are not equal.

3. the state of the resource is not compatible with the type of access being performed by the end statement

+ Maintenance Notes

This entry needs significant modification. It currently combines information from three different taxonomies, but each taxonomy is talking about a slightly different issue.

+ 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 Maintenance Notes, Relationships, Other Notes, Taxonomy Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
 
Uncontrolled Format String
Definition in a New Window Definition in a New Window
Weakness ID: 134 (Weakness Base)Status: Draft
+ Description

Description Summary

The software uses externally-controlled format strings in printf-style functions, which can lead to buffer overflows or data representation problems.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C: (Often)

C++: (Often)

Perl: (Rarely)

Languages that support format strings

+ Modes of Introduction

The programmer rarely intends for a format string to be user-controlled at all. This weakness is frequently introduced in code that constructs log messsages, where a constant format string is omitted.

In cases such as localization and internationalization, the language-specific message repositories could be an avenue for exploitation, but the format string issue would be resultant, since attacker control of those repositories would also allow modification of message length, format, and content.

+ Common Consequences
ScopeEffect
Confidentiality

Format string problems allow for information disclosure which can severely simplify exploitation of the program.

Access Control

Format string problems can result in the execution of arbitrary code.

+ Likelihood of Exploit

Very High

+ Detection Factors

Since format strings often occur in rarely-occurring erroneous conditions (e.g. for error message logging), they can be difficult to detect using black box methods. It is highly likely that many latent issues exist in executables that do not have associated source code (or equivalent source).

+ Demonstrative Examples

Example 1

The following example is exploitable, due to the printf() call in the printWrapper() function. Note: The stack buffer was added to make exploitation more simple.

(Bad Code)
C
#include <stdio.h>
void printWrapper(char *string) {
printf(string);
}
int main(int argc, char **argv) {
char buf[5012];
memcpy(buf, argv[1], 5012);
printWrapper(argv[1]);
return (0);
}

Example 2

The following code copies a command line argument into a buffer using snprintf().

(Bad Code)
C
int main(int argc, char **argv){
char buf[128];
...
snprintf(buf,128,argv[1]);
}

This code allows an attacker to view the contents of the stack and write to the stack using a command line argument containing a sequence of formatting directives. The attacker can read from the stack by providing more formatting directives, such as %x, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.) By using the %n formatting directive, the attacker can write to the stack, causing snprintf() to write the number of bytes output thus far to the specified argument (rather than reading a value from the argument, which is the intended behavior). A sophisticated version of this attack will use four staggered writes to completely control the value of a pointer on the stack.

Example 3

Certain implementations make more advanced attacks even easier by providing format directives that control the location in memory to read from or write to. An example of these directives is shown in the following code, written for glibc:

(Bad Code)
C
printf("%d %d %1$d %1$d\n", 5, 9);

This code produces the following output: 5 9 5 5 It is also possible to use half-writes (%hn) to accurately control arbitrary DWORDS in memory, which greatly reduces the complexity needed to execute an attack that would otherwise require four staggered writes, such as the one mentioned in the first example.

+ Observed Examples
ReferenceDescription
CVE-2002-1825format string in Perl program
CVE-2001-0717format string in bad call to syslog function
CVE-2002-0573format string in bad call to syslog function
CVE-2002-1788format strings in NNTP server responses
CVE-2007-2027Chain: untrusted search path enabling resultant format string by loading malicious internationalization messages
+ Potential Mitigations
PhaseDescription
Requirements

Choose a language that is not subject to this flaw.

Implementation

Ensure that all format string functions are passed a static string which cannot be controlled by the user and that the proper number of arguments are always sent to that function as well. If at all possible, use functions that do not support the %n operator in format strings.

Build: Heed the warnings of compilers and linkers, since they may alert you to improper usage.

+ Other Notes

While Format String vulnerabilities typically fall under the Buffer Overflow category, technically they are not overflowed buffers. The Format String vulnerability is fairly new (circa 1999) and stems from the fact that there is no realistic way for a function that takes a variable number of arguments to determine just how many arguments were passed in. The most common functions that take a variable number of arguments, including C-runtime functions, are the printf() family of calls. The Format String problem appears in a number of ways. A *printf() call without a format specifier is dangerous and can be exploited. For example, printf(input); is exploitable, while printf(y, input); is not exploitable in that context. The result of the first call, used incorrectly, allows for an attacker to be able to peek at stack memory since the input string will be used as the format specifier. The attacker can stuff the input string with format specifiers and begin reading stack values, since the remaining parameters will be pulled from the stack. Worst case, this improper use may give away enough control to allow an arbitrary value (or values in the case of an exploit program) to be written into the memory of the running program

Frequently targeted entities are file names, process names, identifiers

Format string problems are a classic C/C++ issue that are now rare due to the ease of discovery. One main reason format string vulnerabilities can be exploited is due to the %n operator. The %n operator will write the number of characters, which have been printed by the format string therefore far, to the memory pointed to by its argument. Through skilled creation of a format string, a malicious user may use values on the stack to create a write-what-where condition. Once this is achieved, he can execute arbitrary code. Other operators can be used as well; for example, a %9999s operator could also trigger a buffer overflow, or when used in file-formatting functions like fprintf, it can generate a much larger output than intended.

+ 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
Seven Pernicious Kingdoms (primary)700
ChildOfWeakness ClassWeakness Class74Failure to Sanitize Data into a Different Plane ('Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
PeerOfWeakness BaseWeakness Base123Write-what-where Condition
Research Concepts1000
ChildOfCategoryCategory133String Errors
Development Concepts699
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory726OWASP Top Ten 2004 Category A5 - Buffer Overflows
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory743CERT C Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
+ Research Gaps

Format string issues are under-studied for languages other than C. Memory or disk consumption, control flow or variable alteration, and data corruption may result from format string exploitation in applications written in other languages such as Perl, PHP, Python, etc.

+ Affected Resources
  • Memory
+ Functional Areas
  • logging
  • errors
  • general output
+ Causal Nature

Implicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERFormat string vulnerability
7 Pernicious KingdomsFormat String
CLASPFormat string problem
CERT C Secure CodingFIO30-CExactExclude user input from format strings
OWASP Top Ten 2004A1CWE More SpecificUnvalidated Input
CERT C Secure CodingFIO30-CExclude user input from format strings
+ White Box Definitions

A weakness where the code path has:

1. start statement that accepts input

2. end statement that passes a format string to format string function where

a. the input data is part of the format string and

b. the format string is undesirable

Where "undesirable" is defined through the following scenarios:

1. not validated

2. incorrectly validated

+ References
Steve Christey. "Format String Vulnerabilities in Perl Programs". <http://www.securityfocus.com/archive/1/418460/30/0/threaded>.
Hal Burch and Robert C. Seacord. "Programming Language Format String Vulnerabilities". <http://www.ddj.com/dept/security/197002914>.
Tim Newsham. "Format String Attacks". Guardent. September 2000. <http://www.lava.net/~newsham/format-string-attacks.pdf>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-08-01KDM AnalyticsExternal
added/updated white box definitions
2008-09-08CWE Content TeamMITREInternal
updated Applicable Platforms, Common Consequences, Detection Factors, Modes of Introduction, Relationships, Other Notes, Research Gaps, Taxonomy Mappings, Weakness Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy Mappings
2009-03-10CWE Content TeamMITREInternal
updated Relationships
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative Examples
2009-07-17KDM AnalyticsExternal
Improved the White Box Definition
2009-07-27CWE Content TeamMITREInternal
updated White Box Definitions
 
Unrestricted Externally Accessible Lock
Definition in a New Window Definition in a New Window
Weakness ID: 412 (Weakness Base)Status: Incomplete
+ Description

Description Summary

The software properly checks for the existence of a lock, but the lock can be externally controlled or influenced by an actor that is outside of the intended sphere of control.

Extended Description

This prevents the software from acting on associated resources or performing other behaviors that are controlled by the presence of the lock. Relevant locks might include an exclusive lock or mutex, or modifying a shared resource that is treated as a lock. If the lock can be held for an indefinite period of time, then the denial of service could be permanent.

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

Languages

All

+ Common Consequences
ScopeEffect
Availability

When an attacker can control a lock, the program may wait indefinitely until the attacker releases the lock, causing a denial of service to other users of the program. This is especially problematic if there is a blocking operation on the lock.

+ Detection Factors
White Box:

Automated code analysis techniques might not be able to reliably detect this weakness, since the application's behavior and general security model dictate which resource locks are critical. Interpretation of the weakness might require knowledge of the environment, e.g. if the existence of a file is used as a lock, but the file is created in a world-writable directory.

+ Observed Examples
ReferenceDescription
CVE-2001-0682Program can not execute when attacker obtains a mutex.
CVE-2002-1914Program can not execute when attacker obtains a lock on a critical output file.
CVE-2002-1915Program can not execute when attacker obtains a lock on a critical output file.
CVE-2002-0051Critical file can be opened with exclusive read access by user, preventing application of security policy. Possibly related to improper permissions, large-window race condition.
CVE-2000-0338Chain: predictable file names used for locking, allowing attacker to create the lock beforehand. Resultant from permissions and randomness.
CVE-2000-1198Chain: Lock files with predictable names. Resultant from randomness.
CVE-2002-1869Product does not check if it can write to a log file, allowing attackers to avoid logging by accessing the file using an exclusive lock. Overlaps unchecked error condition. This is not quite CWE-412, but close.
+ Potential Mitigations
PhaseDescription
Architecture and Design
Implementation

Use any access control that is offered by the functionality that is offering the lock.

Architecture and Design
Implementation

Use unpredictable names or identifiers for the locks. This might not always be possible or feasible.

Architecture and Design

Consider modifying your code to use non-blocking synchronization methods.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
CanAlsoBeWeakness BaseWeakness Base410Insufficient Resource Pool
Research Concepts1000
ChildOfCategoryCategory411Resource Locking Problems
Development Concepts699
ChildOfWeakness BaseWeakness Base667Insufficient Locking
Research Concepts (primary)1000
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
Weaknesses in OWASP Top Ten (2004) (primary)711
MemberOfViewView630Weaknesses Examined by SAMATE
Weaknesses Examined by SAMATE (primary)630
+ Relationship Notes

This overlaps Insufficient Resource Pool when the "pool" is of size 1. It can also be resultant from race conditions, although the timing window could be quite large in some cases.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUnrestricted Critical Resource Lock
7 Pernicious KingdomsDeadlock
OWASP Top Ten 2004A9CWE More SpecificDenial of Service
+ White Box Definitions

A weakness where:

1. either an end statement performs a blocking operation on an externally accessible lock or

2. a code path has

2.1. the start statement that performs a non-blocking operation on an externally accessible lock and

2.2. the end statement that is a condition which checks that the lock operation failed and that either

2.2.1. leads to the start statement or

2.2.2. leads to abnormal termination.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Contributions
Contribution DateContributorOrganizationSource
2008-08-29KDM AnalyticsFeedback
suggested clarification of description and observed examples, which were vague and inconsistent.
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential Mitigations, 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 Common Consequences, Description, Detection Factors, Relationships, Observed Example, Relationship Notes, Taxonomy Mappings