CWE

Common Weakness Enumeration

A Community-Developed List of Software Weakness Types

CWE/SANS Top 25 Most Dangerous Software Errors
Home > CWE List > VIEW SLICE: CWE-884: CWE Cross-section (2.11)  
ID

CWE VIEW: CWE Cross-section

View ID: 884
Structure: Explicit Slice
Status: Incomplete
Presentation Filter:
+ View Data

View Objective

This view contains a selection of weaknesses that represent the variety of weaknesses that are captured in CWE, at a level of abstraction that is likely to be useful to most audiences. It can be used by researchers to determine how broad their theories, models, or tools are. It will also be used by the CWE content team in 2012 to focus quality improvement efforts for individual CWE entries.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
HasMemberWeakness BaseWeakness Base14Compiler Removal of Code to Clear Buffers
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base23Relative Path Traversal
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base36Absolute Path Traversal
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base41Improper Resolution of Path Equivalence
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base59Improper Link Resolution Before File Access ('Link Following')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base78Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base79Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base88Argument Injection or Modification
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base89Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base90Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class94Improper Control of Generation of Code ('Code Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base95Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base96Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base99Improper Control of Resource Identifiers ('Resource Injection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base113Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base117Improper Output Neutralization for Logs
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base120Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base129Improper Validation of Array Index
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base131Incorrect Calculation of Buffer Size
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base134Use of Externally-Controlled Format String
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base135Incorrect Calculation of Multi-Byte String Length
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base170Improper Null Termination
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant173Improper Handling of Alternate Encoding
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant174Double Decoding of the Same Data
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant175Improper Handling of Mixed Encoding
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base179Incorrect Behavior Order: Early Validation
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class185Incorrect Regular Expression
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base190Integer Overflow or Wraparound
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base191Integer Underflow (Wrap or Wraparound)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base193Off-by-one Error
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class203Information Exposure Through Discrepancy
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base209Information Exposure Through an Error Message
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base212Improper Cross-boundary Removal of Sensitive Data
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base222Truncation of Security-relevant Information
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base223Omission of Security-relevant Information
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class228Improper Handling of Syntactically Invalid Structure
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant244Improper Clearing of Heap Memory Before Release ('Heap Inspection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base248Uncaught Exception
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class250Execution with Unnecessary Privileges
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base252Unchecked Return Value
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base253Incorrect Check of Function Return Value
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant262Not Using Password Aging
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base263Password Aging with Long Expiration
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base266Incorrect Privilege Assignment
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base267Privilege Defined With Unsafe Actions
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base268Privilege Chaining
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base270Privilege Context Switching Error
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class271Privilege Dropping / Lowering Errors
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base273Improper Check for Dropped Privileges
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base283Unverified Ownership
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base290Authentication Bypass by Spoofing
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base294Authentication Bypass by Capture-replay
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base296Improper Following of a Certificate's Chain of Trust
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant299Improper Check for Certificate Revocation
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class300Channel Accessible by Non-Endpoint ('Man-in-the-Middle')
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant301Reflection Attack in an Authentication Protocol
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base304Missing Critical Step in Authentication
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant306Missing Authentication for Critical Function
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base307Improper Restriction of Excessive Authentication Attempts
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base308Use of Single-factor Authentication
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base312Cleartext Storage of Sensitive Information
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base319Cleartext Transmission of Sensitive Information
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base322Key Exchange without Entity Authentication
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base323Reusing a Nonce, Key Pair in Encryption
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base325Missing Required Cryptographic Step
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base327Use of a Broken or Risky Cryptographic Algorithm
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base331Insufficient Entropy
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base334Small Space of Random Values
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class335PRNG Seed Error
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base338Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base341Predictable from Observable State
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base347Improper Verification of Cryptographic Signature
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base348Use of Less Trusted Source
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base349Acceptance of Extraneous Untrusted Data With Trusted Data
CWE Cross-section (primary)884
HasMemberCompound Element: CompositeCompound Element: Composite352Cross-Site Request Forgery (CSRF)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base353Missing Support for Integrity Check
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base354Improper Validation of Integrity Check Value
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base364Signal Handler Race Condition
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base367Time-of-check Time-of-use (TOCTOU) Race Condition
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base369Divide By Zero
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class390Detection of Error Condition Without Action
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base392Missing Report of Error Condition
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base393Return of Wrong Status Code
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base400Uncontrolled Resource Consumption ('Resource Exhaustion')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base406Insufficient Control of Network Message Volume (Network Amplification)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base407Algorithmic Complexity
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base408Incorrect Behavior Order: Early Amplification
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base409Improper Handling of Highly Compressed Data (Data Amplification)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base434Unrestricted Upload of File with Dangerous Type
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base444Inconsistent Interpretation of HTTP Requests ('HTTP Request Smuggling')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base451User Interface (UI) Misrepresentation of Critical Information
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base453Insecure Default Variable Initialization
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base454External Initialization of Trusted Variables or Data Stores
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base455Non-exit on Failed Initialization
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base456Missing Initialization of a Variable
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant467Use of sizeof() on a Pointer Type
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base468Incorrect Pointer Scaling
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base469Use of Pointer Subtraction to Determine Size
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base470Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base476NULL Pointer Dereference
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant478Missing Default Case in Switch Statement
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base480Use of Incorrect Operator
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant483Incorrect Block Delimitation
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base484Omitted Break Statement in Switch
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant486Comparison of Classes by Name
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base494Download of Code Without Integrity Check
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant495Private Array-Typed Field Returned From A Public Method
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant496Public Data Assigned to Private Array-Typed Field
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant498Cloneable Class Containing Sensitive Information
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant499Serializable Class Containing Sensitive Data
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant502Deserialization of Untrusted Data
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base521Weak Password Requirements
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base522Insufficiently Protected Credentials
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant546Suspicious Comment
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant547Use of Hard-coded, Security-relevant Constants
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant561Dead Code
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant563Assignment to Variable without Use ('Unused Variable')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base567Unsynchronized Access to Shared Data in a Multithreaded Context
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base587Assignment of a Fixed Address to a Pointer
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base595Comparison of Object References Instead of Object Contents
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant601URL Redirection to Untrusted Site ('Open Redirect')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base602Client-Side Enforcement of Server-Side Security
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base605Multiple Binds to the Same Port
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant617Reachable Assertion
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base621Variable Extraction Error
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base627Dynamic Variable Evaluation
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base628Function Call with Incorrectly Specified Arguments
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class642External Control of Critical State Data
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base648Incorrect Use of Privileged APIs
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base667Improper Locking
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base672Operation on a Resource after Expiration or Release
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base674Uncontrolled Recursion
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base676Use of Potentially Dangerous Function
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base681Incorrect Conversion between Numeric Types
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base698Execution After Redirect (EAR)
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base708Incorrect Ownership Assignment
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class732Incorrect Permission Assignment for Critical Resource
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class756Missing Custom Error Page
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base763Release of Invalid Pointer or Reference
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base770Allocation of Resources Without Limits or Throttling
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base772Missing Release of Resource after Effective Lifetime
CWE Cross-section (primary)884
HasMemberWeakness VariantWeakness Variant783Operator Precedence Logic Error
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base786Access of Memory Location Before Start of Buffer
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base788Access of Memory Location After End of Buffer
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base798Use of Hard-coded Credentials
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base805Buffer Access with Incorrect Length Value
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base807Reliance on Untrusted Inputs in a Security Decision
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base822Untrusted Pointer Dereference
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base825Expired Pointer Dereference
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class829Inclusion of Functionality from Untrusted Control Sphere
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base835Loop with Unreachable Exit Condition ('Infinite Loop')
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base838Inappropriate Encoding for Output Context
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base839Numeric Range Comparison Without Minimum Check
CWE Cross-section (primary)884
HasMemberWeakness BaseWeakness Base841Improper Enforcement of Behavioral Workflow
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class862Missing Authorization
CWE Cross-section (primary)884
HasMemberWeakness ClassWeakness Class863Incorrect Authorization
CWE Cross-section (primary)884
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2011-12-15 CWE Content Team MITRE Internal CWE Team
Modifications
Modification DateModifierOrganizationSource
2017-05-03CWE Content TeamMITREInternal
updated Relationships
+ View Metrics
CWEs in this viewTotal CWEs
Total157out of1006
Views0out of33
Categories0out of245
Weaknesses156out of720
Compound_Elements1out of8
View Components
View Components
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

CWE-36: Absolute Path Traversal

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

Description Summary

The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory.

Extended Description

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

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

Languages

All

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

The attacker may be able to create or overwrite critical files that are used to execute code, such as programs or libraries.

Integrity

Technical Impact: Modify files or directories

The attacker may be able to overwrite or create critical files, such as programs, libraries, or important data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, appending a new account at the end of a password file may allow an attacker to bypass authentication.

Confidentiality

Technical Impact: Read files or directories

The attacker may be able read the contents of unexpected files and expose sensitive data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, by reading a password file, the attacker could conduct brute force password guessing attacks in order to break into an account on the system.

Availability

Technical Impact: DoS: crash / exit / restart

The attacker may be able to overwrite, delete, or corrupt unexpected critical files such as programs, libraries, or important data. This may prevent the software from working at all and in the case of a protection mechanisms such as authentication, it has the potential to lockout every user of the software.

+ Demonstrative Examples

Example 1

In the example below, the path to a dictionary file is read from a system property and used to initialize a File object.

(Bad Code)
Example Language: Java 
String filename = System.getProperty("com.domain.application.dictionaryFile");
File dictionaryFile = new File(filename);

However, the path is not validated or modified to prevent it from containing absolute path sequences before creating the File object. This allows anyone who can control the system property to determine what file is used. Ideally, the path should be resolved relative to some kind of application or user home directory.

Example 2

The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet.

(Good Code)
Example Language: HTML 
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">

Choose a file to upload:
<input type="file" name="filename"/>
<br/>
<input type="submit" name="submit" value="Submit"/>

</form>

When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory.

(Bad Code)
Example Language: Java 
public class FileUploadServlet extends HttpServlet {

...

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contentType = request.getContentType();

// the starting position of the boundary header
int ind = contentType.indexOf("boundary=");
String boundary = contentType.substring(ind+9);

String pLine = new String();
String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value

// verify that content type is multipart form data
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {

// extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
...
pLine = br.readLine();
String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));
...

// output the file to the local upload directory
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) {
if (line.indexOf(boundary) == -1) {
bw.write(line);
bw.newLine();
bw.flush();
}
} //end of for loop
bw.close();

} catch (IOException ex) {...}
// output successful upload response HTML page
}
// output unsuccessful upload response HTML page
else
{...}
}
...
}

As with the previous example this code does not perform a check on the type of the file being uploaded. This could allow an attacker to upload any executable file or other file with malicious code.

Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-22, CWE-23). Depending on the executing environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or system crash.

+ Observed Examples
ReferenceDescription
Multiple FTP clients write arbitrary files via absolute paths in server responses
ZIP file extractor allows full path
Path traversal using absolute pathname
Path traversal using absolute pathname
Path traversal using absolute pathname
Arbitrary files may be overwritten via compressed attachments that specify absolute path names for the decompressed output.
Mail client allows remote attackers to overwrite arbitrary files via an e-mail message containing a uuencoded attachment that specifies the full pathname for the file to be modified.
Remote attackers can read arbitrary files via a full pathname to the target file in config parameter.
Remote attackers can read arbitrary files via an absolute pathname.
Remote attackers can read arbitrary files by specifying the drive letter in the requested URL.
FTP server allows remote attackers to list arbitrary directories by using the "ls" command and including the drive letter name (e.g. C:) in the requested pathname.
FTP server allows remote attackers to list the contents of arbitrary drives via a ls command that includes the drive letter as an argument.
Server allows remote attackers to browse arbitrary directories via a full pathname in the arguments to certain dynamic pages.
Remote attackers can read arbitrary files via an HTTP request whose argument is a filename of the form "C:" (Drive letter), "//absolute/path", or ".." .
FTP server read/access arbitrary files using "C:\" filenames
FTP server allows a remote attacker to retrieve privileged web server system information by specifying arbitrary paths in the UNC format (\\computername\sharename).
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class22Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory981SFP Secondary Cluster: Path Traversal
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant37Path Traversal: '/absolute/pathname/here'
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant38Path Traversal: '\absolute\pathname\here'
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant39Path Traversal: 'C:dirname'
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant40Path Traversal: '\\UNC\share\name\' (Windows UNC Share)
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAbsolute Path Traversal
Software Fault PatternsSFP16Path Traversal
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 9, "Filenames and Paths", Page 503.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2008-10-14CWE Content TeamMITREInternal
updated Description
2010-02-16CWE Content TeamMITREInternal
updated Demonstrative_Examples
2010-06-21CWE Content TeamMITREInternal
updated Demonstrative_Examples, Description
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2017-01-19CWE Content TeamMITREInternal
updated Related_Attack_Patterns

CWE-349: Acceptance of Extraneous Untrusted Data With Trusted Data

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

Description Summary

The software, when processing trusted data, accepts any untrusted data that is also included with the trusted data, treating the untrusted data as if it were trusted.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control
Integrity

Technical Impact: Bypass protection mechanism; Modify application data

An attacker could package untrusted data with trusted data to bypass protection mechanisms to gain access to and possibly modify sensitive data.

+ Observed Examples
ReferenceDescription
Does not verify that trusted entity is authoritative for all entities in its response.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class345Insufficient Verification of Data Authenticity
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory860CERT Java Secure Coding Section 15 - Runtime Environment (ENV)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUntrusted Data Appended with Trusted Data
CERT Java Secure CodingENV01-JPlace all security-sensitive code in a single JAR and sign and seal it
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Related_Attack_Patterns, Relationships, Taxonomy_Mappings
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Untrusted Data Appended with Trusted Data

CWE-788: Access of Memory Location After End of Buffer

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

Description Summary

The software reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer.

Extended Description

This typically occurs when a pointer or its index is decremented to a position before the buffer; when pointer arithmetic results in a position before the buffer; or when a negative index is used, which generates a position before the buffer.

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read memory

For an out-of-bounds read, the attacker may have access to sensitive information. If the sensitive information contains system details, such as the current buffers position in memory, this knowledge can be used to craft further attacks, possibly with more severe consequences.

Integrity
Availability

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

Out of bounds memory access will very likely result in the corruption of relevant memory, and perhaps instructions, possibly leading to a crash. Other attacks leading to lack of availability are possible, including putting the program into an infinite loop.

Technical Impact: Modify memory; Execute unauthorized code or commands

If the memory accessible by the attacker can be effectively controlled, it may be possible to execute arbitrary code, as with a standard buffer overflow. If the attacker can overwrite a pointer's worth of memory (usually 32 or 64 bits), he can redirect a function pointer to his own malicious code. Even when the attacker can only modify a single byte arbitrary code execution can be possible. Sometimes this is because the same problem can be exploited repeatedly to the same effect. Other times it is because the attacker can overwrite security-critical application-specific data -- such as a flag indicating whether the user is an administrator.

+ Demonstrative Examples

Example 1

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.

(Bad Code)
Example Language:
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);

/*routine that ensures user_supplied_addr is in the right format for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(hostname, hp->h_name);
}

This function allocates a buffer of 64 bytes to store the hostname, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then we may overwrite sensitive data or even relinquish control flow to the attacker.

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

Example 2

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

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

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

Example 3

This example applies an encoding procedure to an input string and stores it into a buffer.

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

The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands.

Example 4

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

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

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

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

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

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

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

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

+ Observed Examples
ReferenceDescription
Classic stack-based buffer overflow in media player using a long entry in a playlist
Heap-based buffer overflow in media player using a long entry in a playlist
large precision value in a format string triggers overflow
attacker-controlled array index leads to code execution
OS kernel trusts userland-supplied length value, allowing reading of sensitive information
Chain: integer signedness passes signed comparison, leads to heap overflow
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant121Stack-based Buffer Overflow
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant122Heap-based Buffer Overflow
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant126Buffer Over-read
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-10-21MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, Relationships
2013-02-21CWE Content TeamMITREInternal
updated Demonstrative_Examples
2014-06-23CWE Content TeamMITREInternal
updated Demonstrative_Examples
2015-12-07CWE Content TeamMITREInternal
updated Description
2017-05-03CWE Content TeamMITREInternal
updated Description

CWE-786: Access of Memory Location Before Start of Buffer

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

Description Summary

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

Extended Description

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

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read memory

For an out-of-bounds read, the attacker may have access to sensitive information. If the sensitive information contains system details, such as the current buffers position in memory, this knowledge can be used to craft further attacks, possibly with more severe consequences.

Integrity
Availability

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

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

Technical Impact: Modify memory; Execute unauthorized code or commands

If the corrupted memory can be effectively controlled, it may be possible to execute arbitrary code. If the corrupted memory is data rather than instructions, the system will continue to function with improper changes, possibly in violation of an implicit or explicit policy.

+ Demonstrative Examples

Example 1

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

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

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

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

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

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

Example 2

The following example asks a user for an offset into an array to select an item.

(Bad Code)
Example Language:

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

The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126).

Example 3

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

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

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

+ Observed Examples
ReferenceDescription
Unchecked length of SSLv2 challenge value leads to buffer underflow.
Buffer underflow from a small size value with a large buffer (length parameter inconsistency, CWE-130)
Buffer underflow from an all-whitespace string, which causes a counter to be decremented before the buffer while looking for a non-whitespace character.
Buffer underflow resultant from encoded data that triggers an integer overflow.
Product sets an incorrect buffer size limit, leading to "off-by-two" buffer underflow.
Negative value is used in a memcpy() operation, leading to buffer underflow.
Buffer underflow due to mishandled special characters
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class119Improper Restriction of Operations within the Bounds of a Memory Buffer
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness BaseWeakness Base124Buffer Underwrite ('Buffer Underflow')
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant127Buffer Under-read
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-10-21MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, Relationships

CWE-407: Algorithmic Complexity

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

Description Summary

An algorithm in a product has an inefficient worst-case computational complexity that may be detrimental to system performance and can be triggered by an attacker, typically using crafted manipulations that ensure that the worst case is being reached.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

Language-independent

+ Common Consequences
ScopeEffect
Availability

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

The typical consequence is CPU consumption, but memory consumption and consumption of other resources can also occur.

+ Likelihood of Exploit

Low to Medium

+ Observed Examples
ReferenceDescription
CPU consumption via inputs that cause many hash table collisions.
CPU consumption via inputs that cause many hash table collisions.
Product performs unnecessary processing before dropping an invalid packet.
CPU and memory consumption using many wildcards.
Product allows attackers to cause multiple copies of a program to be loaded more quickly than the program can detect that other copies are running, then exit. This type of error should probably have its own category, where teardown takes more time than initialization.
Network monitoring system allows remote attackers to cause a denial of service (CPU consumption and detection outage) via crafted network traffic, aka a "backtracking attack."
Wiki allows remote attackers to cause a denial of service (CPU consumption) by performing a diff between large, crafted pages that trigger the worst case algorithmic complexity.
Wiki allows remote attackers to cause a denial of service (CPU consumption) by performing a diff between large, crafted pages that trigger the worst case algorithmic complexity.
OS allows attackers to cause a denial of service (CPU consumption) via crafted Gregorian dates.
Memory leak by performing actions faster than the software can clear them.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class405Asymmetric Resource Consumption (Amplification)
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Functional Areas
  • Cryptography
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAlgorithmic Complexity
+ References
Crosby and Wallach. "Algorithmic Complexity Attacks". <http://www.cs.rice.edu/~scrosby/hash/CrosbyWallach_UsenixSec2003/index.html>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Other_Notes, Taxonomy_Mappings
2009-07-27CWE Content TeamMITREInternal
updated Functional_Areas, Other_Notes
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences
2009-12-28CWE Content TeamMITREInternal
updated Applicable_Platforms, Likelihood_of_Exploit
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Observed_Examples, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-770: Allocation of Resources Without Limits or Throttling

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

Description Summary

The software allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on how many resources can be allocated, in violation of the intended security policy for that actor.
+ Time of Introduction
  • Architecture and Design
  • Implementation
  • Operation
  • System Configuration
+ Applicable Platforms

Languages

Language-independent

+ Common Consequences
ScopeEffect
Availability

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

When allocating resources without limits, an attacker could prevent other systems, applications, or processes from accessing the same type of resource.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Manual Static Analysis

Manual static analysis can be useful for finding this weakness, but it might not achieve desired code coverage within limited time constraints. If denial-of-service is not considered a significant risk, or if there is strong emphasis on consequences such as code execution, then manual analysis may not focus on this weakness at all.

Fuzzing

While fuzzing is typically geared toward finding low-level implementation bugs, it can inadvertently find uncontrolled resource allocation problems. This can occur when the fuzzer generates a large number of test cases but does not restart the targeted software in between test cases. If an individual test case produces a crash, but it does not do so reliably, then an inability to limit resource allocation may be the cause.

When the allocation is directly affected by numeric inputs, then fuzzing may produce indications of this weakness.

Effectiveness: Opportunistic

Automated Dynamic Analysis

Certain automated dynamic analysis techniques may be effective in producing side effects of uncontrolled resource allocation problems, especially with resources such as processes, memory, and connections. The technique may involve generating a large number of requests to the software within a short time frame. Manual analysis is likely required to interpret the results.

Automated Static Analysis

Specialized configuration or tuning may be required to train automated tools to recognize this weakness.

Automated static analysis typically has limited utility in recognizing unlimited allocation problems, except for the missing release of program-independent system resources such as files, sockets, and processes, or unchecked arguments to memory. For system resources, automated static analysis may be able to detect circumstances in which resources are not released after they have expired, or if too much of a resource is requested at once, as can occur with memory. Automated analysis of configuration files may be able to detect settings that do not specify a maximum value.

Automated static analysis tools will not be appropriate for detecting exhaustion of custom resources, such as an intended security policy in which a bulletin board user is only allowed to make a limited number of posts per day.

+ Demonstrative Examples

Example 1

This code allocates a socket and forks each time it receives a new connection.

(Bad Code)
Example Languages: C and C++ 
sock=socket(AF_INET, SOCK_STREAM, 0);
while (1) {
newsock=accept(sock, ...);
printf("A connection has been accepted\n");
pid = fork();
}

The program does not track how many connections have been made, and it does not limit the number of connections. Because forking is a relatively expensive operation, an attacker would be able to cause the system to run out of CPU, processes, or memory by making a large number of connections. Alternatively, an attacker could consume all available connections, preventing others from accessing the system remotely.

Example 2

In the following example a server socket connection is used to accept a request to store data on the local file system using a specified filename. The method openSocketConnection establishes a server socket to accept requests from a client. When a client establishes a connection to this service the getNextMessage method is first used to retrieve from the socket the name of the file to store the data, the openFileToWrite method will validate the filename and open a file to write to on the local file system. The getNextMessage is then used within a while loop to continuously read data from the socket and output the data to the file until there is no longer any data from the socket.

(Bad Code)
Example Languages: C and C++ 
int writeDataFromSocketToFile(char *host, int port)
{

char filename[FILENAME_SIZE];
char buffer[BUFFER_SIZE];
int socket = openSocketConnection(host, port);

if (socket < 0) {
printf("Unable to open socket connection");
return(FAIL);
}
if (getNextMessage(socket, filename, FILENAME_SIZE) > 0) {
if (openFileToWrite(filename) > 0) {
while (getNextMessage(socket, buffer, BUFFER_SIZE) > 0){
if (!(writeToFile(buffer) > 0))
break;
}
}
closeFile();
}
closeSocket(socket);
}

This example creates a situation where data can be dumped to a file on the local file system without any limits on the size of the file. This could potentially exhaust file or disk resources and/or limit other clients' ability to access the service.

Example 3

In the following example, the processMessage method receives a two dimensional character array containing the message to be processed. The two-dimensional character array contains the length of the message in the first character array and the message body in the second character array. The getMessageLength method retrieves the integer value of the length from the first character array. After validating that the message length is greater than zero, the body character array pointer points to the start of the second character array of the two-dimensional character array and memory is allocated for the new body character array.

(Bad Code)
Example Languages: C and C++ 
/* process message accepts a two-dimensional character array of the form [length][body] containing the message to be processed */
int processMessage(char **message)
{
char *body;

int length = getMessageLength(message[0]);

if (length > 0) {
body = &message[1][0];
processMessageBody(body);
return(SUCCESS);
}
else {
printf("Unable to process message; invalid message length");
return(FAIL);
}
}

This example creates a situation where the length of the body character array can be very large and will consume excessive memory, exhausting system resources. This can be avoided by restricting the length of the second character array with a maximum length check

Also, consider changing the type from 'int' to 'unsigned int', so that you are always guaranteed that the number is positive. This might not be possible if the protocol specifically requires allowing negative values, or if you cannot control the return value from getMessageLength(), but it could simplify the check to ensure the input is positive, and eliminate other errors such as signed-to-unsigned conversion errors (CWE-195) that may occur elsewhere in the code.

(Good Code)
Example Languages: C and C++ 
unsigned int length = getMessageLength(message[0]);
if ((length > 0) && (length < MAX_LENGTH)) {...}

Example 4

In the following example, a server object creates a server socket and accepts client connections to the socket. For every client connection to the socket a separate thread object is generated using the ClientSocketThread class that handles request made by the client through the socket.

(Bad Code)
Example Language: Java 
public void acceptConnections() {

try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
Socket client = serverSocket.accept();
Thread t = new Thread(new ClientSocketThread(client));
t.setName(client.getInetAddress().getHostName() + ":" + counter++);
t.start();
}
serverSocket.close();

} catch (IOException ex) {...}
}

In this example there is no limit to the number of client connections and client threads that are created. Allowing an unlimited number of client connections and threads could potentially overwhelm the system and system resources.

The server should limit the number of client connections and the client threads that are created. This can be easily done by creating a thread pool object that limits the number of threads that are generated.

(Good Code)
Example Language: Java 
public static final int SERVER_PORT = 4444;
public static final int MAX_CONNECTIONS = 10;
...

public void acceptConnections() {

try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
int counter = 0;
boolean hasConnections = true;
while (hasConnections) {
hasConnections = checkForMoreConnections();
Socket client = serverSocket.accept();
Thread t = new Thread(new ClientSocketThread(client));
t.setName(client.getInetAddress().getHostName() + ":" + counter++);
ExecutorService pool = Executors.newFixedThreadPool(MAX_CONNECTIONS);
pool.execute(t);
}
serverSocket.close();

} catch (IOException ex) {...}
}

Example 5

An unnamed web site allowed a user to purchase tickets for an event. A menu option allowed the user to purchase up to 10 tickets, but the back end did not restrict the actual number of tickets that could be purchased.

Example 5 References:

Rafal Los. "Real-Life Example of a 'Business Logic Defect' (Screen Shots!)". 2011. <http://h30501.www3.hp.com/t5/Following-the-White-Rabbit-A/Real-Life-Example-of-a-Business-Logic-Defect-Screen-Shots/ba-p/22581>.
+ Observed Examples
ReferenceDescription
Language interpreter does not restrict the number of temporary files being created when handling a MIME request with a large number of parts..
Driver does not use a maximum width when invoking sscanf style functions, causing stack consumption.
Large integer value for a length property in an object causes a large amount of memory allocation.
Product allows exhaustion of file descriptors when processing a large number of TCP packets.
Communication product allows memory consumption with a large number of SIP requests, which cause many sessions to be created.
Product allows attackers to cause a denial of service via a large number of directives, each of which opens a separate window.
CMS does not restrict the number of searches that can occur simultaneously, leading to resource exhaustion.
+ Potential Mitigations

Phase: Requirements

Clearly specify the minimum and maximum expectations for capabilities, and dictate which behaviors are acceptable when resource allocation reaches limits.

Phase: Architecture and Design

Limit the amount of resources that are accessible to unprivileged users. Set per-user limits for resources. Allow the system administrator to define these limits. Be careful to avoid CWE-410.

Phase: Architecture and Design

Design throttling mechanisms into the system architecture. The best protection is to limit the amount of resources that an unauthorized user can cause to be expended. A strong authentication and access control model will help prevent such attacks from occurring in the first place, and it will help the administrator to identify who is committing the abuse. The login application should be protected against DoS attacks as much as possible. Limiting the database access, perhaps by caching result sets, can help minimize the resources expended. To further limit the potential for a DoS attack, consider tracking the rate of requests received from users and blocking requests that exceed a defined rate threshold.

Phase: Implementation

Strategy: Input Validation

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

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

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

This will only be applicable to cases where user input can influence the size or frequency of resource allocations.

Phase: Architecture and Design

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

Phase: Architecture and Design

Mitigation of resource exhaustion attacks requires that the target system either:

  • recognizes the attack and denies that user further access for a given amount of time, typically by using increasing time delays

  • uniformly throttles all requests in order to make it more difficult to consume resources more quickly than they can again be freed.

The first of these solutions is an issue in itself though, since it may allow attackers to prevent the use of the system by a particular valid user. If the attacker impersonates the valid user, he may be able to prevent the user from accessing the server in question.

The second solution can be difficult to effectively institute -- and even when properly done, it does not provide a full solution. It simply requires more resources on the part of the attacker.

Phase: Architecture and Design

Ensure that protocols have specific limits of scale placed on them.

Phases: Architecture and Design; Implementation

If the program must fail, ensure that it fails gracefully (fails closed). There may be a temptation to simply let the program fail poorly in cases such as low memory conditions, but an attacker may be able to assert control before the software has fully exited. Alternately, an uncontrolled failure could cause cascading problems with other downstream components; for example, the program could send a signal to a downstream process so the process immediately knows that a problem has occurred and has a better chance of recovery.

Ensure that all failures in resource allocation place the system into a safe posture.

Phases: Operation; Architecture and Design

Strategy: Limit Resource Consumption

Use resource-limiting settings provided by the operating system or environment. For example, when managing system resources in POSIX, setrlimit() can be used to set limits for certain types of resources, and getrlimit() can determine how many resources are available. However, these functions are not available on all operating systems.

When the current levels get close to the maximum that is defined for the application (see CWE-770), then limit the allocation of further resources to privileged users; alternately, begin releasing resources for less-privileged users. While this mitigation may protect the system from attack, it will not necessarily stop attackers from adversely impacting other users.

Ensure that the application performs the appropriate error checks and error handling in case resources become unavailable (CWE-703).

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base400Uncontrolled Resource Consumption ('Resource Exhaustion')
Development Concepts (primary)699
Research Concepts1000
ChildOfWeakness ClassWeakness Class665Improper Initialization
Research Concepts (primary)1000
ChildOfCategoryCategory8022010 Top 25 - Risky Resource Management
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory840Business Logic Errors
Development Concepts699
ChildOfCategoryCategory857CERT Java Secure Coding Section 12 - Input Output (FIO)
Weaknesses Addressed by the CERT Java Secure Coding Standard844
ChildOfCategoryCategory858CERT Java Secure Coding Section 13 - Serialization (SER)
Weaknesses Addressed by the CERT Java Secure Coding Standard844
ChildOfCategoryCategory861CERT Java Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory8672011 Top 25 - Weaknesses On the Cusp
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory876CERT C++ Secure Coding Section 08 - Memory Management (MEM)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory877CERT C++ Secure Coding Section 09 - Input Output (FIO)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory985SFP Secondary Cluster: Unrestricted Consumption
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant774Allocation of File Descriptors or Handles Without Limits or Throttling
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant789Uncontrolled Memory Allocation
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Theoretical Notes

Vulnerability theory is largely about how behaviors and resources interact. "Resource exhaustion" can be regarded as either a consequence or an attack, depending on the perspective. This entry is an attempt to reflect one of the underlying weaknesses that enable these attacks (or consequences) to take place.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT Java Secure CodingFIO04-JClose resources when they are no longer needed
CERT Java Secure CodingSER12-JAvoid memory and resource leaks during serialization
CERT Java Secure CodingMSC05-JDo not exhaust heap space
CERT C++ Secure CodingMEM12-CPPDo not assume infinite heap space
CERT C++ Secure CodingFIO42-CPPEnsure files are properly closed when they are no longer needed
+ References
Joao Antunes, Nuno Ferreira Neves and Paulo Verissimo. "Detection and Prediction of Resource-Exhaustion Vulnerabilities". Proceedings of the IEEE International Symposium on Software Reliability Engineering (ISSRE). November 2008. <http://homepages.di.fc.ul.pt/~nuno/PAPERS/ISSRE08.pdf>.
D.J. Bernstein. "Resource exhaustion". <http://cr.yp.to/docs/resources.html>.
Pascal Meunier. "Resource exhaustion". Secure Programming Educational Material. 2004. <http://homes.cerias.purdue.edu/~pmeunier/secprog/sanitized/class1/6.resource%20exhaustion.ppt>.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 17, "Protecting Against Denial of Service Attacks" Page 517. 2nd Edition. Microsoft. 2002.
Frank Kim. "Top 25 Series - Rank 22 - Allocation of Resources Without Limits or Throttling". SANS Software Security Institute. 2010-03-23. <http://blogs.sans.org/appsecstreetfighter/2010/03/23/top-25-series-rank-22-allocation-of-resources-without-limits-or-throttling/>.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 10, "Resource Limits", Page 574.. 1st Edition. Addison Wesley. 2006.
+ Maintenance Notes

"Resource exhaustion" (CWE-400) is currently treated as a weakness, although it is more like a category of weaknesses that all have the same type of consequence. While this entry treats CWE-400 as a parent in view 1000, the relationship is probably more appropriately described as a chain.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2009-05-13Internal CWE Team
Modifications
Modification DateModifierOrganizationSource
2009-07-27CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2009-10-29CWE Content TeamMITREInternal
updated Relationships
2009-12-28CWE Content TeamMITREInternal
updated Applicable_Platforms, Demonstrative_Examples, Detection_Factors, Observed_Examples, References, Time_of_Introduction
2010-02-16CWE Content TeamMITREInternal
updated Common_Consequences, Detection_Factors, Potential_Mitigations, References, Related_Attack_Patterns, Relationships
2010-04-05CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Potential_Mitigations, References
2010-09-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Demonstrative_Examples, Detection_Factors, Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Related_Attack_Patterns, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2014-06-23CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2017-05-03CWE Content TeamMITREInternal
updated Related_Attack_Patterns

CWE-88: Argument Injection or Modification

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

Description Summary

The software does not sufficiently delimit the arguments being passed to a component in another control sphere, allowing alternate arguments to be provided, leading to potentially security-relevant changes.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability
Other

Technical Impact: Execute unauthorized code or commands; Alter execution logic; Read application data; Modify application data

An attacker could include arguments that allow unintended commands or code to be executed, allow sensitive data to be read or modified or could cause other unintended behavior.

+ Demonstrative Examples

Example 1

The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system.

(Bad Code)
Example Language:
int main(int argc, char** argv) {
char cmd[CMD_MAX] = "/usr/bin/cat ";
strcat(cmd, argv[1]);
system(cmd);
}

Because the program runs with root privileges, the call to system() also executes with root privileges. If a user specifies a standard filename, the call works as expected. However, if an attacker passes a string of the form ";rm -rf /", then the call to system() fails to execute cat due to a lack of arguments and then plows on to recursively delete the contents of the root partition.

Note that if argv[1] is a very long argument, then this issue might also be subject to a buffer overflow (CWE-120).

+ Observed Examples
ReferenceDescription
Canonical Example
Web browser executes Telnet sessions using command line arguments that are specified by the web site, which could allow remote attackers to execute arbitrary commands.
Web browser allows remote attackers to execute commands by spawning Telnet with a log file option on the command line and writing arbitrary code into an executable file which is later executed.
Argument injection vulnerability in the mail function for PHP may allow attackers to bypass safe mode restrictions and modify command line arguments to the MTA (e.g. sendmail) possibly executing commands.
Help and Support center in windows does not properly validate HCP URLs, which allows remote attackers to execute arbitrary code via quotation marks in an "hcp://" URL.
Mail client does not sufficiently filter parameters of mailto: URLs when using them as arguments to mail executable, which allows remote attackers to execute arbitrary programs.
Web browser doesn't filter "-" when invoking various commands, allowing command-line switches to be specified.
Mail client allows remote attackers to execute arbitrary code via a URI that uses a UNC network share pathname to provide an alternate configuration file.
SSH URI handler for web browser allows remote attackers to execute arbitrary code or conduct port forwarding via the a command line option.
Web browser doesn't filter "-" when invoking various commands, allowing command-line switches to be specified.
Argument injection vulnerability in TellMe 1.2 and earlier allows remote attackers to modify command line arguments for the Whois program and obtain sensitive information via "--" style options in the q_Host parameter.
Beagle before 0.2.5 can produce certain insecure command lines to launch external helper applications while indexing, which allows attackers to execute arbitrary commands. NOTE: it is not immediately clear whether this issue involves argument injection, shell metacharacters, or other issues.
Argument injection vulnerability in Internet Explorer 6 for Windows XP SP2 allows user-assisted remote attackers to modify command line arguments to an invoked mail client via " (double quote) characters in a mailto: scheme handler, as demonstrated by launching Microsoft Outlook with an arbitrary filename as an attachment. NOTE: it is not clear whether this issue is implementation-specific or a problem in the Microsoft API.
Argument injection vulnerability in Mozilla Firefox 1.0.6 allows user-assisted remote attackers to modify command line arguments to an invoked mail client via " (double quote) characters in a mailto: scheme handler, as demonstrated by launching Microsoft Outlook with an arbitrary filename as an attachment. NOTE: it is not clear whether this issue is implementation-specific or a problem in the Microsoft API.
Argument injection vulnerability in Avant Browser 10.1 Build 17 allows user-assisted remote attackers to modify command line arguments to an invoked mail client via " (double quote) characters in a mailto: scheme handler, as demonstrated by launching Microsoft Outlook with an arbitrary filename as an attachment. NOTE: it is not clear whether this issue is implementation-specific or a problem in the Microsoft API.
Argument injection vulnerability in the URI handler in Skype 2.0.*.104 and 2.5.*.0 through 2.5.*.78 for Windows allows remote authorized attackers to download arbitrary files via a URL that contains certain command-line switches.
Argument injection vulnerability in WinSCP 3.8.1 build 328 allows remote attackers to upload or download arbitrary files via encoded spaces and double-quote characters in a scp or sftp URI.
Argument injection vulnerability in the Windows Object Packager (packager.exe) in Microsoft Windows XP SP1 and SP2 and Server 2003 SP1 and earlier allows remote user-assisted attackers to execute arbitrary commands via a crafted file with a "/" (slash) character in the filename of the Command Line property, followed by a valid file extension, which causes the command before the slash to be executed, aka "Object Packager Dialogue Spoofing Vulnerability."
Argument injection vulnerability in HyperAccess 8.4 allows user-assisted remote attackers to execute arbitrary vbscript and commands via the /r option in a telnet:// URI, which is configured to use hawin32.exe.
Argument injection vulnerability in the telnet daemon (in.telnetd) in Solaris 10 and 11 (SunOS 5.10 and 5.11) misinterprets certain client "-f" sequences as valid requests for the login program to skip authentication, which allows remote attackers to log into certain accounts, as demonstrated by the bin account.
Language interpreter's mail function accepts another argument that is concatenated to a string used in a dangerous popen() call. Since there is no neutralization of this argument, both OS Command Injection (CWE-78) and Argument Injection (CWE-88) are possible.
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Input Validation

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

Phase: Implementation

Strategy: Input Validation

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

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

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

Phase: Implementation

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

Phase: Implementation

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

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

Phase: Implementation

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

Phase: Implementation

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

Phase: Testing

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

Phase: Testing

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

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class77Improper Neutralization of Special Elements used in a Command ('Command Injection')
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory634Weaknesses that Affect System Processes
Resource-specific Weaknesses (primary)631
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
ChildOfCategoryCategory810OWASP Top Ten 2010 Category A1 - Injection
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfCategoryCategory875CERT C++ Secure Coding Section 07 - Characters and Strings (STR)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory878CERT C++ Secure Coding Section 10 - Environment (ENV)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory929OWASP Top Ten 2013 Category A1 - Injection
Weaknesses in OWASP Top Ten (2013) (primary)928
ChildOfCategoryCategory990SFP Secondary Cluster: Tainted Input to Command
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanAlsoBeWeakness BaseWeakness Base78Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
Research Concepts1000
+ Relationship Notes

At one layer of abstraction, this can overlap other weaknesses that have whitespace problems, e.g. injection of javascript into attributes of HTML tags.

+ Affected Resources
  • System Process
+ Causal Nature

Explicit

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERArgument Injection or Modification
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
WASC30Mail Command Injection
CERT C++ Secure CodingSTR02-CPPSanitize data passed to complex subsystems
CERT C++ Secure CodingENV03-CPPSanitize the environment when invoking external programs
CERT C++ Secure CodingENV04-CPPDo not call system() if you do not need a command processor
+ References
Steven Christey. "Argument injection issues". <http://www.securityfocus.com/archive/1/archive/1/460089/100/100/threaded>.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 10, "The Argument Array", Page 567.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings, Weakness_Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Observed_Examples, Relationships, Taxonomy_Mappings
2009-07-27CWE Content TeamMITREInternal
updated Other_Notes, Relationship_Notes
2009-10-29CWE Content TeamMITREInternal
updated Observed_Examples
2010-02-16CWE Content TeamMITREInternal
updated Potential_Mitigations, Relationships, Taxonomy_Mappings
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated Observed_Examples, Relationships
2010-09-27CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, References, Related_Attack_Patterns, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-06-23CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2015-12-07CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships

CWE-587: Assignment of a Fixed Address to a Pointer

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

Description Summary

The software sets a pointer to a specific address other than NULL or 0.

Extended Description

Using a fixed address is not portable because that address will probably not be valid in all environments or platforms.

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

Languages

C

C++

C#

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

If one executes code at a known location, an attacker might be able to inject code there beforehand.

Availability

Technical Impact: DoS: crash / exit / restart

If the code is ported to another platform or environment, the pointer is likely to be invalid and cause a crash.

Confidentiality
Integrity

Technical Impact: Read memory; Modify memory

The data at a known pointer location can be easily read or influenced by an attacker.

+ Demonstrative Examples

Example 1

This code assumes a particular function will always be found at a particular address. It assigns a pointer to that address and calls the function.

(Bad Code)
Example Language:
int (*pt2Function) (float, char, char)=0x08040000;
int result2 = (*pt2Function) (12, 'a', 'b');
// Here we can inject code to execute.

The same function may not always be found at the same memory address. This could lead to a crash, or an attacker may alter the memory at the expected address, leading to arbitrary code execution.

+ Potential Mitigations

Phase: Implementation

Never set a pointer to a fixed address.

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base344Use of Invariant Value in Dynamically Changing Context
Research Concepts (primary)1000
ChildOfCategoryCategory465Pointer Issues
Development Concepts (primary)699
ChildOfCategoryCategory738CERT C Secure Coding Section 04 - Integers (INT)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfWeakness ClassWeakness Class758Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
Research Concepts1000
ChildOfCategoryCategory872CERT C++ Secure Coding Section 04 - Integers (INT)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory998SFP Secondary Cluster: Glitch in Computation
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT C Secure CodingINT11-CTake care when converting from pointer to integer or integer to pointer
CERT C++ Secure CodingINT11-CPPTake care when converting from pointer to integer or integer to pointer
Software Fault PatternsSFP1Glitch in computation
+ White Box Definitions

A weakness where code path has:

1. end statement that assigns an address to a pointer

2. start statement that defines the address and the address is a literal value

+ Content History
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, Description, Relationships, Other_Notes, Weakness_Ordinalities
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-03-10CWE Content TeamMITREInternal
updated Relationships
2009-07-27CWE Content TeamMITREInternal
updated Common_Consequences, Description, Other_Notes
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings

CWE-563: Assignment to Variable without Use ('Unused Variable')

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

Description Summary

The variable's value is assigned but never used, making it a dead store.

Extended Description

After the assignment, the variable is either assigned another value or goes out of scope. It is likely that the variable is simply vestigial, but it is also possible that the unused variable points out a bug.

+ Time of Introduction
  • Implementation
+ Common Consequences
ScopeEffect
Other

Technical Impact: Quality degradation; Varies by context

This weakness could be an indication of a bug in the program or a deprecated variable that was not removed and is an indication of poor quality. This could lead to further bugs and the introduction of weaknesses.

+ Demonstrative Examples

Example 1

The following code excerpt assigns to the variable r and then overwrites the value without using it.

(Bad Code)
Example Language:
r = getName();
r = getNewBuffer(buf);
+ Potential Mitigations

Phase: Implementation

Remove unused variables from the code.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory747CERT C Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory883CERT C++ Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory886SFP Primary Cluster: Unused entities
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
Anonymous Tool Vendor (under NDA)
CERT C Secure CodingMSC00-CCompile cleanly at high warning levels
CERT C++ Secure CodingMSC00-CPPCompile cleanly at high warning levels
Software Fault PatternsSFP2Unused Entities
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
Anonymous Tool Vendor (under NDA)Externally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-06-23CWE Content TeamMITREInternal
updated Common_Consequences, Description, Name, Other_Notes
2014-07-30CWE Content TeamMITREInternal
updated Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2014-06-23Unused Variable

CWE-294: Authentication Bypass by Capture-replay

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

Description Summary

A capture-replay flaw exists when the design of the software makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).

Extended Description

Capture-replay attacks are common and can be difficult to defeat without cryptography. They are a subset of network injection attacks that rely on observing previously-sent valid commands, then changing them slightly if necessary and resending the same commands to the server.

+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control

Technical Impact: Gain privileges / assume identity

Messages sent with a capture-relay attack allow access to resources which are not otherwise accessible without proper authentication.

+ Likelihood of Exploit

High

+ Observed Examples
ReferenceDescription
product authentication succeeds if user-provided MD5 hash matches the hash in its database; this can be subjected to replay attacks.
Chain: cleartext transmission of the MD5 hash of password (CWE-319) enables attacks against a server that is susceptible to replay (CWE-294).
+ Potential Mitigations

Phase: Architecture and Design

Utilize some sequence or time stamping functionality along with a checksum which takes this into account in order to ensure that messages can be parsed only once.

Phase: Architecture and Design

Since any attacker who can listen to traffic can see sequence numbers, it is necessary to sign messages with some kind of cryptography to ensure that sequence numbers are not simply doctored along with content.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class287Improper Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory956SFP Secondary Cluster: Channel Attack
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAuthentication bypass by replay
CLASPCapture-replay
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-09-08CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Other_Notes, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2009-07-27CWE Content TeamMITREInternal
updated Description, Other_Notes, Potential_Mitigations
2009-10-29CWE Content TeamMITREInternal
updated Observed_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples
2012-05-11CWE Content TeamMITREInternal
updated Observed_Examples, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships
2017-05-03CWE Content TeamMITREInternal
updated Relationships

CWE-290: Authentication Bypass by Spoofing

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

Description Summary

This attack-focused weakness is caused by improperly implemented authentication schemes that are subject to spoofing attacks.
+ Time of Introduction
  • Architecture and Design
  • Implementation
+ Common Consequences
ScopeEffect
Access Control

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

This weakness can allow an attacker to access resources which are not otherwise accessible without proper authentication.

+ Demonstrative Examples

Example 1

The following code authenticates users.

(Bad Code)
Example Language: Java 
String sourceIP = request.getRemoteAddr();
if (sourceIP != null && sourceIP.equals(APPROVED_IP)) {
authenticated = true;
}

The authentication mechanism implemented relies on an IP address for source validation. If an attacker is able to spoof the IP, they may be able to bypass the authentication mechanism.

Example 2

Both of these examples check if a request is from a trusted address before responding to the request.

(Bad Code)
Example Languages: C and C++ 
sd = socket(AF_INET, SOCK_DGRAM, 0);
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
servr.sin_port = htons(1008);
bind(sd, (struct sockaddr *) & serv, sizeof(serv));

while (1) {
memset(msg, 0x0, MAX_MSG);
clilen = sizeof(cli);
if (inet_ntoa(cli.sin_addr)==getTrustedAddress()) {
n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *) & cli, &clilen);
}
}
(Bad Code)
Example Language: Java 
while(true) {
DatagramPacket rp=new DatagramPacket(rData,rData.length);
outSock.receive(rp);
String in = new String(p.getData(),0, rp.getLength());
InetAddress clientIPAddress = rp.getAddress();
int port = rp.getPort();

if (isTrustedAddress(clientIPAddress) & secretKey.equals(in)) {
out = secret.getBytes();
DatagramPacket sp =new DatagramPacket(out,out.length, IPAddress, port); outSock.send(sp);
}
}

The code only verifies the address as stored in the request packet. An attacker can spoof this address, thus impersonating a trusted client

Example 3

The following code samples use a DNS lookup in order to decide whether or not an inbound request is from a trusted host. If an attacker can poison the DNS cache, they can gain trusted status.

(Bad Code)
Example Language:
struct hostent *hp;struct in_addr myaddr;
char* tHost = "trustme.example.com";
myaddr.s_addr=inet_addr(ip_addr_string);

hp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET);
if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) {
trusted = true;
} else {
trusted = false;
}
(Bad Code)
Example Language: Java 
String ip = request.getRemoteAddr();
InetAddress addr = InetAddress.getByName(ip);
if (addr.getCanonicalHostName().endsWith("trustme.com")) {
trusted = true;
}
(Bad Code)
Example Language: C# 
IPAddress hostIPAddress = IPAddress.Parse(RemoteIpAddress);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
if (hostInfo.HostName.EndsWith("trustme.com")) {
trusted = true;
}

IP addresses are more reliable than DNS names, but they can also be spoofed. Attackers can easily forge the source IP address of the packets they send, but response packets will return to the forged IP address. To see the response packets, the attacker has to sniff the traffic between the victim machine and the forged IP address. In order to accomplish the required sniffing, attackers typically attempt to locate themselves on the same subnet as the victim machine. Attackers may be able to circumvent this requirement by using source routing, but source routing is disabled across much of the Internet today. In summary, IP address verification can be a useful part of an authentication scheme, but it should not be the single factor required for authentication.

+ Observed Examples
ReferenceDescription
VOIP product allows authentication bypass using 127.0.0.1 in the Host header.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class287Improper Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory956SFP Secondary Cluster: Channel Attack
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant291Reliance on IP Address for Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant293Using Referer Field for Authentication
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant350Reliance on Reverse DNS Resolution for a Security-Critical Action
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base602Client-Side Enforcement of Server-Side Security
Research Concepts1000
CanAlsoBeWeakness BaseWeakness Base358Improperly Implemented Security Check for Standard
Research Concepts1000
+ Relationship Notes

This can be resultant from insufficient verification.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERAuthentication bypass by spoofing
+ References
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 3, "Spoofing and Identification", Page 72.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Relationship_Notes, Taxonomy_Mappings
2009-07-27CWE Content TeamMITREInternal
updated Relationship_Notes
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, References, Related_Attack_Patterns, Relationships
2013-07-17CWE Content TeamMITREInternal
updated Relationships
2014-02-18CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2014-07-30CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
2017-05-03CWE Content TeamMITREInternal
updated Relationships

CWE-805: Buffer Access with Incorrect Length Value

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

Description Summary

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

Extended Description

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

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C: (Often)

C++: (Often)

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

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

Availability

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

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

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Automated Static Analysis

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

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

Effectiveness: High

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

Automated Dynamic Analysis

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

Effectiveness: Moderate

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

Manual Analysis

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

+ Demonstrative Examples

Example 1

This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer.

(Bad Code)
Example Language:
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr;
char hostname[64];
in_addr_t inet_addr(const char *cp);

/*routine that ensures user_supplied_addr is in the right format for conversion */
validate_addr_form(user_supplied_addr);
addr = inet_addr(user_supplied_addr);
hp = gethostbyaddr( addr, sizeof(struct in_addr), AF_INET);
strcpy(hostname, hp->h_name);
}

This function allocates a buffer of 64 bytes to store the hostname under the assumption that the maximum length value of hostname is 64 bytes, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then we may overwrite sensitive data or even relinquish control flow to the attacker.

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

Example 2

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

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

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

Example 3

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

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

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

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

Example 4

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

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

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

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

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

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

return success;
}

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

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

Phase: Requirements

Strategy: Language Selection

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

For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.

Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

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

Examples include the Safe C String Library (SafeStr) by Messier and Viega [R.805.6], and the Strsafe.h library from Microsoft [R.805.7]. These libraries provide safer versions of overflow-prone string-handling functions.

This is not a complete solution, since many buffer overflows are not related to strings.

Phase: Build and Compilation

Strategy: Compilation or Build Hardening

Run or compile the software using features or extensions that automatically provide a protection mechanism that mitigates or eliminates buffer overflows.

For example, certain compilers and extensions provide automatic buffer overflow detection mechanisms that are built into the compiled code. Examples include the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice.

Effectiveness: Defense in Depth

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

Phase: Implementation

Consider adhering to the following rules when allocating and managing an application's memory:

  • Double check that your buffer is as large as you specify.

  • When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.

  • Check buffer boundaries if accessing the buffer in a loop and make sure you are not in danger of writing past the allocated space.

  • If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.

Phase: Architecture and Design

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

Phase: Operation

Strategy: Environment Hardening

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

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

Effectiveness: Defense in Depth

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

Phase: Operation

Strategy: Environment Hardening

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

Effectiveness: Defense in Depth

This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

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

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

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

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

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

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

Effectiveness: Limited

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

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

Explicit

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

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

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

Description Summary

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

Extended Description

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

+ Alternate Terms
buffer overrun:

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

Unbounded Transfer
+ Terminology Notes

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

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C

C++

Assembly

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

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

Availability

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

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

+ Likelihood of Exploit

High to Very High

+ Detection Methods

Automated Static Analysis

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

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

Effectiveness: High

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

Automated Dynamic Analysis

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

Manual Analysis

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

Automated Static Analysis - Binary / Bytecode

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

Highly cost effective:

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

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

Effectiveness: SOAR High

Manual Static Analysis - Binary / Bytecode

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

Cost effective for partial coverage:

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

Effectiveness: SOAR Partial

Dynamic Analysis with automated results interpretation

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

Cost effective for partial coverage:

  • Web Application Scanner

  • Web Services Scanner

  • Database Scanners

Effectiveness: SOAR Partial

Dynamic Analysis with manual results interpretation

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

Cost effective for partial coverage:

  • Fuzz Tester

  • Framework-based Fuzzer

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

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

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

  • Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

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

Highly cost effective:

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR High

Architecture / Design Review

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

Highly cost effective:

  • Formal Methods / Correct-By-Construction

Cost effective for partial coverage:

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

Effectiveness: SOAR High

+ Demonstrative Examples

Example 1

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

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

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

Example 2

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

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

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

Example 3

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

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

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

Example 4

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

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

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

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

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

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

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

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

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

Phase: Requirements

Strategy: Language Selection

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

For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.

Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.

Phase: Architecture and Design

Strategy: Libraries or Frameworks

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

Examples include the Safe C String Library (SafeStr) by Messier and Viega [R.120.4], and the Strsafe.h library from Microsoft [R.120.3]. These libraries provide safer versions of overflow-prone string-handling functions.

This is not a complete solution, since many buffer overflows are not related to strings.

Phase: Build and Compilation

Strategy: Compilation or Build Hardening

Run or compile the software using features or extensions that automatically provide a protection mechanism that mitigates or eliminates buffer overflows.

For example, certain compilers and extensions provide automatic buffer overflow detection mechanisms that are built into the compiled code. Examples include the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice.

Effectiveness: Defense in Depth

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

Phase: Implementation

Consider adhering to the following rules when allocating and managing an application's memory:

  • Double check that your buffer is as large as you specify.

  • When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.

  • Check buffer boundaries if accessing the buffer in a loop and make sure you are not in danger of writing past the allocated space.

  • If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.

Phase: Implementation

Strategy: Input Validation

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

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

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

Phase: Architecture and Design

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

Phase: Operation

Strategy: Environment Hardening

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

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

Effectiveness: Defense in Depth

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

Phase: Operation

Strategy: Environment Hardening

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

Effectiveness: Defense in Depth

This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.

Phases: Build and Compilation; Operation

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

Phase: Implementation

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

Effectiveness: Moderate

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

Phase: Architecture and Design

Strategy: Enforcement by Conversion

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

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

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

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

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

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

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

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

Effectiveness: Limited

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

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

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

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

Explicit

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

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

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

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

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

CWE-300: Channel Accessible by Non-Endpoint ('Man-in-the-Middle')

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

Description Summary

The product does not adequately verify the identity of actors at both ends of a communication channel, or does not adequately ensure the integrity of the channel, in a way that allows the channel to be accessed or influenced by an actor that is not an endpoint.

Extended Description

In order to establish secure communication between two parties, it is often important to adequately verify the identity of entities at each end of the communication channel. Inadequate or inconsistent verification may result in insufficient or incorrect identification of either communicating entity. This can have negative consequences such as misplaced trust in the entity at the other end of the channel. An attacker can leverage this by interposing between the communicating entities and masquerading as the original entity. In the absence of sufficient verification of identity, such an attacker can eavesdrop and potentially modify the communication between the original entities.

+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Access Control

Technical Impact: Read application data; Modify application data; Gain privileges / assume identity

An attacker could pose as one of the entities and read or possibly modify the communication.

+ Demonstrative Examples

Example 1

In the Java snippet below, data is sent over an unencrypted channel to a remote server.

(Bad Code)
Example Language: Java 
Socket sock;
PrintWriter out;

try {
sock = new Socket(REMOTE_HOST, REMOTE_PORT);
out = new PrintWriter(echoSocket.getOutputStream(), true);

// Write data to remote host via socket output stream.
...
}

By eavesdropping on the communication channel or posing as the endpoint, an attacker would be able to read all of the transmitted data.

+ Observed Examples
ReferenceDescription
chain: incorrect "goto" in Apple SSL product bypasses certificate validation, allowing man-in-the-middle attack (Apple "goto fail" bug). CWE-705 (Incorrect Control Flow Scoping) -> CWE-561 (Dead Code) -> CWE-295 (Improper Certificate Validation) -> CWE-393 (Return of Wrong Status Code) -> CWE-300 (Channel Accessible by Non-Endpoint ('Man-in-the-Middle')).
+ Potential Mitigations

Phase: Implementation

Always fully authenticate both ends of any communications channel.

Phase: Architecture and Design

Adhere to the principle of complete mediation.

Phase: Implementation

A certificate binds an identity to a cryptographic key to authenticate a communicating party. Often, the certificate takes the encrypted form of the hash of the identity of the subject, the public key, and information such as time of issue or expiration using the issuer's private key. The certificate can be validated by deciphering the certificate with the issuer's public key. See also X.509 certificate signature chains and the PGP certification structure.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory859CERT Java Secure Coding Section 14 - Platform Security (SEC)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfWeakness ClassWeakness Class923Improper Restriction of Communication Channel to Intended Endpoints
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory956SFP Secondary Cluster: Channel Attack
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base602Client-Side Enforcement of Server-Side Security
Research Concepts1000
PeerOfWeakness BaseWeakness Base603Use of Client-Side Authentication
Research Concepts1000
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERMan-in-the-middle (MITM)
WASC32Routing Detour
CERT Java Secure CodingSEC06-JDo not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar
+ References
M. Bishop. "Computer Security: Art and Science". Addison-Wesley. 2003.
+ Maintenance Notes

The summary identifies multiple distinct possibilities, suggesting that this is a category that must be broken into more specific weaknesses.

+ 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-09-08CWE Content TeamMITREInternal
updated Description, Maintenance_Notes, Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Name
2010-02-16CWE Content TeamMITREInternal
updated Taxonomy_Mappings
2010-12-13CWE Content TeamMITREInternal
updated Description
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Related_Attack_Patterns, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-02-18CWE Content TeamMITREInternal
updated Relationships
2014-06-23CWE Content TeamMITREInternal
updated Observed_Examples
2014-07-30CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Man-in-the-middle (MITM)
2009-05-27Channel Accessible by Non-Endpoint (aka 'Man-in-the-Middle')

CWE-312: Cleartext Storage of Sensitive Information

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

Description Summary

The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.

Extended Description

Because the information is stored in cleartext, attackers could potentially read it. Even if the information is encoded in a way that is not human-readable, certain techniques could determine which encoding is being used, then decode the information.

+ Terminology Notes

Different people use "cleartext" and "plaintext" to mean the same thing: the lack of encryption. However, within cryptography, these have more precise meanings. Plaintext is the information just before it is fed into a cryptographic algorithm, including already-encrypted text. Cleartext is any information that is unencrypted, although it might be in an encoded form that is not easily human-readable (such as base64 encoding).

+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

Language-independent

Architectural Paradigms

Mobile Application

+ Common Consequences
ScopeEffect
Confidentiality

Technical Impact: Read application data

An attacker with access to the system could read sensitive information stored in cleartext.

+ Demonstrative Examples

Example 1

The following code excerpt stores a plaintext user account ID in a browser cookie.

(Bad Code)
Example Language: Java 
response.addCookie( new Cookie("userAccountID", acctID);

Because the account ID is in plaintext, the user's account information is exposed if their computer is compromised by an attacker.

Example 2

This code writes a user's login information to a cookie so the user does not have to login again later.

(Bad Code)
Example Language: PHP 
function persistLogin($username, $password){
$data = array("username" => $username, "password"=> $password);
setcookie ("userdata", $data);
}

The code stores the user's username and password in plaintext in a cookie on the user's machine. This exposes the user's login information if their computer is compromised by an attacker. Even if the user's machine is not compromised, this weakness combined with cross-site scripting (CWE-79) could allow an attacker to remotely copy the cookie.

Also note this example code also exhibits Plaintext Storage in a Cookie (CWE-315).

Example 3

The following code attempts to establish a connection, read in a password, then store it to a buffer.

(Bad Code)
Example Language:
server.sin_family = AF_INET; hp = gethostbyname(argv[1]);
if (hp==NULL) error("Unknown host");
memcpy( (char *)&server.sin_addr,(char *)hp->h_addr,hp->h_length);
if (argc < 3) port = 80;
else port = (unsigned short)atoi(argv[3]);
server.sin_port = htons(port);
if (connect(sock, (struct sockaddr *)&server, sizeof server) < 0) error("Connecting");
...
while ((n=read(sock,buffer,BUFSIZE-1))!=-1) {

write(dfd,password_buffer,n);
...

While successful, the program does not encrypt the data before writing it to a buffer, possibly exposing it to unauthorized actors.

Example 4

The following examples show a portion of properties and configuration files for Java and ASP.NET applications. The files include username and password information but they are stored in plaintext.

This Java example shows a properties file with a plaintext username / password pair.

(Bad Code)
Example Language: Java 
# Java Web App ResourceBundle properties file
...
webapp.ldap.username=secretUsername
webapp.ldap.password=secretPassword
...

The following example shows a portion of a configuration file for an ASP.Net application. This configuration file includes username and password information for a connection to a database but the pair is stored in plaintext.

(Bad Code)
Example Language: ASP.NET 
...
<connectionStrings>
<add name="ud_DEV" connectionString="connectDB=uDB; uid=db2admin; pwd=password; dbalias=uDB;" providerName="System.Data.Odbc" />
</connectionStrings>
...

Username and password information should not be included in a configuration file or a properties file in plaintext as this will allow anyone who can read the file access to the resource. If possible, encrypt this information and avoid CWE-260 and CWE-13.

+ Observed Examples
ReferenceDescription
password and username stored in cleartext in a cookie
password stored in cleartext in a file with insecure permissions
chat program disables SSL in some circumstances even when the user says to use SSL.
Chain: product uses an incorrect public exponent when generating an RSA key, which effectively disables the encryption
storage of unencrypted passwords in a database
storage of unencrypted passwords in a database
product stores a password in cleartext in memory
storage of a secret key in cleartext in a temporary file
SCADA product uses HTTP Basic Authentication, which is not encrypted
login credentials stored unencrypted in a registry key
Plaintext credentials in world-readable file.
Password in cleartext in config file.
Password in cleartext in config file.
Decrypted copy of a message written to disk given a combination of options and when user replies to an encrypted message.
Plaintext storage of private key and passphrase in log file when user imports the key.
Admin password in plaintext in a cookie.
Default configuration has cleartext usernames/passwords in cookie.
Usernames/passwords in cleartext in cookies.
Authentication information stored in cleartext in a cookie.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base311Missing Encryption of Sensitive Data
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory816OWASP Top Ten 2010 Category A7 - Insecure Cryptographic Storage
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfWeakness ClassWeakness Class922Insecure Storage of Sensitive Information
Development Concepts699
Research Concepts1000
ChildOfCategoryCategory934OWASP Top Ten 2013 Category A6 - Sensitive Data Exposure
Weaknesses in OWASP Top Ten (2013) (primary)928
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant313Cleartext Storage in a File or on Disk
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant314Cleartext Storage in the Registry
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant315Cleartext Storage of Sensitive Information in a Cookie
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant316Cleartext Storage of Sensitive Information in Memory
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant317Cleartext Storage of Sensitive Information in GUI
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant318Cleartext Storage of Sensitive Information in Executable
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERPlaintext Storage of Sensitive Information
Software Fault PatternsSFP23Exposed Data
+ References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 9, "Protecting Secret Data" Page 299. 2nd Edition. Microsoft. 2002.
[REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 2, "Common Vulnerabilities of Encryption", Page 43.. 1st Edition. Addison Wesley. 2006.
[REF-33] Chris Wysopal. "Mobile App Top 10 List". 2010-12-13. <http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Description, Name
2010-02-16CWE Content TeamMITREInternal
updated References
2010-06-21CWE Content TeamMITREInternal
updated Relationships
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Observed_Examples, References, Related_Attack_Patterns, Relationships
2013-02-21CWE Content TeamMITREInternal
updated Applicable_Platforms, References
2013-07-17CWE Content TeamMITREInternal
updated Description, Relationships, Terminology_Notes
2014-07-30CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships, Taxonomy_Mappings
2017-05-03CWE Content TeamMITREInternal
updated Related_Attack_Patterns
Previous Entry Names
Change DatePrevious Entry Name
2009-01-12Plaintext Storage of Sensitive Information

CWE-319: Cleartext Transmission of Sensitive Information

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

Description Summary

The software transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors.

Extended Description

Many communication channels can be "sniffed" by attackers during data transmission. For example, network traffic can often be sniffed by any attacker who has access to a network interface. This significantly lowers the difficulty of exploitation by attackers.

+ Time of Introduction
  • Architecture and Design
  • Operation
  • System Configuration
+ Applicable Platforms

Languages

Language-independent

Architectural Paradigms

Mobile Application

+ Common Consequences
ScopeEffect
Integrity
Confidentiality

Technical Impact: Read application data; Modify files or directories

Anyone can read the information by gaining access to the channel being used for communication.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Black Box

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

Attach the monitor to the process, trigger the feature that sends the data, and look for the presence or absence of common cryptographic functions in the call tree. Monitor the network and determine if the data packets contain readable commands. Tools exist for detecting if certain encodings are in use. If the traffic contains high entropy, this might indicate the usage of encryption.

+ Demonstrative Examples

Example 1

The following code attempts to establish a connection to a site to communicate sensitive information.

(Bad Code)
Example Language: Java 
try {
URL u = new URL("http://www.secret.example.org/");
HttpURLConnection hu = (HttpURLConnection) u.openConnection();
hu.setRequestMethod("PUT");
hu.connect();
OutputStream os = hu.getOutputStream();
hu.disconnect();
}
catch (IOException e) {
//...
}

Though a connection is successfully made, the connection is unencrypted and it is possible that all sensitive data sent to or received from the server will be read by unintended actors.

+ Observed Examples
ReferenceDescription
Passwords transmitted in cleartext.
Chain: Use of HTTPS cookie without "secure" flag causes it to be transmitted across unencrypted HTTP.
Product sends password hash in cleartext in violation of intended policy.
Remote management feature sends sensitive information including passwords in cleartext.
Backup routine sends password in cleartext in email.
Product transmits Blowfish encryption key in cleartext.
Printer sends configuration information, including administrative password, in cleartext.
Chain: cleartext transmission of the MD5 hash of password enables attacks against a server that is susceptible to replay (CWE-294).
Product sends passwords in cleartext to a log server.
Product sends file with cleartext passwords in e-mail message intended for diagnostic purposes.
+ Potential Mitigations

Phase: Architecture and Design

Encrypt the data with a reliable encryption scheme before transmitting.

Phase: Implementation

When using web applications with SSL, use SSL for the entire session from login to logout, not just for the initial login page.

Phase: Testing

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

Phase: Operation

Configure servers to use encrypted channels for communication, which may include SSL or other secure protocols.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base311Missing Encryption of Sensitive Data
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory7512009 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory818OWASP Top Ten 2010 Category A9 - Insufficient Transport Layer Protection
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfCategoryCategory858CERT Java Secure Coding Section 13 - Serialization (SER)
Weaknesses Addressed by the CERT Java Secure Coding Standard844
ChildOfCategoryCategory859CERT Java Secure Coding Section 14 - Platform Security (SEC)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory930OWASP Top Ten 2013 Category A2 - Broken Authentication and Session Management
Weaknesses in OWASP Top Ten (2013)928
ChildOfCategoryCategory934OWASP Top Ten 2013 Category A6 - Sensitive Data Exposure
Weaknesses in OWASP Top Ten (2013) (primary)928
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant5J2EE Misconfiguration: Data Transmission Without Encryption
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERPlaintext Transmission of Sensitive Information
CERT Java Secure CodingSEC06-JDo not rely on the default automatic signature verification provided by URLClassLoader and java.util.jar
CERT Java Secure CodingSER02-JSign then seal sensitive objects before sending them outside a trust boundary
Software Fault PatternsSFP23Exposed Data
+ References
OWASP. "Top 10 2007-Insecure Communications". <http://www.owasp.org/index.php/Top_10_2007-A9>.
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 9, "Protecting Secret Data" Page 299. 2nd Edition. Microsoft. 2002.
[REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 22: Failing to Protect Network Traffic." Page 337. McGraw-Hill. 2010.
[REF-33] Chris Wysopal. "Mobile App Top 10 List". 2010-12-13. <http://www.veracode.com/blog/2010/12/mobile-app-top-10-list/>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Common_Consequences, Description, Likelihood_of_Exploit, Name, Observed_Examples, Potential_Mitigations, References, Relationships
2009-03-10CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-05-27CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-02-16CWE Content TeamMITREInternal
updated References
2010-04-05CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences, Time_of_Introduction
2010-06-21CWE Content TeamMITREInternal
updated Detection_Factors, Relationships
2010-12-13CWE Content TeamMITREInternal
updated Observed_Examples, Related_Attack_Patterns
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, References, Related_Attack_Patterns, Relationships, Taxonomy_Mappings
2013-02-21CWE Content TeamMITREInternal
updated Applicable_Platforms, References
2013-07-17CWE Content TeamMITREInternal
updated Relationships
2014-02-18CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2014-06-23CWE Content TeamMITREInternal
updated Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2017-05-03CWE Content TeamMITREInternal
updated Related_Attack_Patterns
Previous Entry Names
Change DatePrevious Entry Name
2009-01-12Plaintext Transmission of Sensitive Information

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

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

Description Summary

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

Extended Description

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

+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

All

Architectural Paradigms

Client-Server: (Sometimes)

+ Common Consequences
ScopeEffect
Access Control
Availability

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

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

Access Control

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

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

+ Likelihood of Exploit

Medium

+ Enabling Factors for Exploitation

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

+ Demonstrative Examples

Example 1

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

CLIENT-SIDE (client.pl)

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

SERVER-SIDE (server.pl):

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

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

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

Phase: Architecture and Design

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

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

Phase: Architecture and Design

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

Phase: Testing

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

Phase: Testing

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

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

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

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

CWE-498: Cloneable Class Containing Sensitive Information

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

Description Summary

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

Extended Description

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

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

C++

Java

.NET

+ Common Consequences
ScopeEffect
Access Control

Technical Impact: Bypass protection mechanism

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

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

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

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

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

public Object clone() {

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

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

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

Phase: Implementation

Make classes uncloneable by defining a clone function like:

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

Phase: Implementation

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

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

CWE-486: Comparison of Classes by Name

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

Description Summary

The program compares classes by name, which can cause it to use the wrong class when multiple classes can have the same name.

Extended Description

If the decision to trust the methods and data of an object is based on the name of a class, it is possible for malicious users to send objects of the same name as trusted classes and thereby gain the trust afforded to known classes and types.

+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

Java

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

If a program relies solely on the name of an object to determine identity, it may execute the incorrect or unintended code.

+ Likelihood of Exploit

High

+ Demonstrative Examples

Example 1

In this example, the expression in the if statement compares the class of the inputClass object to a trusted class by comparing the class names.

(Bad Code)
Example Language: Java 
if (inputClass.getClass().getName().equals("TrustedClassName")) {
// Do something assuming you trust inputClass
// ...
}

However, multiple classes can have the same name therefore comparing an object's class by name can allow untrusted classes of the same name as the trusted class to be use to execute unintended or incorrect code. To compare the class of an object to the intended class the getClass() method and the comparison operator "==" should be used to ensure the correct trusted class is used, as shown in the following example.

(Good Code)
Example Language: Java 
if (inputClass.getClass() == TrustedClass.class) {
// Do something assuming you trust inputClass
// ...
}

Example 2

In this example, the Java class, TrustedClass, overrides the equals method of the parent class Object to determine equivalence of objects of the class. The overridden equals method first determines if the object, obj, is the same class as the TrustedClass object and then compares the object's fields to determine if the objects are equivalent.

(Bad Code)
Example Language: Java 
public class TrustedClass {
...

@Override
public boolean equals(Object obj) {
boolean isEquals = false;

// first check to see if the object is of the same class
if (obj.getClass().getName().equals(this.getClass().getName())) {

// then compare object fields
...
if (...) {
isEquals = true;
}
}

return isEquals;
}

...
}

However, the equals method compares the class names of the object, obj, and the TrustedClass object to determine if they are the same class. As with the previous example using the name of the class to compare the class of objects can lead to the execution of unintended or incorrect code if the object passed to the equals method is of another class with the same name. To compare the class of an object to the intended class, the getClass() method and the comparison operator "==" should be used to ensure the correct trusted class is used, as shown in the following example.

(Good Code)
Example Language: Java 
public boolean equals(Object obj) {
...

// first check to see if the object is of the same class
if (obj.getClass() == this.getClass()) {
...
}

...
}
+ Potential Mitigations

Phase: Implementation

Use class equivalency to determine type. Rather than use the class name to determine if an object is of a given type, use the getClass() method, and == operator.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory171Cleansing, Canonicalization, and Comparison Errors
Development Concepts699
ChildOfWeakness ClassWeakness Class485Insufficient Encapsulation
Development Concepts (primary)699
Seven Pernicious Kingdoms (primary)700
Research Concepts1000
ChildOfWeakness ClassWeakness Class697Insufficient Comparison
Research Concepts (primary)1000
ChildOfCategoryCategory849CERT Java Secure Coding Section 04 - Object Orientation (OBJ)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory998SFP Secondary Cluster: Glitch in Computation
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base386Symbolic Name not Mapping to Correct Object
Research Concepts1000
+ Relevant Properties
  • Equivalence
  • Uniqueness
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsComparing Classes by Name
CLASPComparing classes by name
CERT Java Secure CodingOBJ09-JCompare classes and not class names
Software Fault PatternsSFP1Glitch in computation
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Common_Consequences, Description, Relationships, Other_Notes, Relevant_Properties, Taxonomy_Mappings
2009-03-10CWE Content TeamMITREInternal
updated Other_Notes
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Demonstrative_Examples, Relationships, Taxonomy_Mappings
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Comparing Classes by Name

CWE-595: Comparison of Object References Instead of Object Contents

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

Description Summary

The program compares object references instead of the contents of the objects themselves, preventing it from detecting equivalent objects.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

Java

Language-independent

+ Common Consequences
ScopeEffect
Other

Technical Impact: Other; Varies by context

This weakness can lead to erroneous results that can cause unexpected application behaviors.

+ Demonstrative Examples

Example 1

In the example below, two Java String objects are declared and initialized with the same string values and an if statement is used to determine if the strings are equivalent.

(Bad Code)
Example Language: Java 
String str1 = new String("Hello");
String str2 = new String("Hello");
if (str1 == str2) {
System.out.println("str1 == str2");
}

However, the if statement will not be executed as the strings are compared using the "==" operator. For Java objects, such as String objects, the "==" operator compares object references, not object values. While the two String objects above contain the same string values, they refer to different object references, so the System.out.println statement will not be executed. To compare object values, the previous code could be modified to use the equals method:

(Good Code)
 
if (str1.equals(str2)) {
System.out.println("str1 equals str2");
}

Example 2

In the following Java example, two BankAccount objects are compared in the isSameAccount method using the == operator.

(Bad Code)
Example Language: Java 
public boolean isSameAccount(BankAccount accountA, BankAccount accountB) {
return accountA == accountB;
}

Using the == operator to compare objects may produce incorrect or deceptive results by comparing object references rather than values. The equals() method should be used to ensure correct results or objects should contain a member variable that uniquely identifies the object.

The following example shows the use of the equals() method to compare the BankAccount objects and the next example uses a class get method to retrieve the bank account number that uniquely identifies the BankAccount object to compare the objects.

(Good Code)
Example Language: Java 
public boolean isSameAccount(BankAccount accountA, BankAccount accountB) {
return accountA.equals(accountB);
}
+ Potential Mitigations

Phase: Implementation

Use the equals() method to compare objects instead of the == operator. If using ==, it is important for performance reasons that your objects are created by a static factory, not by a constructor.

+ Other Notes

This problem can cause unexpected application behavior. Comparing objects using == usually produces deceptive results, since the == operator compares object references rather than values. To use == on a string, the programmer has to make sure that these objects are unique in the program, that is, that they don't have the equals method defined or have a static factory that produces unique objects.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory171Cleansing, Canonicalization, and Comparison Errors
Development Concepts699
ChildOfCategoryCategory569Expression Issues
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class697Insufficient Comparison
Research Concepts (primary)1000
ChildOfCategoryCategory847CERT Java Secure Coding Section 02 - Expressions (EXP)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant597Use of Wrong Operator in String Comparison
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CERT Java Secure CodingEXP02-JUse the two-argument Arrays.equals() method to compare the contents of arrays
CERT Java Secure CodingEXP02-JUse the two-argument Arrays.equals() method to compare the contents of arrays
CERT Java Secure CodingEXP03-JDo not use the equality operators when comparing values of boxed primitives
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes
2009-05-27CWE Content TeamMITREInternal
updated Name
2010-12-13CWE Content TeamMITREInternal
updated Demonstrative_Examples
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-06-23CWE Content TeamMITREInternal
updated Applicable_Platforms, Common_Consequences
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Incorrect Object Comparison: Syntactic
2009-05-27Incorrect Syntactic Object Comparison

CWE-14: Compiler Removal of Code to Clear Buffers

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

Description Summary

Sensitive memory is cleared according to the source code, but compiler optimizations leave the memory untouched when it is not read from again, aka "dead store removal."

Extended Description

This compiler optimization error occurs when:

1. Secret data are stored in memory.

2. The secret data are scrubbed from memory by overwriting its contents.

3. The source code is compiled using an optimizing compiler, which identifies and removes the function that overwrites the contents as a dead store because the memory is not used subsequently.

+ Time of Introduction
  • Implementation
  • Build and Compilation
+ Applicable Platforms

Languages

C

C++

+ Common Consequences
ScopeEffect
Confidentiality
Access Control

Technical Impact: Read memory; Bypass protection mechanism

This weakness will allow data that has not been cleared from memory to be read. If this data contains sensitive password information, then an attacker can read the password and use the information to bypass protection mechanisms.

+ Detection Methods

Black Box

This specific weakness is impossible to detect using black box methods. While an analyst could examine memory to see that it has not been scrubbed, an analysis of the executable would not be successful. This is because the compiler has already removed the relevant code. Only the source code shows whether the programmer intended to clear the memory or not, so this weakness is indistinguishable from others.

White Box

This weakness is only detectable using white box methods (see black box detection factor). Careful analysis is required to determine if the code is likely to be removed by the compiler.

+ Demonstrative Examples

Example 1

The following code reads a password from the user, uses the password to connect to a back-end mainframe and then attempts to scrub the password from memory using memset().

(Bad Code)
Example Language:
void GetData(char *MFAddr) {
char pwd[64];
if (GetPasswordFromUser(pwd, sizeof(pwd))) {

if (ConnectToMainframe(MFAddr, pwd)) {

// Interaction with mainframe
}
}
memset(pwd, 0, sizeof(pwd));
}

The code in the example will behave correctly if it is executed verbatim, but if the code is compiled using an optimizing compiler, such as Microsoft Visual C++ .NET or GCC 3.x, then the call to memset() will be removed as a dead store because the buffer pwd is not used after its value is overwritten [18]. Because the buffer pwd contains a sensitive value, the application may be vulnerable to attack if the data are left memory resident. If attackers are able to access the correct region of memory, they may use the recovered password to gain control of the system.

It is common practice to overwrite sensitive data manipulated in memory, such as passwords or cryptographic keys, in order to prevent attackers from learning system secrets. However, with the advent of optimizing compilers, programs do not always behave as their source code alone would suggest. In the example, the compiler interprets the call to memset() as dead code because the memory being written to is not subsequently used, despite the fact that there is clearly a security motivation for the operation to occur. The problem here is that many compilers, and in fact many programming languages, do not take this and other security concerns into consideration in their efforts to improve efficiency.

Attackers typically exploit this type of vulnerability by using a core dump or runtime mechanism to access the memory used by a particular application and recover the secret information. Once an attacker has access to the secret information, it is relatively straightforward to further exploit the system and possibly compromise other resources with which the application interacts.

+ Potential Mitigations

Phase: Implementation

Store the sensitive data in a "volatile" memory location if available.

Phase: Build and Compilation

If possible, configure your compiler so that it does not remove dead stores.

Phase: Architecture and Design

Where possible, encrypt sensitive data that are used by a software system.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory2Environment
Seven Pernicious Kingdoms (primary)700
ChildOfCategoryCategory633Weaknesses that Affect Memory
Resource-specific Weaknesses (primary)631
ChildOfCategoryCategory729OWASP Top Ten 2004 Category A8 - Insecure Storage
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfWeakness BaseWeakness Base733Compiler Optimization Removal or Modification of Security-critical Code
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory747CERT C Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory883CERT C++ Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory963SFP Secondary Cluster: Exposed Data
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Affected Resources
  • Memory
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
7 Pernicious KingdomsInsecure Compiler Optimization
PLOVERSensitive memory uncleared by compiler optimization
OWASP Top Ten 2004A8CWE More SpecificInsecure Storage
CERT C Secure CodingMSC06-CBe aware of compiler optimization when dealing with sensitive data
CERT C++ Secure CodingMSC06-CPPBe aware of compiler optimization when dealing with sensitive data
Software Fault PatternsSFP23Exposed Data
+ References
[REF-11] M. Howard and D. LeBlanc. "Writing Secure Code". Chapter 9, "A Compiler Optimization Caveat" Page 322. 2nd Edition. Microsoft. 2002.
Michael Howard. "When scrubbing secrets in memory doesn't work". BugTraq. 2002-11-05. <http://cert.uni-stuttgart.de/archive/bugtraq/2002/11/msg00046.html>.
Michael Howard. "Some Bad News and Some Good News". Microsoft. 2002-10-21. <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncode/html/secure10102002.asp>.
Joseph Wagner. "GNU GCC: Optimizer Removes Code Necessary for Security". Bugtraq. 2002-11-16. <http://www.derkeiler.com/Mailing-Lists/securityfocus/bugtraq/2002-11/0257.html>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
7 Pernicious KingdomsExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Other_Notes, Taxonomy_Mappings
2008-10-14CWE Content TeamMITREInternal
updated Relationships
2008-11-24CWE Content TeamMITREInternal
updated Applicable_Platforms, Description, Detection_Factors, Other_Notes, Potential_Mitigations, Relationships, Taxonomy_Mappings, Time_of_Introduction
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2010-02-16CWE Content TeamMITREInternal
updated References
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2017-01-19CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Insecure Compiler Optimization

CWE-352: Cross-Site Request Forgery (CSRF)

Compound Element ID: 352
Abstraction: Variant
Structure: Composite
Status: Draft
Presentation Filter:
+ Description

Description Summary

The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.

Extended Description

When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server which will be treated as an authentic request. This can be done via a URL, image load, XMLHttpRequest, etc. and can result in exposure of data or unintended code execution.

+ Alternate Terms
Session Riding
Cross Site Reference Forgery
XSRF
+ Time of Introduction
  • Architecture and Design
+ Applicable Platforms

Languages

Language-independent

Technology Classes

Web-Server

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability
Non-Repudiation
Access Control

Technical Impact: Gain privileges / assume identity; Bypass protection mechanism; Read application data; Modify application data; DoS: crash / exit / restart

The consequences will vary depending on the nature of the functionality that is vulnerable to CSRF. An attacker could effectively perform any operations as the victim. If the victim is an administrator or privileged user, the consequences may include obtaining complete control over the web application - deleting or stealing data, uninstalling the product, or using it to launch other attacks against all of the product's users. Because the attacker has the identity of the victim, the scope of CSRF is limited only by the victim's privileges.

+ Likelihood of Exploit

Medium to High

+ Detection Methods

Manual Analysis

This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session.

Specifically, manual analysis can be useful for finding this weakness, and for minimizing false positives assuming an understanding of business logic. However, it might not achieve desired code coverage within limited time constraints. For black-box analysis, if credentials are not known for privileged accounts, then the most security-critical portions of the application may not receive sufficient attention.

Consider using OWASP CSRFTester to identify potential issues and aid in manual analysis.

Effectiveness: High

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

Automated Static Analysis

CSRF is currently difficult to detect reliably using automated techniques. This is because each application has its own implicit security policy that dictates which requests can be influenced by an outsider and automatically performed on behalf of a user, versus which requests require strong confidence that the user intends to make the request. For example, a keyword search of the public portion of a web site is typically expected to be encoded within a link that can be launched automatically when the user clicks on the link.

Effectiveness: Limited

Automated Static Analysis - Binary / Bytecode

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

Cost effective for partial coverage:

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

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

Effectiveness: SOAR Partial

Manual Static Analysis - Binary / Bytecode

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

Cost effective for partial coverage:

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

Effectiveness: SOAR Partial

Dynamic Analysis with automated results interpretation

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

Highly cost effective:

  • Web Application Scanner

Effectiveness: SOAR High

Dynamic Analysis with manual results interpretation

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

Highly cost effective:

  • Fuzz Tester

  • Framework-based Fuzzer

Effectiveness: SOAR High

Manual Static Analysis - Source Code

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

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

  • Manual Source Code Review (not inspections)

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

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

Cost effective for partial coverage:

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR Partial

Architecture / Design Review

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

Cost effective for partial coverage:

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

  • Formal Methods / Correct-By-Construction

Effectiveness: SOAR Partial

+ Demonstrative Examples

Example 1

This example PHP code attempts to secure the form submission process by validating that the user submitting the form has a valid session. A CSRF attack would not be prevented by this countermeasure because the attacker forges a request through the user's web browser in which a valid session already exists.

The following HTML is intended to allow a user to update a profile.

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

profile.php contains the following code.

(Bad Code)
Example Language: PHP 
// initiate the session in order to validate sessions

session_start();

//if the session is registered to a valid user then allow update

if (! session_is_registered("username")) {

echo "invalid session detected!";

// Redirect user to login page
[...]

exit;
}

// The user session is valid, so process the request
// and update the information

update_profile();

function update_profile {
// read in the data from $POST and send an update
// to the database
SendUpdateToDatabase($_SESSION['username'], $_POST['email']);
[...]
echo "Your profile has been successfully updated.";
}

This code may look protected since it checks for a valid session. However, CSRF attacks can be staged from virtually any tag or HTML construct, including image tags, links, embed or object tags, or other attributes that load background images.

The attacker can then host code that will silently change the username and email address of any user that visits the page while remaining logged in to the target web application. The code might be an innocent-looking web page such as:

(Attack)
Example Language: HTML 
<SCRIPT>
function SendAttack () {
form.email = "attacker@example.com";
// send to profile.php
form.submit();
}
</SCRIPT>

<BODY onload="javascript:SendAttack();">

<form action="http://victim.example.com/profile.php" id="form" method="post">
<input type="hidden" name="firstname" value="Funny">
<input type="hidden" name="lastname" value="Joke">
<br/>
<input type="hidden" name="email">
</form>

Notice how the form contains hidden fields, so when it is loaded into the browser, the user will not notice it. Because SendAttack() is defined in the body's onload attribute, it will be automatically called when the victim loads the web page.

Assuming that the user is already logged in to victim.example.com, profile.php will see that a valid user session has been established, then update the email address to the attacker's own address. At this stage, the user's identity has been compromised, and messages sent through this profile could be sent to the attacker's address.

+ Observed Examples
ReferenceDescription
Add user accounts via a URL in an img tag
Add user accounts via a URL in an img tag
Arbitrary code execution by specifying the code in a crafted img tag or URL
Gain administrative privileges via a URL in an img tag
Delete a victim's information via a URL or an img tag
Change another user's settings via a URL or an img tag
Perform actions as administrator via a URL or an img tag
modify password for the administrator
CMS allows modification of configuration via CSRF attack against the administrator
web interface allows password changes or stopping a virtual machine via CSRF
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Libraries or Frameworks

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

For example, use anti-CSRF packages such as the OWASP CSRFGuard. [R.352.3]

Another example is the ESAPI Session Management control, which includes a component for CSRF. [R.352.9]

Phase: Implementation

Ensure that the application is free of cross-site scripting issues (CWE-79), because most CSRF defenses can be bypassed using attacker-controlled script.

Phase: Architecture and Design

Generate a unique nonce for each form, place the nonce into the form, and verify the nonce upon receipt of the form. Be sure that the nonce is not predictable (CWE-330). [R.352.5]

Note that this can be bypassed using XSS (CWE-79).

Phase: Architecture and Design

Identify especially dangerous operations. When the user performs a dangerous operation, send a separate confirmation request to ensure that the user intended to perform that operation.

Note that this can be bypassed using XSS (CWE-79).

Phase: Architecture and Design

Use the "double-submitted cookie" method as described by Felten and Zeller:

When a user visits a site, the site should generate a pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same.

Because of the same-origin policy, an attacker cannot read or modify the value stored in the cookie. To successfully submit a form on behalf of the user, the attacker would have to correctly guess the pseudorandom value. If the pseudorandom value is cryptographically strong, this will be prohibitively difficult.

This technique requires Javascript, so it may not work for browsers that have Javascript disabled. [R.352.4]

Note that this can probably be bypassed using XSS (CWE-79), or when using web technologies that enable the attacker to read raw headers from HTTP requests.

Phase: Architecture and Design

Do not use the GET method for any request that triggers a state change.

Phase: Implementation

Check the HTTP Referer header to see if the request originated from an expected page. This could break legitimate functionality, because users or proxies may have disabled sending the Referer for privacy reasons.

Note that this can be bypassed using XSS (CWE-79). An attacker could use XSS to generate a spoofed Referer, or to generate a malicious request from a page whose Referer would be allowed.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
RequiresWeakness BaseWeakness Base346Origin Validation Error
Research Concepts1000
RequiresWeakness ClassWeakness Class441Unintended Proxy or Intermediary ('Confused Deputy')
Research Concepts1000
RequiresWeakness BaseWeakness Base613Insufficient Session Expiration
Research Concepts1000
RequiresWeakness ClassWeakness Class642External Control of Critical State Data
Research Concepts1000
ChildOfWeakness ClassWeakness Class345Insufficient Verification of Data Authenticity
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory442Web Problems
Development Concepts699
ChildOfCategoryCategory716OWASP Top Ten 2007 Category A5 - Cross Site Request Forgery (CSRF)
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory7512009 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)750
ChildOfCategoryCategory8012010 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory814OWASP Top Ten 2010 Category A5 - Cross-Site Request Forgery(CSRF)
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfCategoryCategory8642011 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
ChildOfCategoryCategory936OWASP Top Ten 2013 Category A8 - Cross-Site Request Forgery (CSRF)
Weaknesses in OWASP Top Ten (2013) (primary)928
MemberOfViewView635Weaknesses Used by NVD
Weaknesses Used by NVD (primary)635
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
PeerOfWeakness BaseWeakness Base79Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
Research Concepts1000
+ Relationship Notes

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

+ Research Gaps

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

+ Theoretical Notes

The CSRF topology is multi-channel:

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

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

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERCross-Site Request Forgery (CSRF)
OWASP Top Ten 2007A5ExactCross Site Request Forgery (CSRF)
WASC9Cross-site Request Forgery
+ References
[R.352.1] [REF-17] Michael Howard, David LeBlanc and John Viega. "24 Deadly Sins of Software Security". "Sin 2: Web-Server Related Vulnerabilities (XSS, XSRF, and Response Splitting)." Page 37. McGraw-Hill. 2010.
[R.352.2] Peter W. "Cross-Site Request Forgeries (Re: The Dangers of Allowing Users to Post Images)". Bugtraq. <http://marc.info/?l=bugtraq&m=99263135911884&w=2>.
[R.352.3] OWASP. "Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet". <http://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet>.
[R.352.4] Edward W. Felten and William Zeller. "Cross-Site Request Forgeries: Exploitation and Prevention". 2008-10-18. <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.147.1445>.
[R.352.5] Robert Auger. "CSRF - The Cross-Site Request Forgery (CSRF/XSRF) FAQ". <http://www.cgisecurity.com/articles/csrf-faq.shtml>.
[R.352.6] "Cross-site request forgery". Wikipedia. 2008-12-22. <http://en.wikipedia.org/wiki/Cross-site_request_forgery>.
[R.352.7] Jason Lam. "Top 25 Series - Rank 4 - Cross Site Request Forgery". SANS Software Security Institute. 2010-03-03. <http://software-security.sans.org/blog/2010/03/03/top-25-series-rank-4-cross-site-request-forgery>.
[R.352.8] Jeff Atwood. "Preventing CSRF and XSRF Attacks". 2008-10-14. <http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html>.
[R.352.9] [REF-21] OWASP. "OWASP Enterprise Security API (ESAPI) Project". <http://www.owasp.org/index.php/ESAPI>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Alternate_Terms, Description, Relationships, Other_Notes, Relationship_Notes, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Applicable_Platforms, Description, Likelihood_of_Exploit, Observed_Examples, Other_Notes, Potential_Mitigations, References, Relationship_Notes, Relationships, Research_Gaps, Theoretical_Notes
2009-03-10CWE Content TeamMITREInternal
updated Potential_Mitigations
2009-05-20Tom StracenerExternal
Added demonstrative example for profile.
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples, Related_Attack_Patterns
2009-12-28CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Detection_Factors, Likelihood_of_Exploit, Observed_Examples, Potential_Mitigations, Time_of_Introduction
2010-02-16CWE Content TeamMITREInternal
updated Applicable_Platforms, Detection_Factors, References, Relationships, Taxonomy_Mappings
2010-06-21CWE Content TeamMITREInternal
updated Common_Consequences, Detection_Factors, Potential_Mitigations, References, Relationships
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Description
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Potential_Mitigations, References
2012-05-11CWE Content TeamMITREInternal
updated Related_Attack_Patterns, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2013-02-21CWE Content TeamMITREInternal
updated Relationships
2013-07-17CWE Content TeamMITREInternal
updated References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-561: Dead Code

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

Description Summary

The software contains dead code, which can never be executed.

Extended Description

Dead code is source code that can never be executed in a running program. The surrounding code makes it impossible for a section of code to ever be executed.

+ Time of Introduction
  • Implementation
+ Common Consequences
ScopeEffect
Other

Technical Impact: Quality degradation

Dead code that results from code that can never be executed is an indication of problems with the source code that needs to be fixed and is an indication of poor quality.

+ Detection Methods

Architecture / Design Review

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

Highly cost effective:

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

  • Formal Methods / Correct-By-Construction

Cost effective for partial coverage:

  • Attack Modeling

Effectiveness: SOAR High

Automated Static Analysis - Binary / Bytecode

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

Highly cost effective:

  • Binary / Bytecode Quality Analysis

  • Compare binary / bytecode to application permission manifest

Effectiveness: SOAR High

Dynamic Analysis with manual results interpretation

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

Cost effective for partial coverage:

  • Automated Monitored Execution

Effectiveness: SOAR Partial

Automated Static Analysis

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

Cost effective for partial coverage:

  • Permission Manifest Analysis

Effectiveness: SOAR Partial

Automated Static Analysis - Source Code

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

Highly cost effective:

  • Source Code Quality Analyzer

Cost effective for partial coverage:

  • Warning Flags

  • Source code Weakness Analyzer

  • Context-configured Source Code Weakness Analyzer

Effectiveness: SOAR High

Dynamic Analysis with automated results interpretation

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

Cost effective for partial coverage:

  • Web Application Scanner

  • Web Services Scanner

  • Database Scanners

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

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

Highly cost effective:

  • Manual Source Code Review (not inspections)

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source

Effectiveness: SOAR High

+ Demonstrative Examples

Example 1

The condition for the second if statement is impossible to satisfy. It requires that the variables be non-null, while on the only path where s can be assigned a non-null value there is a return statement.

(Bad Code)
Example Language: C++ 
String s = null;
if (b) {
s = "Yes";
return;
}

if (s != null) {
Dead();
}

Example 2

In the following class, two private methods call each other, but since neither one is ever invoked from anywhere else, they are both dead code.

(Bad Code)
Example Language: Java 
public class DoubleDead {
private void doTweedledee() {
doTweedledumb();
}
private void doTweedledumb() {
doTweedledee();
}
public static void main(String[] args) {
System.out.println("running DoubleDead");
}
}

(In this case it is a good thing that the methods are dead: invoking either one would cause an infinite loop.)

Example 3

The field named glue is not used in the following class. The author of the class has accidentally put quotes around the field name, transforming it into a string constant.

(Bad Code)
Example Language: Java 
public class Dead {
String glue;

public String getGlue() {
return "glue";
}
}
+ Observed Examples
ReferenceDescription
chain: incorrect "goto" in Apple SSL product bypasses certificate validation, allowing man-in-the-middle attack (Apple "goto fail" bug). CWE-705 (Incorrect Control Flow Scoping) -> CWE-561 (Dead Code) -> CWE-295 (Improper Certificate Validation) -> CWE-393 (Return of Wrong Status Code) -> CWE-300 (Channel Accessible by Non-Endpoint ('Man-in-the-Middle')).
+ Potential Mitigations

Phase: Implementation

Remove dead code before deploying the application.

Phase: Testing

Use a static analysis tool to spot dead code.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class398Indicator of Poor Code Quality
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory747CERT C Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory883CERT C++ Secure Coding Section 49 - Miscellaneous (MSC)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory886SFP Primary Cluster: Unused entities
Software Fault Pattern (SFP) Clusters (primary)888
ParentOfWeakness VariantWeakness Variant570Expression is Always False
Development Concepts (primary)699
Research Concepts (primary)1000
ParentOfWeakness VariantWeakness Variant571Expression is Always True
Development Concepts (primary)699
Research Concepts (primary)1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
Anonymous Tool Vendor (under NDA)
CERT C Secure CodingMSC07-CDetect and remove dead code
CERT C++ Secure CodingMSC07-CPPDetect and remove dead code
Software Fault PatternsSFP2Unused Entities
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
Anonymous Tool Vendor (under NDA)Externally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations, Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Description, Relationships, Other_Notes, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2009-05-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-07-27CWE Content TeamMITREInternal
updated Demonstrative_Examples
2009-10-29CWE Content TeamMITREInternal
updated Common_Consequences, Other_Notes
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-06-23CWE Content TeamMITREInternal
updated Observed_Examples
2014-07-30CWE Content TeamMITREInternal
updated Detection_Factors, Taxonomy_Mappings

CWE-502: Deserialization of Untrusted Data

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

Description Summary

The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.

Extended Description

It is often convenient to serialize objects for communication or to save them for later use. However, deserialized data or code can often be modified without using the provided accessor functions if it does not use cryptography to protect itself. Furthermore, any cryptography would still be client-side security -- which is a dangerous security assumption.

Data that is untrusted can not be trusted to be well-formed.

When developers place no restrictions on "gadget chains," or series of instances and method invocations that can self-execute during the deserialization process (i.e., before the object is returned to the caller), it is sometimes possible for attackers to leverage them to perform unauthorized actions, like generating a shell.

+ Alternate Terms
Marshaling, Unmarshaling:

Marshaling and unmarshaling are effectively synonyms for serialization and deserialization, respectively.

Pickling, Unpickling:

In Python, the "pickle" functionality is used to perform serialization and deserialization.

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

Languages

Java

Ruby

PHP

Python

Node.js

Language-independent

+ Common Consequences
ScopeEffect

Technical Impact: Varies by context

The consequences can vary widely, because it depends on which objects or methods are being deserialized, and how they are used.

Integrity

Technical Impact: Modify application data; Unexpected state

Attackers can modify unexpected objects or data that was assumed to be safe from modification.

Availability

Technical Impact: DoS: resource consumption (CPU)

If a function is making an assumption on when to terminate, based on a sentry in a string, it could easily never terminate.

Authorization
Other

Technical Impact: Other

Code could potentially make the assumption that information in the deserialized object is valid. Functions that make this dangerous assumption could be exploited.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

This code snippet deserializes an object from a file and uses it as a UI button:

(Bad Code)
Example Language: Java 
try {
File file = new File("object.obj");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
javax.swing.JButton button = (javax.swing.JButton) in.readObject();
in.close();
}

This code does not attempt to verify the source or contents of the file before deserializing it. An attacker may be able to replace the intended file with a file that contains arbitrary malicious code which will be executed when the button is pressed.

Example 2

In Python, the Pickle library handles the serialization and deserialization processes. In this example derived from [R.502.7], the code receives and parses data, and afterwards tries to authenticate a user based on validating a token.

(Bad Code)
Example Language: Python 
try {
class ExampleProtocol(protocol.Protocol):
def dataReceived(self, data):

# Code that would be here would parse the incoming data
# After receiving headers, call confirmAuth() to authenticate

def confirmAuth(self, headers):
try:
token = cPickle.loads(base64.b64decode(headers['AuthToken']))
if not check_hmac(token['signature'], token['data'], getSecretKey()):
raise AuthFail
self.secure_data = token['data']
except:
raise AuthFail
}

Unfortunately, the code does not verify that the incoming data is legitimate. An attacker can construct a illegitimate, serialized object "AuthToken" that instantiates one of Python's subprocesses to execute arbitrary commands. For instance,the attacker could construct a pickle that leverages Python's subprocess module, which spawns new processes and includes a number of arguments for various uses. Since Pickle allows objects to define the process for how they should be unpickled, the attacker can direct the unpickle process to call Popen in the subprocess module and execute /bin/sh.

+ Observed Examples
ReferenceDescription
Deserialization issue in commonly-used Java library allows remote execution.
Deserialization issue in commonly-used Java library allows remote execution.
Use of PHP unserialize function on untrusted input allows attacker to modify application configuration.
Use of PHP unserialize function on untrusted input in content management system might allow code execution.
Use of PHP unserialize function on untrusted input in content management system allows code execution using a crafted cookie value.
Content management system written in PHP allows unserialize of arbitrary objects, possibly allowing code execution.
Python script allows local users to execute code via pickled data.
Unsafe deserialization using pickle in a Python script.
Web browser allows execution of native methods via a crafted string to a JavaScript function that deserializes the string.
+ Potential Mitigations

Phases: Architecture and Design; Implementation

If available, use the signing/sealing features of the programming language to assure that deserialized data has not been tainted. For example, a hash-based message authentication code (HMAC) could be used to ensure that data has not been modified.

Phase: Implementation

When deserializing data, populate a new object rather than just deserializing. The result is that the data flows through safe input validation and that the functions are safe.

Phase: Implementation

Explicitly define final readObject() to prevent deserialization. An example of this is:

(Good Code)
Example Language: Java 
private final void readObject(ObjectInputStream in) throws java.io.IOException {
throw new java.io.IOException("Cannot be deserialized"); }

Phases: Architecture and Design; Implementation

Make fields transient to protect them from deserialization.

An attempt to serialize and then deserialize a class containing transient fields will result in NULLs where the transient data should be. This is an excellent way to prevent time, environment-based, or sensitive variables from being carried over and used improperly.

Phase: Implementation

Avoid having unnecessary types or gadgets available that can be leveraged for malicious ends. This limits the potential for unintended or unauthorized types and gadgets to be leveraged by the attacker. Whitelist acceptable classes. Note: new gadgets are constantly being discovered, so this alone is not a sufficient mitigation.

+ Background Details

Serialization and deserialization refer to the process of taking program-internal object-related data, packaging it in a way that allows the data to be externally stored or transferred ("serialization"), then extracting the serialized data to reconstruct the original object ("deserialization").

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory858CERT Java Secure Coding Section 13 - Serialization (SER)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfWeakness ClassWeakness Class913Improper Control of Dynamically-Managed Code Resources
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory994SFP Secondary Cluster: Tainted Input to Variable
Software Fault Pattern (SFP) Clusters (primary)888
PeerOfWeakness BaseWeakness Base915Improperly Controlled Modification of Dynamically-Determined Object Attributes
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
CLASPDeserialization of untrusted data
CERT Java Secure CodingSER01-JDo not deviate from the proper signatures of serialization methods
CERT Java Secure CodingSER03-JDo not serialize unencrypted, sensitive data
CERT Java Secure CodingSER06-JMake defensive copies of private mutable components during deserialization
CERT Java Secure CodingSER08-JDo not use the default serialized form for implementation defined invariants
Software Fault PatternsSFP25Tainted input to variable
+ References
Matthias Kaiser. "Exploiting Deserialization Vulnerabilities in Java". 2015-10-28. <http://www.slideshare.net/codewhitesec/exploiting-deserialization-vulnerabilities-in-java-54707478>.
Sam Thomas. "PHP unserialization vulnerabilities: What are we missing?". 2015-08-27. <http://www.slideshare.net/_s_n_t/php-unserialization-vulnerabilities-what-are-we-missing>.
Gabriel Lawrence and Chris Frohoff. "Marshalling Pickles: How deserializing objects can ruin your day". 2015-01-28. <http://www.slideshare.net/frohoff1/appseccali-2015-marshalling-pickles>.
Heine Deelstra. "Unserializing user-supplied data, a bad idea". 2010-08-25. <http://heine.familiedeelstra.com/security/unserialize>.
Manish S. Saindane. "Black Hat EU 2010 - Attacking Java Serialized Communication". 2010-04-26. <http://www.slideshare.net/msaindane/black-hat-eu-2010-attacking-java-serialized-communication>.
Nadia Alramli. "Why Python Pickle is Insecure". 2009-09-09. <http://nadiana.com/python-pickle-insecure>.
Nelson Elhage. "Exploiting misuse of Python's "pickle"". 2011-03-20. <https://blog.nelhage.com/2011/03/exploiting-pickle/>.
Chris Frohoff. "Deserialize My Shorts: Or How I Learned to Start Worrying and Hate Java Object Deserialization". 2016-03-21. <https://www.slideshare.net/frohoff1/deserialize-my-shorts-or-how-i-learned-to-start-worrying-and-hate-java-object-deserialization>.
+ Maintenance Notes

The relationships between CWE-502 and CWE-915 need further exploration. CWE-915 is more narrowly scoped to object modification, and is not necessarily used for deserialization.

+ Content History
Submissions
Submission DateSubmitterOrganizationSource
CLASPExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Common_Consequences, Description, Relationships, Other_Notes, Taxonomy_Mappings
2009-10-29CWE Content TeamMITREInternal
updated Description, Other_Notes, Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-10-30CWE Content TeamMITREInternal
updated Demonstrative_Examples
2013-02-21CWE Content TeamMITREInternal
updated Alternate_Terms, Applicable_Platforms, Background_Details, Common_Consequences, Maintenance_Notes, Observed_Examples, Potential_Mitigations, References, Relationships
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2015-12-07CWE Content TeamMITREInternal
updated Observed_Examples, References, Relationships
2017-05-03CWE Content TeamMITREInternal
updated Applicable_Platforms, Demonstrative_Examples, Description, Potential_Mitigations, References

CWE-390: Detection of Error Condition Without Action

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

Description Summary

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

Languages

All

+ Common Consequences
ScopeEffect
Integrity
Other

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

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

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

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

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

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

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

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

Example 2

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

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

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

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

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

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

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

infile.close();

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

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

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

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

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

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

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

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

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

Example 3

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

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

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

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

// close file
fr.close();

retString = new String(cBuf);

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

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

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

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

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

// close file
fr.close();

retString = new String(cBuf);

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

Phase: Implementation

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

Phase: Implementation

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

Phase: Testing

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

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

CWE-369: Divide By Zero

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

Description Summary

The product divides a value by zero.

Extended Description

This weakness typically occurs when an unexpected value is provided to the product, or if an error occurs that is not properly detected. It frequently occurs in calculations involving physical dimensions such as size, length, width, and height.

+ Time of Introduction
  • Implementation
+ Common Consequences
ScopeEffect
Availability

Technical Impact: DoS: crash / exit / restart

A Divide by Zero results in a crash.

+ Likelihood of Exploit

Medium

+ Demonstrative Examples

Example 1

The following Java example contains a function to compute an average but does not validate that the input value used as the denominator is not zero. This will create an exception for attempting to divide by zero. If this error is not handled by Java exception handling, unexpected results can occur.

(Bad Code)
Example Language: Java 
public int computeAverageResponseTime (int totalTime, int numRequests) {
return totalTime / numRequests;
}

By validating the input value used as the denominator the following code will ensure that a divide by zero error will not cause unexpected results. The following Java code example will validate the input value, output an error message, and throw an exception.

(Good Code)
 
public int computeAverageResponseTime (int totalTime, int numRequests) throws ArithmeticException {
if (numRequests == 0) {
System.out.println("Division by zero attempted!");
throw ArithmeticException;
}
return totalTime / numRequests;
}

Example 2

The following C/C++ example contains a function that divides two numeric values without verifying that the input value used as the denominator is not zero. This will create an error for attempting to divide by zero, if this error is not caught by the error handling capabilities of the language, unexpected results can occur.

(Bad Code)
Example Languages: C and C++ 
double divide(double x, double y){
return x/y;
}

By validating the input value used as the denominator the following code will ensure that a divide by zero error will not cause unexpected results. If the method is called and a zero is passed as the second argument a DivideByZero error will be thrown and should be caught by the calling block with an output message indicating the error.

(Good Code)
 
const int DivideByZero = 10;
double divide(double x, double y){
if ( 0 == y ){
throw DivideByZero;
}
return x/y;
}
...
try{
divide(10, 0);
}
catch( int i ){
if(i==DivideByZero) {
cerr<<"Divide by zero error";
}
}

Example 3

The following C# example contains a function that divides two numeric values without verifying that the input value used as the denominator is not zero. This will create an error for attempting to divide by zero, if this error is not caught by the error handling capabilities of the language, unexpected results can occur.

(Bad Code)
Example Language: C# 
int Division(int x, int y){
return (x / y);
}

The method can be modified to raise, catch and handle the DivideByZeroException if the input value used as the denominator is zero.

(Good Code)
 
int SafeDivision(int x, int y){
try{
return (x / y);
}
catch (System.DivideByZeroException dbz){
System.Console.WriteLine("Division by zero attempted!");
return 0;
}
}

Example 3 References:

+ Observed Examples
ReferenceDescription
Invalid size value leads to divide by zero.
"Empty" content triggers divide by zero.
Height value of 0 triggers divide by zero.
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class682Incorrect Calculation
Development Concepts (primary)699
Research Concepts (primary)1000
Weaknesses for Simplified Mapping of Published Vulnerabilities (primary)1003
ChildOfCategoryCategory730OWASP Top Ten 2004 Category A9 - Denial of Service
Weaknesses in OWASP Top Ten (2004) (primary)711
ChildOfCategoryCategory738CERT C Secure Coding Section 04 - Integers (INT)
Weaknesses Addressed by the CERT C Secure Coding Standard (primary)734
ChildOfCategoryCategory739CERT C Secure Coding Section 05 - Floating Point (FLP)
Weaknesses Addressed by the CERT C Secure Coding Standard734
ChildOfCategoryCategory848CERT Java Secure Coding Section 03 - Numeric Types and Operations (NUM)
Weaknesses Addressed by the CERT Java Secure Coding Standard (primary)844
ChildOfCategoryCategory872CERT C++ Secure Coding Section 04 - Integers (INT)
Weaknesses Addressed by the CERT C++ Secure Coding Standard (primary)868
ChildOfCategoryCategory873CERT C++ Secure Coding Section 05 - Floating Point Arithmetic (FLP)
Weaknesses Addressed by the CERT C++ Secure Coding Standard868
ChildOfCategoryCategory998SFP Secondary Cluster: Glitch in Computation
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
OWASP Top Ten 2004A9CWE More SpecificDenial of Service
CERT C Secure CodingFLP03-CDetect and handle floating point errors
CERT C Secure CodingINT33-CEnsure that division and modulo operations do not result in divide-by-zero errors
CERT Java Secure CodingNUM02-JEnsure that division and modulo operations do not result in divide-by-zero errors
CERT C++ Secure CodingINT33-CPPEnsure that division and modulo operations do not result in divide-by-zero errors
CERT C++ Secure CodingFLP03-CPPDetect and handle floating point errors
Software Fault PatternsSFP1Glitch in computation
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Sean EidemillerCigitalExternal
added/updated demonstrative examples
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Common_Consequences, Description, Relationships, Other_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
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences, Relationships, Taxonomy_Mappings
2011-09-13CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2012-05-11CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2014-07-30CWE Content TeamMITREInternal
updated Relationships, Taxonomy_Mappings
2015-12-07CWE Content TeamMITREInternal
updated Relationships

CWE-174: Double Decoding of the Same Data

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

Description Summary

The software decodes the same input twice, which can limit the effectiveness of any protection mechanism that occurs in between the decoding operations.
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

All

+ Common Consequences
ScopeEffect
Access Control
Confidentiality
Availability
Integrity
Other

Technical Impact: Bypass protection mechanism; Execute unauthorized code or commands; Varies by context

+ Observed Examples
ReferenceDescription
Forum software improperly URL decodes the highlight parameter when extracting text to highlight, which allows remote attackers to execute arbitrary PHP code by double-encoding the highlight value so that special characters are inserted into the result.
XSS protection mechanism attempts to remove "/" that could be used to close tags, but it can be bypassed using double encoded slashes (%252F)
Directory traversal using double encoding.
"%2527" (double-encoded single quote) used in SQL injection.
Double hex-encoded data.
Browser executes HTML at higher privileges via URL with hostnames that are double hex encoded, which are decoded twice to generate a malicious hostname.
+ Potential Mitigations

Phase: Architecture and Design

Strategy: Input Validation

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

Phase: Implementation

Strategy: Input Validation

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

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

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

Phase: Implementation

Strategy: Output Encoding

Use and specify an output encoding that can be handled by the downstream component that is reading the output. Common encodings include ISO-8859-1, UTF-7, and UTF-8. When an encoding is not specified, a downstream component may choose a different encoding, either by assuming a default encoding or automatically inferring which encoding is being used, which can be erroneous. When the encodings are inconsistent, the downstream component might treat some character or byte sequences as special, even if they are not special in the original encoding. Attackers might then be able to exploit this discrepancy and conduct injection attacks; they even might be able to bypass protection mechanisms that assume the original encoding is also being used by the downstream component.

Phase: Implementation

Strategy: Input Validation

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

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness ClassWeakness Class172Encoding Error
Development Concepts (primary)699
Research Concepts1000
ChildOfWeakness ClassWeakness Class675Duplicate Operations on Resource
Research Concepts (primary)1000
ChildOfCategoryCategory992SFP Secondary Cluster: Faulty Input Transformation
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Research Gaps

Probably under-studied.

+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERDouble Encoding
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Potential_Mitigations
2008-09-08CWE Content TeamMITREInternal
updated Relationships, Observed_Example, Taxonomy_Mappings
2008-11-24CWE Content TeamMITREInternal
updated Observed_Examples
2009-07-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-03-29CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Observed_Examples, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2008-04-11Double Encoding

CWE-494: Download of Code Without Integrity Check

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

Description Summary

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

Extended Description

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

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

Languages

Language-independent

+ Common Consequences
ScopeEffect
Integrity
Availability
Confidentiality
Other

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

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

+ Likelihood of Exploit

Medium

+ Detection Methods

Manual Analysis

This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session.

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

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

Black Box

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

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

+ Demonstrative Examples

Example 1

This example loads an external class from a local subdirectory.

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

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

Example 2

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

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

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

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

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

Phase: Implementation

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

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

Phases: Architecture and Design; Operation

Encrypt the code with a reliable encryption scheme before transmitting.

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

Phase: Architecture and Design

Strategy: Libraries or Frameworks

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

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

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

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

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

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

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

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

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

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

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

Effectiveness: Limited

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

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

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

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

CWE-627: Dynamic Variable Evaluation

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

Description Summary

In a language where the user can influence the name of a variable at runtime, if the variable names are not controlled, an attacker can read or write to arbitrary variables, or access arbitrary functions.

Extended Description

The resultant vulnerabilities depend on the behavior of the application, both at the crossover point and in any control/data flow that is reachable by the related variables or functions.

+ Alternate Terms
Dynamic evaluation
+ Time of Introduction
  • Implementation
+ Applicable Platforms

Languages

PHP

Perl

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability

Technical Impact: Modify application data; Execute unauthorized code or commands

An attacker could gain unauthorized access to internal program variables and execute arbitrary code.

+ Observed Examples
ReferenceDescription
Chain: Dynamic variable evaluation allows resultant remote file inclusion and path traversal.
Chain: dynamic variable evaluation in PHP program used to modify critical, unexpected $_SERVER variable for resultant XSS.
Chain: dynamic variable evaluation in PHP program used to conduct remote file inclusion.
Dynamic variable evaluation in mail program allows reading and modifying attachments and preferences of other users.
+ Potential Mitigations

Phase: Implementation

Strategy: Refactoring

Refactor the code to avoid dynamic variable evaluation whenever possible.

Phase: Implementation

Strategy: Input Validation

Use only whitelists of acceptable variable or function names.

Phase: Implementation

For function names, ensure that you are only calling functions that accept the proper number of arguments, to avoid unexpected null arguments.

+ Background Details

Many interpreted languages support the use of a "$$varname" construct to set a variable whose name is specified by the $varname variable. In PHP, these are referred to as "variable variables." Functions might also be invoked using similar syntax, such as $$funcname(arg1, arg2).

+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfWeakness BaseWeakness Base914Improper Control of Dynamically-Identified Variables
Development Concepts (primary)699
Research Concepts (primary)1000
ChildOfCategoryCategory990SFP Secondary Cluster: Tainted Input to Command
Software Fault Pattern (SFP) Clusters (primary)888
PeerOfWeakness BaseWeakness Base183Permissive Whitelist
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ Research Gaps

Under-studied, probably under-reported. Few researchers look for this issue; most public reports are for PHP, although other languages are affected. This issue is likely to grow in PHP as developers begin to implement functionality in place of register_globals.

+ References
Steve Christey. "Dynamic Evaluation Vulnerabilities in PHP applications". Full-Disclosure. 2006-05-03. <http://seclists.org/fulldisclosure/2006/May/0035.html>.
Shaun Clowes. "A Study In Scarlet: Exploiting Common Vulnerabilities in PHP Applications". <http://www.securereality.com.au/studyinscarlet.txt>.
+ Content History
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Applicable_Platforms, Relationships
2008-10-14CWE Content TeamMITREInternal
updated Background_Details, Description
2011-03-29CWE Content TeamMITREInternal
updated Description
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
2013-02-21CWE Content TeamMITREInternal
updated Common_Consequences, Observed_Examples, Potential_Mitigations, Relationships, Weakness_Ordinalities
2014-07-30CWE Content TeamMITREInternal
updated Relationships

CWE-698: Execution After Redirect (EAR)

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

Description Summary

The web application sends a redirect to another location, but instead of exiting, it executes additional code.
+ Alternate Terms
Redirect Without Exit
+ Time of Introduction
  • Implementation
+ Common Consequences
ScopeEffect
Other
Confidentiality
Integrity
Availability

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

This weakness could affect the control flow of the application and allow execution of untrusted code.

+ Detection Methods

Black Box

This issue might not be detected if testing is performed using a web browser, because the browser might obey the redirect and move the user to a different page before the application has produced outputs that indicate something is amiss.

+ Demonstrative Examples

Example 1

This code queries a server and displays its status when a request comes from an authorized IP address.

(Bad Code)
Example Language: PHP 
$requestingIP = $_SERVER['REMOTE_ADDR'];
if(!in_array($requestingIP,$ipWhitelist)){
echo "You are not authorized to view this page";
http_redirect($errorPageURL);
}
$status = getServerStatus();
echo $status;
...

This code redirects unauthorized users, but continues to execute code after calling http_redirect(). This means even unauthorized users may be able to access the contents of the page or perform a DoS attack on the server being queried. Also, note that this code is vulnerable to an IP address spoofing attack (CWE-212).

+ Observed Examples
ReferenceDescription
Execution-after-redirect allows access to application configuration details.
chain: library file sends a redirect if it is directly requested but continues to execute, allowing remote file inclusion and path traversal.
Remote attackers can obtain access to administrator functionality through EAR.
Remote attackers can obtain access to administrator functionality through EAR.
Bypass of authentication step through EAR.
Chain: Execution after redirect triggers eval injection.
chain: execution after redirect allows non-administrator to perform static code injection.
+ Weakness Ordinalities
OrdinalityDescription
Primary
(where the weakness exists independent of other weaknesses)
+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory361Time and State
Development Concepts (primary)699
ChildOfWeakness ClassWeakness Class670Always-Incorrect Control Flow Implementation
Research Concepts1000
ChildOfWeakness ClassWeakness Class705Incorrect Control Flow Scoping
Research Concepts (primary)1000
ChildOfCategoryCategory977SFP Secondary Cluster: Design
Software Fault Pattern (SFP) Clusters (primary)888
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
+ References
Adam Doupé, Bryce Boe, Christopher Kruegel and Giovanni Vigna. "Fear the EAR: Discovering and Mitigating Execution After Redirect Vulnerabilities". <http://cs.ucsb.edu/~bboe/public/pubs/fear-the-ear-ccs2011.pdf>.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
2008-09-09MITREInternal CWE Team
Modifications
Modification DateModifierOrganizationSource
2011-06-01CWE Content TeamMITREInternal
updated Common_Consequences
2012-05-11CWE Content TeamMITREInternal
updated Common_Consequences, Demonstrative_Examples, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Demonstrative_Examples
2013-02-21CWE Content TeamMITREInternal
updated Alternate_Terms, Name, Observed_Examples, References
2014-07-30CWE Content TeamMITREInternal
updated Relationships
Previous Entry Names
Change DatePrevious Entry Name
2013-02-21Redirect Without Exit

CWE-250: Execution with Unnecessary Privileges

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

Description Summary

The software performs an operation at a privilege level that is higher than the minimum level required, which creates new weaknesses or amplifies the consequences of other weaknesses.

Extended Description

New weaknesses can be exposed because running with extra privileges, such as root or Administrator, can disable the normal security checks being performed by the operating system or surrounding environment. Other pre-existing weaknesses can turn into security vulnerabilities if they occur while operating at raised privileges.

Privilege management functions can behave in some less-than-obvious ways, and they have different quirks on different platforms. These inconsistencies are particularly pronounced if you are transitioning from one non-root user to another. Signal handlers and spawned processes run at the privilege of the owning process, so if a process is running as root when a signal fires or a sub-process is executed, the signal handler or sub-process will operate with root privileges.

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

Languages

Language-independent

Architectural Paradigms

Mobile Application

+ Modes of Introduction

If an application has this design problem, then it can be easier for the developer to make implementation-related errors such as CWE-271 (Privilege Dropping / Lowering Errors). In addition, the consequences of Privilege Chaining (CWE-268) can become more severe.

+ Common Consequences
ScopeEffect
Confidentiality
Integrity
Availability
Access Control

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

An attacker will be able to gain access to any resources that are allowed by the extra privileges. Common results include executing code, disabling services, and reading restricted data.

+ Likelihood of Exploit

Medium

+ Detection Methods

Manual Analysis

This weakness can be detected using tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session.

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

Black Box

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

Attach the monitor to the process and perform a login. Look for library functions and system calls that indicate when privileges are being raised or dropped. Look for accesses of resources that are restricted to normal users.

Note that this technique is only useful for privilege issues related to system resources. It is not likely to detect application-level business rules that are related to privileges, such as if a blog system allows a user to delete a blog entry without first checking that the user has administrator privileges.

Automated Static Analysis - Binary / Bytecode

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

Highly cost effective:

  • Compare binary / bytecode to application permission manifest

Cost effective for partial coverage:

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

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

Effectiveness: SOAR High

Manual Static Analysis - Binary / Bytecode

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

Cost effective for partial coverage:

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

Effectiveness: SOAR Partial

Dynamic Analysis with automated results interpretation

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

Cost effective for partial coverage:

  • Host-based Vulnerability Scanners – Examine configuration for flaws, verifying that audit mechanisms work, ensure host configuration meets certain predefined criteria

Effectiveness: SOAR Partial

Dynamic Analysis with manual results interpretation

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

Cost effective for partial coverage:

  • Host Application Interface Scanner

Effectiveness: SOAR Partial

Manual Static Analysis - Source Code

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

Highly cost effective:

  • Manual Source Code Review (not inspections)

Cost effective for partial coverage:

  • Focused Manual Spotcheck - Focused manual analysis of source