Home > CWE List > VIEW SLICE: CWE-1178: Weaknesses Addressed by the SEI CERT Perl Coding Standard (4.16) |
|
CWE VIEW: Weaknesses Addressed by the SEI CERT Perl Coding Standard
CWE entries in this view (graph) are fully or partially eliminated by following the guidance presented in the online wiki that reflects that current rules and recommendations of the SEI CERT Perl Coding Standard.
The following graph shows the tree-like relationships between
weaknesses that exist at different levels of abstraction. At the highest level, categories
and pillars exist to group weaknesses. Categories (which are not technically weaknesses) are
special CWE entries used to group weaknesses that share a common characteristic. Pillars are
weaknesses that are described in the most abstract fashion. Below these top-level entries
are weaknesses are varying levels of abstraction. Classes are still very abstract, typically
independent of any specific language or technology. Base level weaknesses are used to
present a more specific type of weakness. A variant is a weakness that is described at a
very low level of detail, typically limited to a specific language or technology. A chain is
a set of weaknesses that must be reachable consecutively in order to produce an exploitable
vulnerability. While a composite is a set of weaknesses that must all be present
simultaneously in order to produce an exploitable vulnerability.
Show Details:
1178 - Weaknesses Addressed by the SEI CERT Perl Coding Standard
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)
- (1179)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS))
Weaknesses in this category are related to the rules and recommendations in the Input Validation and Data Sanitization (IDS) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
- (22)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
22
(Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal'))
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
Directory traversal
Path traversal
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Use of Externally-Controlled Format String
- (134)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
134
(Use of Externally-Controlled Format String)
The product uses a function that accepts a format string as an argument, but the format string originates from an external source.
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Improper Validation of Array Index
- (129)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
129
(Improper Validation of Array Index)
The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
out-of-bounds array index
index-out-of-range
array index underflow
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Memory Allocation with Excessive Size Value
- (789)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
789
(Memory Allocation with Excessive Size Value)
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
Stack Exhaustion
Class - a weakness that is described in a very abstract fashion, typically independent of any specific language or technology. More specific than a Pillar Weakness, but more general than a Base Weakness. Class level weaknesses typically describe issues in terms of 1 or 2 of the following dimensions: behavior, property, and resource.
Improper Encoding or Escaping of Output
- (116)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
116
(Improper Encoding or Escaping of Output)
The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.
Output Sanitization
Output Validation
Output Encoding
Class - a weakness that is described in a very abstract fashion, typically independent of any specific language or technology. More specific than a Pillar Weakness, but more general than a Base Weakness. Class level weaknesses typically describe issues in terms of 1 or 2 of the following dimensions: behavior, property, and resource.
Improper Neutralization of Special Elements used in a Command ('Command Injection')
- (77)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
77
(Improper Neutralization of Special Elements used in a Command ('Command Injection'))
The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
Command injection
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
- (95)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1179
(SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)) >
95
(Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'))
The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before using the input in a dynamic evaluation call (e.g. "eval").
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)
- (1180)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1180
(SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL))
Weaknesses in this category are related to the rules and recommendations in the Declarations and Initialization (DCL) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Function Call with Incorrectly Specified Arguments
- (628)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1180
(SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)) >
628
(Function Call with Incorrectly Specified Arguments)
The product calls a function, procedure, or routine with arguments that are not correctly specified, leading to always-incorrect behavior and resultant weaknesses.
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Missing Initialization of a Variable
- (456)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1180
(SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)) >
456
(Missing Initialization of a Variable)
The product does not initialize critical variables, which causes the execution environment to use unexpected values.
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Use of Uninitialized Variable
- (457)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1180
(SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)) >
457
(Use of Uninitialized Variable)
The code uses a variable that has not been initialized, leading to unpredictable or unintended results.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Use of Obsolete Function
- (477)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1180
(SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)) >
477
(Use of Obsolete Function)
The code uses deprecated or obsolete functions, which suggests that the code has not been actively reviewed or maintained.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)
- (1181)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP))
Weaknesses in this category are related to the rules and recommendations in the Expressions (EXP) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Unexpected Status Code or Return Value
- (394)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
394
(Unexpected Status Code or Return Value)
The product does not properly check when a function or operation returns a value that is legitimate for the function, but is not expected by the product.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Operator Precedence Logic Error
- (783)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
783
(Operator Precedence Logic Error)
The product uses an expression in which operator precedence causes incorrect logic to be used.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Use of Obsolete Function
- (477)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
477
(Use of Obsolete Function)
The code uses deprecated or obsolete functions, which suggests that the code has not been actively reviewed or maintained.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Uncaught Exception
- (248)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
248
(Uncaught Exception)
An exception is thrown from a function, but it is not caught.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Unchecked Error Condition
- (391)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
391
(Unchecked Error Condition)
[PLANNED FOR DEPRECATION. SEE MAINTENANCE NOTES AND CONSIDER CWE-252, CWE-248, OR CWE-1069.] Ignoring exceptions and other error conditions may allow an attacker to induce unexpected behavior unnoticed.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Improper Cleanup on Thrown Exception
- (460)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
460
(Improper Cleanup on Thrown Exception)
The product does not clean up its state or incorrectly cleans up its state when an exception is thrown, leading to unexpected state or control flow.
Class - a weakness that is described in a very abstract fashion, typically independent of any specific language or technology. More specific than a Pillar Weakness, but more general than a Base Weakness. Class level weaknesses typically describe issues in terms of 1 or 2 of the following dimensions: behavior, property, and resource.
Incorrect Control Flow Scoping
- (705)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
705
(Incorrect Control Flow Scoping)
The product does not properly return control flow to the proper location after it has completed a task or detected an unusual condition.
Class - a weakness that is described in a very abstract fashion, typically independent of any specific language or technology. More specific than a Pillar Weakness, but more general than a Base Weakness. Class level weaknesses typically describe issues in terms of 1 or 2 of the following dimensions: behavior, property, and resource.
Improper Check for Unusual or Exceptional Conditions
- (754)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
754
(Improper Check for Unusual or Exceptional Conditions)
The product does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the product.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Unchecked Return Value
- (252)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
252
(Unchecked Return Value)
The product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.
Chain - a Compound Element that is a sequence of two or more separate weaknesses that can be closely linked together within software. One weakness, X, can directly create the conditions that are necessary to cause another weakness, Y, to enter a vulnerable condition. When this happens, CWE refers to X as "primary" to Y, and Y is "resultant" from X. Chains can involve more than two weaknesses, and in some cases, they might have a tree-like structure.
Unchecked Return Value to NULL Pointer Dereference
- (690)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
690
(Unchecked Return Value to NULL Pointer Dereference)
The product does not check for an error after calling a function that can return with a NULL pointer if the function fails, which leads to a resultant NULL pointer dereference.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Function Call with Incorrectly Specified Arguments
- (628)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
628
(Function Call with Incorrectly Specified Arguments)
The product calls a function, procedure, or routine with arguments that are not correctly specified, leading to always-incorrect behavior and resultant weaknesses.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Returning a Mutable Object to an Untrusted Caller
- (375)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
375
(Returning a Mutable Object to an Untrusted Caller)
Sending non-cloned mutable data as a return value may result in that data being altered or deleted by the calling function.
Variant - a weakness that is linked to a certain type of product, typically involving a specific language or technology. More specific than a Base weakness. Variant level weaknesses typically describe issues in terms of 3 to 5 of the following dimensions: behavior, property, technology, language, and resource.
Use of Wrong Operator in String Comparison
- (597)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1181
(SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)) >
597
(Use of Wrong Operator in String Comparison)
The product uses the wrong operator when comparing a string, such as using "==" when the .equals() method should be used instead.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 04. Integers (INT)
- (1182)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1182
(SEI CERT Perl Coding Standard - Guidelines 04. Integers (INT))
Weaknesses in this category are related to the rules and recommendations in the Integers (INT) section of the SEI CERT Perl Coding Standard.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
Numeric Errors
- (189)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1182
(SEI CERT Perl Coding Standard - Guidelines 04. Integers (INT)) >
189
(Numeric Errors)
Weaknesses in this category are related to improper calculation or conversion of numbers.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 05. Strings (STR)
- (1183)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1183
(SEI CERT Perl Coding Standard - Guidelines 05. Strings (STR))
Weaknesses in this category are related to the rules and recommendations in the Strings (STR) section of the SEI CERT Perl Coding Standard.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 06. Object-Oriented Programming (OOP)
- (1184)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1184
(SEI CERT Perl Coding Standard - Guidelines 06. Object-Oriented Programming (OOP))
Weaknesses in this category are related to the rules and recommendations in the Object-Oriented Programming (OOP) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Access to Critical Private Variable via Public Method
- (767)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1184
(SEI CERT Perl Coding Standard - Guidelines 06. Object-Oriented Programming (OOP)) >
767
(Access to Critical Private Variable via Public Method)
The product defines a public method that reads or modifies a private variable.
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 07. File Input and Output (FIO)
- (1185)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1185
(SEI CERT Perl Coding Standard - Guidelines 07. File Input and Output (FIO))
Weaknesses in this category are related to the rules and recommendations in the File Input and Output (FIO) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Improper Link Resolution Before File Access ('Link Following')
- (59)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1185
(SEI CERT Perl Coding Standard - Guidelines 07. File Input and Output (FIO)) >
59
(Improper Link Resolution Before File Access ('Link Following'))
The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
insecure temporary file
Zip Slip
Category - a CWE entry that contains a set of other entries that share a common characteristic.
SEI CERT Perl Coding Standard - Guidelines 50. Miscellaneous (MSC)
- (1186)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1186
(SEI CERT Perl Coding Standard - Guidelines 50. Miscellaneous (MSC))
Weaknesses in this category are related to the rules and recommendations in the Miscellaneous (MSC) section of the SEI CERT Perl Coding Standard.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Dead Code
- (561)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1186
(SEI CERT Perl Coding Standard - Guidelines 50. Miscellaneous (MSC)) >
561
(Dead Code)
The product contains dead code, which can never be executed.
Base - a weakness that is still mostly independent of a resource or technology, but with sufficient details to provide specific methods for detection and prevention. Base level weaknesses typically describe issues in terms of 2 or 3 of the following dimensions: behavior, property, technology, language, and resource.
Assignment to Variable without Use
- (563)
1178
(Weaknesses Addressed by the SEI CERT Perl Coding Standard) >
1186
(SEI CERT Perl Coding Standard - Guidelines 50. Miscellaneous (MSC)) >
563
(Assignment to Variable without Use)
The variable's value is assigned but never used, making it a dead store.
Unused Variable
Relationship
The relationships in this view were determined based on specific statements within the rules from the standard. Not all rules have direct relationships to individual weaknesses, although they likely have chaining relationships in specific circumstances.
View ComponentsA | 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-767: Access to Critical Private Variable via Public Method
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom Filter
If an attacker modifies the variable to contain unexpected values, this could violate assumptions from other parts of the code. Additionally, if an attacker can read the private variable, it may expose sensitive information or make it easier to launch further attacks.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C++ (Undetermined Prevalence) C# (Undetermined Prevalence) Java (Undetermined Prevalence) Example 1 The following example declares a critical variable to be private, and then allows the variable to be modified by public methods. (bad code)
Example Language: C++
private: float price;
public: void changePrice(float newPrice) { price = newPrice; }Example 2 The following example could be used to implement a user forum where a single user (UID) can switch between multiple profiles (PID). (bad code)
Example Language: Java
public class Client {
private int UID; }public int PID; private String userName; public Client(String userName){ PID = getDefaultProfileID(); }UID = mapUserNametoUID( userName ); this.userName = userName; public void setPID(int ID) { UID = ID; }The programmer implemented setPID with the intention of modifying the PID variable, but due to a typo. accidentally specified the critical variable UID instead. If the program allows profile IDs to be between 1 and 10, but a UID of 1 means the user is treated as an admin, then a user could gain administrative privileges as a result of this typo.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Maintenance
This entry is closely associated with access control for public methods. If the public methods are restricted with proper access controls, then the information in the private variable will not be exposed to unexpected parties. There may be chaining or composite relationships between improper access controls and this weakness.
CWE-563: Assignment to Variable without Use
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom Filter
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.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
Example 1 The following code excerpt assigns to the variable r and then overwrites the value without using it. (bad code)
Example Language: C
r = getName();
r = getNewBuffer(buf);
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-561: Dead Code
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom Filter
Dead code is 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.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The condition for the second if statement is impossible to satisfy. It requires that the variables be non-null. However, 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"; }
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-628: Function Call with Incorrectly Specified Arguments
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product calls a function, procedure, or routine with arguments that are not correctly specified, leading to always-incorrect behavior and resultant weaknesses.
There are multiple ways in which this weakness can be introduced, including:
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following PHP method authenticates a user given a username/password combination but is called with the parameters in reverse order. (bad code)
Example Language: PHP
function authenticate($username, $password) {
// authenticate user ... authenticate($_POST['password'], $_POST['username']); Example 2 This Perl code intends to record whether a user authenticated successfully or not, and to exit if the user fails to authenticate. However, when it calls ReportAuth(), the third argument is specified as 0 instead of 1, so it does not exit. (bad code)
Example Language: Perl
sub ReportAuth {
my ($username, $result, $fatal) = @_; }PrintLog("auth: username=%s, result=%d", $username, $result); if (($result ne "success") && $fatal) { die "Failed!\n"; }sub PrivilegedFunc { my $result = CheckAuth($username); }ReportAuth($username, $result, 0); DoReallyImportantStuff(); Example 3 In the following Java snippet, the accessGranted() method is accidentally called with the static ADMIN_ROLES array rather than the user roles. (bad code)
Example Language: Java
private static final String[] ADMIN_ROLES = ...;
public boolean void accessGranted(String resource, String user) { String[] userRoles = getUserRoles(user); }return accessGranted(resource, ADMIN_ROLES); private boolean void accessGranted(String resource, String[] userRoles) { // grant or deny access based on user roles ...
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-754: Improper Check for Unusual or Exceptional Conditions
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the product.
The programmer may assume that certain events or conditions will never occur or do not need to be worried about, such as low memory conditions, lack of access to resources due to restrictive permissions, or misbehaving clients or components. However, attackers may intentionally trigger these unusual conditions, thus violating the programmer's assumptions, possibly introducing instability, incorrect behavior, or a vulnerability. Note that this entry is not exclusively about the use of exceptions and exception handling, which are mechanisms for both checking and handling unusual or unexpected conditions. This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
Relevant to the view "Architectural Concepts" (CWE-1008)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 Consider the following code segment: (bad code)
Example Language: C
char buf[10], cp_buf[10];
fgets(buf, 10, stdin); strcpy(cp_buf, buf); The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy(). Example 2 The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc(). (bad code)
Example Language: C
buf = (char*) malloc(req_size);
strncpy(buf, xfer, req_size); The traditional defense of this coding error is: "If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or simply allow the program to die with a segmentation fault when it tries to dereference the null pointer." This argument ignores three important considerations:
Example 3 The following examples read a file into a byte array. (bad code)
Example Language: C#
char[] byteArray = new char[1024];
for (IEnumerator i=users.GetEnumerator(); i.MoveNext() ;i.Current()) { String userName = (String) i.Current(); }String pFileName = PFILE_ROOT + "/" + userName; StreamReader sr = new StreamReader(pFileName); sr.Read(byteArray,0,1024);//the file is always 1k bytes sr.Close(); processPFile(userName, byteArray); (bad code)
Example Language: Java
FileInputStream fis;
byte[] byteArray = new byte[1024]; for (Iterator i=users.iterator(); i.hasNext();) { String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName; FileInputStream fis = new FileInputStream(pFileName); fis.read(byteArray); // the file is always 1k bytes fis.close(); processPFile(userName, byteArray); The code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always 1 kilobyte in size and therefore ignores the return value from Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and treat it as though it belongs to the attacker. Example 4 The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference. (bad code)
Example Language: Java
String itemName = request.getParameter(ITEM_NAME);
if (itemName.compareTo(IMPORTANT_ITEM) == 0) { ... }... The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference. (bad code)
Example Language: Java
String itemName = request.Item(ITEM_NAME);
if (itemName.Equals(IMPORTANT_ITEM)) { ... }... The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved. Example 5 The following code shows a system property that is set to null and later dereferenced by a programmer who mistakenly assumes it will always be defined. (bad code)
Example Language: Java
System.clearProperty("os.name");
... String os = System.getProperty("os.name"); if (os.equalsIgnoreCase("Windows 95")) System.out.println("Not supported"); The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or simply allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved. Example 6 The following VB.NET code does not check to make sure that it has read 50 bytes from myfile.txt. This can cause DoDangerousOperation() to operate on an unexpected value. (bad code)
Example Language: C#
Dim MyFile As New FileStream("myfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
Dim MyArray(50) As Byte MyFile.Read(MyArray, 0, 50) DoDangerousOperation(MyArray(20)) In .NET, it is not uncommon for programmers to misunderstand Read() and related methods that are part of many System.IO classes. The stream and reader classes do not consider it to be unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested. Example 7 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: C
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr; char hostname[64]; in_addr_t inet_addr(const char *cp); /*routine that ensures user_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); If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119). Example 8 In the following C/C++ example the method outputStringToFile opens a file in the local filesystem and outputs a string to the file. The input parameters output and filename contain the string to output to the file and the name of the file respectively. (bad code)
Example Language: C++
int outputStringToFile(char *output, char *filename) {
openFileToWrite(filename); writeToFile(output); closeFile(filename); However, this code does not check the return values of the methods openFileToWrite, writeToFile, closeFile to verify that the file was properly opened and closed and that the string was successfully written to the file. The return values for these methods should be checked to determine if the method was successful and allow for detection of errors or unexpected conditions as in the following example. (good code)
Example Language: C++
int outputStringToFile(char *output, char *filename) {
int isOutput = SUCCESS;
int isOpen = openFileToWrite(filename); if (isOpen == FAIL) { printf("Unable to open file %s", filename); }isOutput = FAIL; else { int isWrite = writeToFile(output);
if (isWrite == FAIL) { printf("Unable to write to file %s", filename); }isOutput = FAIL; int isClose = closeFile(filename); if (isClose == FAIL) isOutput = FAIL;
return isOutput; Example 9 In the following Java example the method readFromFile uses a FileReader object to read the contents of a file. The FileReader object is created using the File object readFile, the readFile object is initialized using the setInputFile method. The setInputFile method should be called before calling the readFromFile method. (bad code)
Example Language: Java
private File readFile = null;
public void setInputFile(String inputFile) { // create readFile File object from string containing name of file public void readFromFile() { try {
reader = new FileReader(readFile);
// read input file However, the readFromFile method does not check to see if the readFile object is null, i.e. has not been initialized, before creating the FileReader object and reading from the input file. The readFromFile method should verify whether the readFile object is null and output an error message and raise an exception if the readFile object is null, as in the following code. (good code)
Example Language: Java
private File readFile = null;
public void setInputFile(String inputFile) { // create readFile File object from string containing name of file public void readFromFile() { try {
if (readFile == null) {
System.err.println("Input file has not been set, call setInputFile method before calling openInputFile"); }throw NullPointerException; reader = new FileReader(readFile); // read input file catch (NullPointerException ex) {...}
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
Sometimes, when a return value can be used to indicate an error, an unchecked return value is a code-layer instance of a missing application-layer check for exceptional conditions. However, return values are not always needed to communicate exceptional conditions. For example, expiration of resources, values passed by reference, asynchronously modified data, sockets, etc. may indicate exceptional conditions without the use of a return value.
CWE-460: Improper Cleanup on Thrown Exception
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not clean up its state or incorrectly cleans up its state when an exception is thrown, leading to unexpected state or control flow.
Often, when functions or loops become complicated, some level of resource cleanup is needed throughout execution. Exceptions can disturb the flow of the code and prevent the necessary cleanup from happening.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Architectural Concepts" (CWE-1008)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Undetermined Prevalence) C++ (Undetermined Prevalence) Java (Undetermined Prevalence) C# (Undetermined Prevalence) Example 1 The following example demonstrates the weakness. (bad code)
Example Language: Java
public class foo {
public static final void main( String args[] ) {
boolean returnValue; returnValue=doStuff(); public static final boolean doStuff( ) { boolean threadLock; boolean truthvalue=true; try { while( //check some condition ) { threadLock=true; //do some stuff to truthvalue threadLock=false; catch (Exception e){ System.err.println("You did something bad"); if (something) return truthvalue; return truthvalue; In this case, a thread might be left locked accidentally.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-116: Improper Encoding or Escaping of Output
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.
Improper encoding or escaping can allow attackers to change the commands that are sent to another component, inserting malicious commands instead. Most products follow a certain protocol that uses structured messages for communication between components, such as queries or commands. These structured messages can contain raw data interspersed with metadata or control information. For example, "GET /index.html HTTP/1.1" is a structured message containing a command ("GET") with a single argument ("/index.html") and metadata about which protocol version is being used ("HTTP/1.1"). If an application uses attacker-supplied inputs to construct a structured message without properly encoding or escaping, then the attacker could insert special characters that will cause the data to be interpreted as control information or metadata. Consequently, the component that receives the output will perform the wrong operations, or otherwise interpret the data incorrectly. This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Often Prevalent) Technologies AI/ML (Undetermined Prevalence) Database Server (Often Prevalent) Web Server (Often Prevalent) Example 1 This code displays an email address that was submitted as part of a form. (bad code)
Example Language: JSP
<% String email = request.getParameter("email"); %>
... Email Address: <%= email %> The value read from the form parameter is reflected back to the client browser without having been encoded prior to output, allowing various XSS attacks (CWE-79). Example 2 Consider a chat application in which a front-end web application communicates with a back-end server. The back-end is legacy code that does not perform authentication or authorization, so the front-end must implement it. The chat protocol supports two commands, SAY and BAN, although only administrators can use the BAN command. Each argument must be separated by a single space. The raw inputs are URL-encoded. The messaging protocol allows multiple commands to be specified on the same line if they are separated by a "|" character. First let's look at the back end command processor code (bad code)
Example Language: Perl
$inputString = readLineFromFileHandle($serverFH);
# generate an array of strings separated by the "|" character. @commands = split(/\|/, $inputString); foreach $cmd (@commands) { # separate the operator from its arguments based on a single whitespace ($operator, $args) = split(/ /, $cmd, 2); $args = UrlDecode($args); if ($operator eq "BAN") { ExecuteBan($args); }elsif ($operator eq "SAY") { ExecuteSay($args); }The front end web application receives a command, encodes it for sending to the server, performs the authorization check, and sends the command to the server. (bad code)
Example Language: Perl
$inputString = GetUntrustedArgument("command");
($cmd, $argstr) = split(/\s+/, $inputString, 2); # removes extra whitespace and also changes CRLF's to spaces $argstr =~ s/\s+/ /gs; $argstr = UrlEncode($argstr); if (($cmd eq "BAN") && (! IsAdministrator($username))) { die "Error: you are not the admin.\n"; }# communicate with file server using a file handle $fh = GetServerFileHandle("myserver"); print $fh "$cmd $argstr\n"; It is clear that, while the protocol and back-end allow multiple commands to be sent in a single request, the front end only intends to send a single command. However, the UrlEncode function could leave the "|" character intact. If an attacker provides: (attack code)
SAY hello world|BAN user12
then the front end will see this is a "SAY" command, and the $argstr will look like "hello world | BAN user12". Since the command is "SAY", the check for the "BAN" command will fail, and the front end will send the URL-encoded command to the back end: (result)
SAY hello%20world|BAN%20user12
The back end, however, will treat these as two separate commands: (result)
SAY hello world
BAN user12 Notice, however, that if the front end properly encodes the "|" with "%7C", then the back end will only process a single command. Example 3 This example takes user input, passes it through an encoding scheme and then creates a directory specified by the user. (bad code)
Example Language: Perl
sub GetUntrustedInput {
return($ARGV[0]); }sub encode { my($str) = @_; }$str =~ s/\&/\&/gs; $str =~ s/\"/\"/gs; $str =~ s/\'/\'/gs; $str =~ s/\</\</gs; $str =~ s/\>/\>/gs; return($str); sub doit { my $uname = encode(GetUntrustedInput("username")); }print "<b>Welcome, $uname!</b><p>\n"; system("cd /home/$uname; /bin/ls -l"); The programmer attempts to encode dangerous characters, however the denylist for encoding is incomplete (CWE-184) and an attacker can still pass a semicolon, resulting in a chain with command injection (CWE-77). Additionally, the encoding routine is used inappropriately with command execution. An attacker doesn't even need to insert their own semicolon. The attacker can instead leverage the encoding routine to provide the semicolon to separate the commands. If an attacker supplies a string of the form: (attack code)
' pwd
then the program will encode the apostrophe and insert the semicolon, which functions as a command separator when passed to the system function. This allows the attacker to complete the command injection.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
This weakness is primary to all weaknesses related to injection (CWE-74) since the inherent nature of injection involves the violation of structured messages.
Relationship CWE-116 and CWE-20 have a close association because, depending on the nature of the structured message, proper input validation can indirectly prevent special characters from changing the meaning of a structured message. For example, by validating that a numeric ID field should only contain the 0-9 characters, the programmer effectively prevents injection attacks. However, input validation is not always sufficient, especially when less stringent data types must be supported, such as free-form text. Consider a SQL injection scenario in which a last name is inserted into a query. The name "O'Reilly" would likely pass the validation step since it is a common last name in the English language. However, it cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise neutralized. In this case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded. Terminology
The usage of the "encoding" and "escaping" terms varies widely. For example, in some programming languages, the terms are used interchangeably, while other languages provide APIs that use both terms for different tasks. This overlapping usage extends to the Web, such as the "escape" JavaScript function whose purpose is stated to be encoding. The concepts of encoding and escaping predate the Web by decades. Given such a context, it is difficult for CWE to adopt a consistent vocabulary that will not be misinterpreted by some constituency.
Theoretical
This is a data/directive boundary error in which data boundaries are not sufficiently enforced before it is sent to a different control sphere.
Research Gap
While many published vulnerabilities are related to insufficient output encoding, there is such an emphasis on input validation as a protection mechanism that the underlying causes are rarely described. Within CVE, the focus is primarily on well-understood issues like cross-site scripting and SQL injection. It is likely that this weakness frequently occurs in custom protocols that support multiple encodings, which are not necessarily detectable with automated techniques.
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterMany file operations are intended to take place within a restricted directory. By using special elements such as ".." and "/" separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. One of the most common special elements is the "../" sequence, which in most modern operating systems is interpreted as the parent directory of the current location. This is referred to as relative path traversal. Path traversal also covers the use of absolute pathnames such as "/usr/local/bin" to access unexpected files. This is referred to as absolute path traversal.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following code could be for a social networking application in which each user's profile information is stored in a separate file. All files are stored in a single directory. (bad code)
Example Language: Perl
my $dataPath = "/users/cwe/profiles";
my $username = param("user"); my $profilePath = $dataPath . "/" . $username; open(my $fh, "<", $profilePath) || ExitError("profile read error: $profilePath"); print "<ul>\n"; while (<$fh>) { print "<li>$_</li>\n"; }print "</ul>\n"; While the programmer intends to access files such as "/users/cwe/profiles/alice" or "/users/cwe/profiles/bob", there is no verification of the incoming user parameter. An attacker could provide a string such as: (attack code)
../../../etc/passwd
The program would generate a profile pathname like this: (result)
/users/cwe/profiles/../../../etc/passwd
When the file is opened, the operating system resolves the "../" during path canonicalization and actually accesses this file: (result)
/etc/passwd
As a result, the attacker could read the entire text of the password file. Notice how this code also contains an error message information leak (CWE-209) if the user parameter does not produce a file that exists: the full pathname is provided. Because of the lack of output encoding of the file that is retrieved, there might also be a cross-site scripting problem (CWE-79) if profile contains any HTML, but other code would need to be examined. Example 2 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 relative or 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 3 The following code takes untrusted input and uses a regular expression to filter "../" from the input. It then appends this result to the /home/user/ directory and attempts to read the file in the final resulting path. (bad code)
Example Language: Perl
my $Username = GetUntrustedInput();
$Username =~ s/\.\.\///; my $filename = "/home/user/" . $Username; ReadAndSendFile($filename); Since the regular expression does not have the /g global match modifier, it only removes the first instance of "../" it comes across. So an input value such as: (attack code)
../../../etc/passwd
will have the first "../" stripped, resulting in: (result)
../../etc/passwd
This value is then concatenated with the /home/user/ directory: (result)
/home/user/../../etc/passwd
which causes the /etc/passwd file to be retrieved once the operating system has resolved the ../ sequences in the pathname. This leads to relative path traversal (CWE-23). Example 4 The following code attempts to validate a given input path by checking it against an allowlist and once validated delete the given file. In this specific case, the path is considered valid if it starts with the string "/safe_dir/". (bad code)
Example Language: Java
String path = getInputPath();
if (path.startsWith("/safe_dir/")) { File f = new File(path); }f.delete() An attacker could provide an input such as this: (attack code)
/safe_dir/../important.dat
The software assumes that the path is valid because it starts with the "/safe_path/" sequence, but the "../" sequence will cause the program to delete the important.dat file in the parent directory Example 5 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) { } //end of for loopbw.write(line); }bw.newLine(); bw.flush(); bw.close(); } catch (IOException ex) {...} // output successful upload response HTML page // output unsuccessful upload response HTML page else {...} ...
This code does not perform a check on the type of the file being uploaded (CWE-434). 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-23). Since the code does not check the filename that is provided in the header, an attacker can use "../" sequences to write to files outside of the intended directory. 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. Example 6 This script intends to read a user-supplied file from the current directory. The user inputs the relative path to the file and the script uses Python's os.path.join() function to combine the path to the current working directory with the provided path to the specified file. This results in an absolute path to the desired file. If the file does not exist when the script attempts to read it, an error is printed to the user. (bad code)
Example Language: Python
import os
import sys def main():
filename = sys.argv[1]
main()
path = os.path.join(os.getcwd(), filename) try:
with open(path, 'r') as f:
except FileNotFoundError as e:
file_data = f.read()
print("Error - file not found")
However, if the user supplies an absolute path, the os.path.join() function will discard the path to the current working directory and use only the absolute path provided. For example, if the current working directory is /home/user/documents, but the user inputs /etc/passwd, os.path.join() will use only /etc/passwd, as it is considered an absolute path. In the above scenario, this would cause the script to access and read the /etc/passwd file. (good code)
Example Language: Python
import os
import sys def main():
filename = sys.argv[1]
main()
path = os.path.normpath(f"{os.getcwd()}{os.sep}{filename}") if path.startswith("/home/cwe/documents/"):
try:
with open(path, 'r') as f:
except FileNotFoundError as e:
file_data = f.read()
print("Error - file not found")
The constructed path string uses os.sep to add the appropriate separation character for the given operating system (e.g. '\' or '/') and the call to os.path.normpath() removes any additional slashes that may have been entered - this may occur particularly when using a Windows path. The path is checked against an expected directory (/home/cwe/documents); otherwise, an attacker could provide relative path sequences like ".." to cause normpath() to generate paths that are outside the intended directory (CWE-23). By putting the pieces of the path string together in this fashion, the script avoids a call to os.path.join() and any potential issues that might arise if an absolute path is entered. With this version of the script, if the current working directory is /home/cwe/documents, and the user inputs /etc/passwd, the resulting path will be /home/cwe/documents/etc/passwd. The user is therefore contained within the current working directory as intended.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
Pathname equivalence can be regarded as a type of canonicalization error.
Relationship
Some pathname equivalence issues are not directly related to directory traversal, rather are used to bypass security-relevant checks for whether a file/directory can be accessed by the attacker (e.g. a trailing "/" on a filename could bypass access rules that don't expect a trailing /, causing a server to provide the file when it normally would not).
Terminology Like other weaknesses, terminology is often based on the types of manipulations used, instead of the underlying weaknesses. Some people use "directory traversal" only to refer to the injection of ".." and equivalent sequences whose specific meaning is to traverse directories. Other variants like "absolute pathname" and "drive letter" have the *effect* of directory traversal, but some people may not call it such, since it doesn't involve ".." or equivalent. Research Gap Research Gap Incomplete diagnosis or reporting of vulnerabilities can make it difficult to know which variant is affected. For example, a researcher might say that "..\" is vulnerable, but not test "../" which may also be vulnerable. Any combination of directory separators ("/", "\", etc.) and numbers of "." (e.g. "....") can produce unique variants; for example, the "//../" variant is not listed (CVE-2004-0325). See this entry's children and lower-level descendants. Other
In many programming languages, the injection of a null byte (the 0 or NUL) may allow an attacker to truncate a generated filename to apply to a wider range of files. For example, the product may add ".txt" to any pathname, thus limiting the attacker to text files, but a null injection may effectively remove this restriction.
CWE-59: Improper Link Resolution Before File Access ('Link Following')
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
Relevant to the view "Architectural Concepts" (CWE-1008)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Operating Systems Class: Windows (Sometimes Prevalent) Class: Unix (Often Prevalent)
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Theoretical Link following vulnerabilities are Multi-factor Vulnerabilities (MFV). They are the combination of multiple elements: file or directory permissions, filename predictability, race conditions, and in some cases, a design limitation in which there is no mechanism for performing atomic file creation operations. Some potential factors are race conditions, permissions, and predictability.
CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before using the input in a dynamic evaluation call (e.g. "eval").
This may allow an attacker to execute arbitrary code, or at least modify what code can be executed.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Architectural Concepts" (CWE-1008)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Java (Undetermined Prevalence) JavaScript (Undetermined Prevalence) Python (Undetermined Prevalence) Perl (Undetermined Prevalence) PHP (Undetermined Prevalence) Ruby (Undetermined Prevalence) Class: Interpreted (Undetermined Prevalence) Technologies AI/ML (Undetermined Prevalence) Example 1 edit-config.pl: This CGI script is used to modify settings in a configuration file. (bad code)
Example Language: Perl
use CGI qw(:standard);
sub config_file_add_key { my ($fname, $key, $arg) = @_;
# code to add a field/key to a file goes here sub config_file_set_key { my ($fname, $key, $arg) = @_;
# code to set key to a particular file goes here sub config_file_delete_key { my ($fname, $key, $arg) = @_;
# code to delete key from a particular file goes here sub handleConfigAction { my ($fname, $action) = @_;
my $key = param('key'); my $val = param('val'); # this is super-efficient code, especially if you have to invoke # any one of dozens of different functions! my $code = "config_file_$action_key(\$fname, \$key, \$val);"; eval($code); $configfile = "/home/cwe/config.txt"; print header; if (defined(param('action'))) { handleConfigAction($configfile, param('action')); }else { print "No action specified!\n"; }The script intends to take the 'action' parameter and invoke one of a variety of functions based on the value of that parameter - config_file_add_key(), config_file_set_key(), or config_file_delete_key(). It could set up a conditional to invoke each function separately, but eval() is a powerful way of doing the same thing in fewer lines of code, especially when a large number of functions or variables are involved. Unfortunately, in this case, the attacker can provide other values in the action parameter, such as: (attack code)
add_key(",","); system("/bin/ls");
This would produce the following string in handleConfigAction(): (result)
config_file_add_key(",","); system("/bin/ls");
Any arbitrary Perl code could be added after the attacker has "closed off" the construction of the original function call, in order to prevent parsing errors from causing the malicious eval() to fail before the attacker's payload is activated. This particular manipulation would fail after the system() call, because the "_key(\$fname, \$key, \$val)" portion of the string would cause an error, but this is irrelevant to the attack because the payload has already been activated. Example 2 This simple script asks a user to supply a list of numbers as input and adds them together. (bad code)
Example Language: Python
def main():
sum = 0
main()
numbers = eval(input("Enter a space-separated list of numbers: ")) for num in numbers:
sum = sum + num
print(f"Sum of {numbers} = {sum}")
The eval() function can take the user-supplied list and convert it into a Python list object, therefore allowing the programmer to use list comprehension methods to work with the data. However, if code is supplied to the eval() function, it will execute that code. For example, a malicious user could supply the following string: (attack code)
__import__('subprocess').getoutput('rm -r *')
This would delete all the files in the current directory. For this reason, it is not recommended to use eval() with untrusted input. A way to accomplish this without the use of eval() is to apply an integer conversion on the input within a try/except block. If the user-supplied input is not numeric, this will raise a ValueError. By avoiding eval(), there is no opportunity for the input string to be executed as code. (good code)
Example Language: Python
def main():
sum = 0
main()
numbers = input("Enter a space-separated list of numbers: ").split(" ") try:
for num in numbers:
except ValueError:
sum = sum + int(num)
print(f"Sum of {numbers} = {sum}")
print("Error: invalid input")
An alternative, commonly-cited mitigation for this kind of weakness is to use the ast.literal_eval() function, since it is intentionally designed to avoid executing code. However, an adversary could still cause excessive memory or stack consumption via deeply nested structures [REF-1372], so the python documentation discourages use of ast.literal_eval() on untrusted data [REF-1373].
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Other
Factors: special character errors can play a role in increasing the variety of code that can be injected, although some vulnerabilities do not require special characters at all, e.g. when a single function without arguments can be referenced and a terminator character is not necessary.
CWE-77: Improper Neutralization of Special Elements used in a Command ('Command Injection')
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterMany protocols and products have their own custom command language. While OS or shell command strings are frequently discovered and targeted, developers may not realize that these other command languages might also be vulnerable to attacks.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
Relevant to the view "Architectural Concepts" (CWE-1008)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Technologies AI/ML (Undetermined Prevalence) Example 1 Consider a "CWE Differentiator" application that uses an an LLM generative AI based "chatbot" to explain the difference between two weaknesses. As input, it accepts two CWE IDs, constructs a prompt string, sends the prompt to the chatbot, and prints the results. The prompt string effectively acts as a command to the chatbot component. Assume that invokeChatbot() calls the chatbot and returns the response as a string; the implementation details are not important here. (bad code)
Example Language: Python
prompt = "Explain the difference between {} and {}".format(arg1, arg2)
result = invokeChatbot(prompt) resultHTML = encodeForHTML(result) print resultHTML To avoid XSS risks, the code ensures that the response from the chatbot is properly encoded for HTML output. If the user provides CWE-77 and CWE-78, then the resulting prompt would look like: However, the attacker could provide malformed CWE IDs containing malicious prompts such as: This would produce a prompt like: Instead of providing well-formed CWE IDs, the adversary has performed a "prompt injection" attack by adding an additional prompt that was not intended by the developer. The result from the maliciously modified prompt might be something like this: While the attack in this example is not serious, it shows the risk of unexpected results. Prompts can be constructed to steal private information, invoke unexpected agents, etc. In this case, it might be easiest to fix the code by validating the input CWE IDs: (good code)
Example Language: Python
cweRegex = re.compile("^CWE-\d+$")
match1 = cweRegex.search(arg1) match2 = cweRegex.search(arg2) if match1 is None or match2 is None:
# throw exception, generate error, etc.
prompt = "Explain the difference between {} and {}".format(arg1, arg2)... Example 2 Consider the following program. It intends to perform an "ls -l" on an input filename. The validate_name() subroutine performs validation on the input to make sure that only alphanumeric and "-" characters are allowed, which avoids path traversal (CWE-22) and OS command injection (CWE-78) weaknesses. Only filenames like "abc" or "d-e-f" are intended to be allowed. (bad code)
Example Language: Perl
my $arg = GetArgument("filename");
do_listing($arg); sub do_listing {
my($fname) = @_;
}
if (! validate_name($fname)) {
print "Error: name is not well-formed!\n";
}return; # build command my $cmd = "/bin/ls -l $fname"; system($cmd); sub validate_name {
my($name) = @_;
}
if ($name =~ /^[\w\-]+$/) {
return(1);
}else {
return(0);
}However, validate_name() allows filenames that begin with a "-". An adversary could supply a filename like "-aR", producing the "ls -l -aR" command (CWE-88), thereby getting a full recursive listing of the entire directory and all of its sub-directories. There are a couple possible mitigations for this weakness. One would be to refactor the code to avoid using system() altogether, instead relying on internal functions. Another option could be to add a "--" argument to the ls command, such as "ls -l --", so that any remaining arguments are treated as filenames, causing any leading "-" to be treated as part of a filename instead of another option. Another fix might be to change the regular expression used in validate_name to force the first character of the filename to be a letter or number, such as: (good code)
Example Language: Perl
if ($name =~ /^\w[\w\-]+$/) ...
Example 3 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: C
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, leading to OS command injection (CWE-78). Note that if argv[1] is a very long argument, then this issue might also be subject to a buffer overflow (CWE-120). Example 4 The following code is from an administrative web application designed to allow users to kick off a backup of an Oracle database using a batch-file wrapper around the rman utility and then run a cleanup.bat script to delete some temporary files. The script rmanDB.bat accepts a single command line parameter, which specifies what type of backup to perform. Because access to the database is restricted, the application runs the backup as a privileged user. (bad code)
Example Language: Java
...
String btype = request.getParameter("backuptype"); String cmd = new String("cmd.exe /K \" c:\\util\\rmanDB.bat "
+btype+ "&&c:\\utl\\cleanup.bat\"") System.Runtime.getRuntime().exec(cmd); ... The problem here is that the program does not do any validation on the backuptype parameter read from the user. Typically the Runtime.exec() function will not execute multiple commands, but in this case the program first runs the cmd.exe shell in order to run multiple commands with a single call to Runtime.exec(). Once the shell is invoked, it will happily execute multiple commands separated by two ampersands. If an attacker passes a string of the form "& del c:\\dbms\\*.*", then the application will execute this command along with the others specified by the program. Because of the nature of the application, it runs with the privileges necessary to interact with the database, which means whatever command the attacker injects will run with those privileges as well.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Terminology The "command injection" phrase carries different meanings, either as an attack or as a technical impact. The most common usage of "command injection" refers to the more-accurate OS command injection (CWE-78), but there are many command languages. In vulnerability-focused analysis, the phrase may refer to any situation in which the adversary can execute commands of their own choosing, i.e., the focus is on the risk and/or technical impact of exploitation. Many proof-of-concept exploits focus on the ability to execute commands and may emphasize "command injection." However, there are dozens of weaknesses that can allow execution of commands. That is, the ability to execute commands could be resultant from another weakness. To some, "command injection" can include cases in which the functionality intentionally allows the user to specify an entire command, which is then executed. In this case, the root cause weakness might be related to missing or incorrect authorization, since an adversary should not be able to specify arbitrary commands, but some users or admins are allowed. CWE-77 and its descendants are specifically focused on behaviors in which the product is intentionally building a command to execute, and the adversary can inject separators into the command or otherwise change the command being executed. Other Command injection is a common problem with wrapper programs.
CWE-129: Improper Validation of Array Index
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Often Prevalent) C++ (Often Prevalent) Class: Not Language-Specific (Undetermined Prevalence) Example 1 In the code snippet below, an untrusted integer value is used to reference an object in an array. (bad code)
Example Language: Java
public String getValue(int index) {
return array[index]; }If index is outside of the range of the array, this may result in an ArrayIndexOutOfBounds Exception being raised. Example 2 The following example takes a user-supplied value to allocate an array of objects and then operates on the array. (bad code)
Example Language: Java
private void buildList ( int untrustedListSize ){
if ( 0 > untrustedListSize ){ }die("Negative value supplied for list size, die evil hacker!"); }Widget[] list = new Widget [ untrustedListSize ]; list[0] = new Widget(); This example attempts to build a list from a user-specified value, and even checks to ensure a non-negative value is supplied. If, however, a 0 value is provided, the code will build an array of size 0 and then try to store a new Widget in the first location, causing an exception to be thrown. Example 3 In the following code, the method retrieves a value from an array at a specific array index location that is given as an input parameter to the method (bad code)
Example Language: C
int getValueFromArray(int *array, int len, int index) {
int value; // check that the array index is less than the maximum // length of the array if (index < len) {
// get the value at the specified index of the array
value = array[index]; // if array index is invalid then output error message // and return value indicating error else { printf("Value is: %d\n", array[index]); }value = -1; return value; However, this method only verifies that the given array index is less than the maximum length of the array but does not check for the minimum value (CWE-839). This will allow a negative value to be accepted as the input array index, which will result in a out of bounds read (CWE-125) and may allow access to sensitive memory. The input array index should be checked to verify that is within the maximum and minimum range required for the array (CWE-129). In this example the if statement should be modified to include a minimum range check, as shown below. (good code)
Example Language: C
... // check that the array index is within the correct // range of values for the array if (index >= 0 && index < len) { ... Example 4 The following example retrieves the sizes of messages for a pop3 mail server. The message sizes are retrieved from a socket that returns in a buffer the message number and the message size, the message number (num) and size (size) are extracted from the buffer and the message size is placed into an array using the message number for the array index. (bad code)
Example Language: C
/* capture the sizes of all messages */ int getsizes(int sock, int count, int *sizes) { ...
char buf[BUFFER_SIZE]; int ok; int num, size; // read values from socket and added to sizes array while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) {
// continue read from socket until buf only contains '.'
if (DOTLINE(buf)) break;
else if (sscanf(buf, "%d %d", &num, &size) == 2)sizes[num - 1] = size;
...
In this example the message number retrieved from the buffer could be a value that is outside the allowable range of indices for the array and could possibly be a negative number. Without proper validation of the value to be used for the array index an array overflow could occur and could potentially lead to unauthorized access to memory addresses and system crashes. The value of the array index should be validated to ensure that it is within the allowable range of indices for the array as in the following code. (good code)
Example Language: C
/* capture the sizes of all messages */ int getsizes(int sock, int count, int *sizes) { ...
char buf[BUFFER_SIZE]; int ok; int num, size; // read values from socket and added to sizes array while ((ok = gen_recv(sock, buf, sizeof(buf))) == 0) { // continue read from socket until buf only contains '.' if (DOTLINE(buf)) break;
else if (sscanf(buf, "%d %d", &num, &size) == 2) { if (num > 0 && num <= (unsigned)count)
sizes[num - 1] = size;
else /* warn about possible attempt to induce buffer overflow */ report(stderr, "Warning: ignoring bogus data for message sizes returned by server.\n"); ...
Example 5 In the following example the method displayProductSummary is called from a Web service servlet to retrieve product summary information for display to the user. The servlet obtains the integer value of the product number from the user and passes it to the displayProductSummary method. The displayProductSummary method passes the integer value of the product number to the getProductSummary method which obtains the product summary from the array object containing the project summaries using the integer value of the product number as the array index. (bad code)
Example Language: Java
// Method called from servlet to obtain product information public String displayProductSummary(int index) { String productSummary = new String("");
try { String productSummary = getProductSummary(index);
} catch (Exception ex) {...} return productSummary; public String getProductSummary(int index) { return products[index]; }In this example the integer value used as the array index that is provided by the user may be outside the allowable range of indices for the array which may provide unexpected results or cause the application to fail. The integer value used for the array index should be validated to ensure that it is within the allowable range of indices for the array as in the following code. (good code)
Example Language: Java
// Method called from servlet to obtain product information public String displayProductSummary(int index) { String productSummary = new String("");
try { String productSummary = getProductSummary(index);
} catch (Exception ex) {...} return productSummary; public String getProductSummary(int index) { String productSummary = "";
if ((index >= 0) && (index < MAX_PRODUCTS)) { productSummary = products[index]; }else { System.err.println("index is out of bounds"); }throw new IndexOutOfBoundsException(); return productSummary; An alternative in Java would be to use one of the collection objects such as ArrayList that will automatically generate an exception if an attempt is made to access an array index that is out of bounds. (good code)
Example Language: Java
ArrayList productArray = new ArrayList(MAX_PRODUCTS);
... try { productSummary = (String) productArray.get(index); } catch (IndexOutOfBoundsException ex) {...}Example 6 The following example asks a user for an offset into an array to select an item. (bad code)
Example Language: C
int main (int argc, char **argv) { char *items[] = {"boat", "car", "truck", "train"}; }int index = GetUntrustedOffset(); printf("You selected %s\n", items[index-1]); The programmer allows the user to specify which element in the list to select, however an attacker can provide an out-of-bounds offset, resulting in a buffer over-read (CWE-126).
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
This weakness can precede uncontrolled memory allocation (CWE-789) in languages that automatically expand an array when an index is used that is larger than the size of the array, such as JavaScript.
Theoretical
An improperly validated array index might lead directly to the always-incorrect behavior of "access of array using out-of-bounds index."
CWE-705: Incorrect Control Flow Scoping
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not properly return control flow to the proper location after it has completed a task or detected an unusual condition.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following example attempts to resolve a hostname. (bad code)
Example Language: Java
protected void doPost (HttpServletRequest req, HttpServletResponse res) throws IOException {
String ip = req.getRemoteAddr(); }InetAddress addr = InetAddress.getByName(ip); ... out.println("hello " + addr.getHostName()); A DNS lookup failure will cause the Servlet to throw an exception. Example 2 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,$ipAllowList)){ 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). Example 3 Included in the doPost() method defined below is a call to System.exit() in the event of a specific exception. (bad code)
Example Language: Java
Public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try { }... } catch (ApplicationSpecificException ase) {logger.error("Caught: " + ase.toString()); }System.exit(1);
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-789: Memory Allocation with Excessive Size Value
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Undetermined Prevalence) C++ (Undetermined Prevalence) Class: Not Language-Specific (Undetermined Prevalence) Example 1 Consider the following code, which accepts an untrusted size value and allocates a buffer to contain a string of the given size. (bad code)
Example Language: C
unsigned int size = GetUntrustedInt();
/* ignore integer overflow (CWE-190) for this example */ unsigned int totBytes = size * sizeof(char); char *string = (char *)malloc(totBytes); InitializeString(string); Suppose an attacker provides a size value of:
12345678
This will cause 305,419,896 bytes (over 291 megabytes) to be allocated for the string. Example 2 Consider the following code, which accepts an untrusted size value and uses the size as an initial capacity for a HashMap. (bad code)
Example Language: Java
unsigned int size = GetUntrustedInt();
HashMap list = new HashMap(size); The HashMap constructor will verify that the initial capacity is not negative, however there is no check in place to verify that sufficient memory is present. If the attacker provides a large enough value, the application will run into an OutOfMemoryError. Example 3 This code performs a stack allocation based on a length calculation. (bad code)
Example Language: C
int a = 5, b = 6;
}
size_t len = a - b; char buf[len]; // Just blows up the stack Since a and b are declared as signed ints, the "a - b" subtraction gives a negative result (-1). However, since len is declared to be unsigned, len is cast to an extremely large positive number (on 32-bit systems - 4294967295). As a result, the buffer buf[len] declaration uses an extremely large size to allocate on the stack, very likely more than the entire computer's memory space. Miscalculations usually will not be so obvious. The calculation will either be complicated or the result of an attacker's input to attain the negative value. Example 4 This example shows a typical attempt to parse a string with an error resulting from a difference in assumptions between the caller to a function and the function's action. (bad code)
Example Language: C
int proc_msg(char *s, int msg_len)
{
// Note space at the end of the string - assume all strings have preamble with space
}int pre_len = sizeof("preamble: "); char buf[pre_len - msg_len]; ... Do processing here if we get this far char *s = "preamble: message\n"; char *sl = strchr(s, ':'); // Number of characters up to ':' (not including space) int jnklen = sl == NULL ? 0 : sl - s; // If undefined pointer, use zero length int ret_val = proc_msg ("s", jnklen); // Violate assumption of preamble length, end up with negative value, blow out stack The buffer length ends up being -1, resulting in a blown out stack. The space character after the colon is included in the function calculation, but not in the caller's calculation. This, unfortunately, is not usually so obvious but exists in an obtuse series of calculations. Example 5 The following code obtains an untrusted number that is used as an index into an array of messages. (bad code)
Example Language: Perl
my $num = GetUntrustedNumber();
my @messages = (); $messages[$num] = "Hello World"; The index is not validated at all (CWE-129), so it might be possible for an attacker to modify an element in @messages that was not intended. If an index is used that is larger than the current size of the array, the Perl interpreter automatically expands the array so that the large index works. If $num is a large value such as 2147483648 (1<<31), then the assignment to $messages[$num] would attempt to create a very large array, then eventually produce an error message such as: Out of memory during array extend This memory exhaustion will cause the Perl program to exit, possibly a denial of service. In addition, the lack of memory could also prevent many other programs from successfully running on the system. Example 6 This example shows a typical attempt to parse a string with an error resulting from a difference in assumptions between the caller to a function and the function's action. The buffer length ends up being -1 resulting in a blown out stack. The space character after the colon is included in the function calculation, but not in the caller's calculation. This, unfortunately, is not usually so obvious but exists in an obtuse series of calculations. (bad code)
Example Language: C
int proc_msg(char *s, int msg_len)
{ int pre_len = sizeof("preamble: "); // Note space at the end of the string - assume all strings have preamble with space
char buf[pre_len - msg_len];
... Do processing here and set status
return status;
}
char *s = "preamble: message\n"; char *sl = strchr(s, ':'); // Number of characters up to ':' (not including space) int jnklen = sl == NULL ? 0 : sl - s; // If undefined pointer, use zero length int ret_val = proc_msg ("s", jnklen); // Violate assumption of preamble length, end up with negative value, blow out stack (good code)
Example Language: C
int proc_msg(char *s, int msg_len)
{ int pre_len = sizeof("preamble: "); // Note space at the end of the string - assume all strings have preamble with space
if (pre_len <= msg_len) { // Log error; return error_code; }
char buf[pre_len - msg_len];
... Do processing here and set status
return status;
}
char *s = "preamble: message\n"; char *sl = strchr(s, ':'); // Number of characters up to ':' (not including space) int jnklen = sl == NULL ? 0 : sl - s; // If undefined pointer, use zero length int ret_val = proc_msg ("s", jnklen); // Violate assumption of preamble length, end up with negative value, blow out stack
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
This weakness can be closely associated with integer overflows (CWE-190). Integer overflow attacks would concentrate on providing an extremely large number that triggers an overflow that causes less memory to be allocated than expected. By providing a large value that does not trigger an integer overflow, the attacker could still cause excessive amounts of memory to be allocated.
Applicable Platform Uncontrolled memory allocation is possible in many languages, such as dynamic array allocation in perl or initial size parameters in Collections in Java. However, languages like C and C++ where programmers have the power to more directly control memory management will be more susceptible.
CWE-456: Missing Initialization of a Variable
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not initialize critical variables, which causes the execution environment to use unexpected values.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 This function attempts to extract a pair of numbers from a user-supplied string. (bad code)
Example Language: C
void parse_data(char *untrusted_input){
int m, n, error;
error = sscanf(untrusted_input, "%d:%d", &m, &n); if ( EOF == error ){ die("Did not specify integer value. Die evil hacker!\n"); }/* proceed assuming n and m are initialized correctly */ This code attempts to extract two integer values out of a formatted, user-supplied input. However, if an attacker were to provide an input of the form: (attack code)
123:
then only the m variable will be initialized. Subsequent use of n may result in the use of an uninitialized variable (CWE-457). Example 2 Here, an uninitialized field in a Java class is used in a seldom-called method, which would cause a NullPointerException to be thrown. (bad code)
Example Language: Java
private User user;
public void someMethod() { // Do something interesting. ... // Throws NPE if user hasn't been properly initialized. String username = user.getName(); Example 3 This code first authenticates a user, then allows a delete command if the user is an administrator. (bad code)
Example Language: PHP
if (authenticate($username,$password) && setAdmin($username)){
$isAdmin = true; }/.../ if ($isAdmin){ deleteUser($userToDelete); }The $isAdmin variable is set to true if the user is an admin, but is uninitialized otherwise. If PHP's register_globals feature is enabled, an attacker can set uninitialized variables like $isAdmin to arbitrary values, in this case gaining administrator privileges by setting $isAdmin to true. Example 4 In the following Java code the BankManager class uses the user variable of the class User to allow authorized users to perform bank manager tasks. The user variable is initialized within the method setUser that retrieves the User from the User database. The user is then authenticated as unauthorized user through the method authenticateUser. (bad code)
Example Language: Java
public class BankManager {
// user allowed to perform bank manager tasks private User user = null; private boolean isUserAuthentic = false; // constructor for BankManager class public BankManager() { ... }// retrieve user from database of users public User getUserFromUserDatabase(String username){ ... }// set user variable using username public void setUser(String username) { this.user = getUserFromUserDatabase(username); }// authenticate user public boolean authenticateUser(String username, String password) { if (username.equals(user.getUsername()) && password.equals(user.getPassword())) { }isUserAuthentic = true; }return isUserAuthentic; // methods for performing bank manager tasks ... However, if the method setUser is not called before authenticateUser then the user variable will not have been initialized and will result in a NullPointerException. The code should verify that the user variable has been initialized before it is used, as in the following code. (good code)
Example Language: Java
public class BankManager {
// user allowed to perform bank manager tasks private User user = null; private boolean isUserAuthentic = false; // constructor for BankManager class public BankManager(String username) { user = getUserFromUserDatabase(username); }// retrieve user from database of users public User getUserFromUserDatabase(String username) {...} // authenticate user public boolean authenticateUser(String username, String password) { if (user == null) {
System.out.println("Cannot find user " + username); }else { if (password.equals(user.getPassword())) { }isUserAuthentic = true; }return isUserAuthentic; // methods for performing bank manager tasks ... Example 5 This example will leave test_string in an unknown condition when i is the same value as err_val, because test_string is not initialized (CWE-456). Depending on where this code segment appears (e.g. within a function body), test_string might be random if it is stored on the heap or stack. If the variable is declared in static memory, it might be zero or NULL. Compiler optimization might contribute to the unpredictability of this address. (bad code)
Example Language: C
char *test_string;
if (i != err_val) { test_string = "Hello World!";
}printf("%s", test_string); When the printf() is reached, test_string might be an unexpected address, so the printf might print junk strings (CWE-457). To fix this code, there are a couple approaches to making sure that test_string has been properly set once it reaches the printf(). One solution would be to set test_string to an acceptable default before the conditional: (good code)
Example Language: C
char *test_string = "Done at the beginning";
if (i != err_val) { test_string = "Hello World!";
}printf("%s", test_string); Another solution is to ensure that each branch of the conditional - including the default/else branch - could ensure that test_string is set: (good code)
Example Language: C
char *test_string;
if (i != err_val) { test_string = "Hello World!";
}else { test_string = "Done on the other side!";
}printf("%s", test_string);
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
This weakness is a major factor in a number of resultant weaknesses, especially in web applications that allow global variable initialization (such as PHP) with libraries that can be directly requested.
Research Gap
It is highly likely that a large number of resultant weaknesses have missing initialization as a primary factor, but researcher reports generally do not provide this level of detail.
CWE CATEGORY: Numeric Errors
CWE-783: Operator Precedence Logic Error
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product uses an expression in which operator precedence causes incorrect logic to be used.
While often just a bug, operator precedence logic errors can have serious consequences if they are used in security-critical code, such as making an authentication decision.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Rarely Prevalent) C++ (Rarely Prevalent) Class: Not Language-Specific (Rarely Prevalent) Example 1 In the following example, the method validateUser makes a call to another method to authenticate a username and password for a user and returns a success or failure code. (bad code)
Example Language: C
#define FAIL 0
#define SUCCESS 1 ... int validateUser(char *username, char *password) { int isUser = FAIL; // call method to authenticate username and password // if authentication fails then return failure otherwise return success if (isUser = AuthenticateUser(username, password) == FAIL) { return isUser; }else { isUser = SUCCESS; }return isUser; However, the method that authenticates the username and password is called within an if statement with incorrect operator precedence logic. Because the comparison operator "==" has a higher precedence than the assignment operator "=", the comparison operator will be evaluated first and if the method returns FAIL then the comparison will be true, the return variable will be set to true and SUCCESS will be returned. This operator precedence logic error can be easily resolved by properly using parentheses within the expression of the if statement, as shown below. (good code)
Example Language: C
...
if ((isUser = AuthenticateUser(username, password)) == FAIL) { ... Example 2 In this example, the method calculates the return on investment for an accounting/financial application. The return on investment is calculated by subtracting the initial investment costs from the current value and then dividing by the initial investment costs. (bad code)
Example Language: Java
public double calculateReturnOnInvestment(double currentValue, double initialInvestment) {
double returnROI = 0.0; // calculate return on investment returnROI = currentValue - initialInvestment / initialInvestment; return returnROI; However, the return on investment calculation will not produce correct results because of the incorrect operator precedence logic in the equation. The divide operator has a higher precedence than the minus operator, therefore the equation will divide the initial investment costs by the initial investment costs which will only subtract one from the current value. Again this operator precedence logic error can be resolved by the correct use of parentheses within the equation, as shown below. (good code)
Example Language: Java
...
returnROI = (currentValue - initialInvestment) / initialInvestment; ... Note that the initialInvestment variable in this example should be validated to ensure that it is greater than zero to avoid a potential divide by zero error (CWE-369).
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-375: Returning a Mutable Object to an Untrusted Caller
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterSending non-cloned mutable data as a return value may result in that data being altered or deleted by the calling function.
In situations where functions return references to mutable data, it is possible that the external code which called the function may make changes to the data sent. If this data was not previously cloned, the class will then be using modified data which may violate assumptions about its internal state.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Undetermined Prevalence) C++ (Undetermined Prevalence) Java (Undetermined Prevalence) C# (Undetermined Prevalence) Example 1 This class has a private list of patients, but provides a way to see the list : (bad code)
Example Language: Java
public class ClinicalTrial {
private PatientClass[] patientList = new PatientClass[50]; }public getPatients(...){ return patientList; }While this code only means to allow reading of the patient list, the getPatients() method returns a reference to the class's original patient list instead of a reference to a copy of the list. Any caller of this method can arbitrarily modify the contents of the patient list even though it is a private member of the class.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS)
Weaknesses in this category are related to the rules and recommendations in the Input Validation and Data Sanitization (IDS) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 02. Declarations and Initialization (DCL)
Weaknesses in this category are related to the rules and recommendations in the Declarations and Initialization (DCL) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 03. Expressions (EXP)
Weaknesses in this category are related to the rules and recommendations in the Expressions (EXP) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 04. Integers (INT)
Weaknesses in this category are related to the rules and recommendations in the Integers (INT) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 05. Strings (STR)
Weaknesses in this category are related to the rules and recommendations in the Strings (STR) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 06. Object-Oriented Programming (OOP)
Weaknesses in this category are related to the rules and recommendations in the Object-Oriented Programming (OOP) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 07. File Input and Output (FIO)
Weaknesses in this category are related to the rules and recommendations in the File Input and Output (FIO) section of the SEI CERT Perl Coding Standard.
CWE CATEGORY: SEI CERT Perl Coding Standard - Guidelines 50. Miscellaneous (MSC)
Weaknesses in this category are related to the rules and recommendations in the Miscellaneous (MSC) section of the SEI CERT Perl Coding Standard.
CWE-248: Uncaught Exception
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom Filter
When an exception is not caught, it may cause the program to crash or expose sensitive information.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C++ (Undetermined Prevalence) Java (Undetermined Prevalence) C# (Undetermined Prevalence) Example 1 The following example attempts to resolve a hostname. (bad code)
Example Language: Java
protected void doPost (HttpServletRequest req, HttpServletResponse res) throws IOException {
String ip = req.getRemoteAddr(); }InetAddress addr = InetAddress.getByName(ip); ... out.println("hello " + addr.getHostName()); A DNS lookup failure will cause the Servlet to throw an exception. Example 2 The _alloca() function allocates memory on the stack. If an allocation request is too large for the available stack space, _alloca() throws an exception. If the exception is not caught, the program will crash, potentially enabling a denial of service attack. _alloca() has been deprecated as of Microsoft Visual Studio 2005(R). It has been replaced with the more secure _alloca_s(). Example 3 EnterCriticalSection() can raise an exception, potentially causing the program to crash. Under operating systems prior to Windows 2000, the EnterCriticalSection() function can raise an exception in low memory situations. If the exception is not caught, the program will crash, potentially enabling a denial of service attack.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-391: Unchecked Error Condition
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThis table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "Architectural Concepts" (CWE-1008)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following code excerpt ignores a rarely-thrown exception from doExchange(). (bad code)
Example Language: Java
try {
doExchange(); }catch (RareException e) { // this can never happen If a RareException were to ever be thrown, the program would continue to execute as though nothing unusual had occurred. The program records no evidence indicating the special situation, potentially frustrating any later attempt to explain the program's behavior.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Other When a programmer ignores an exception, they implicitly state that they are operating under one of two assumptions:
Maintenance
This entry is slated for deprecation; it has multiple widespread interpretations by CWE analysts. It currently combines information from three different taxonomies, but each taxonomy is talking about a slightly different issue. CWE analysts might map to this entry based on any of these issues. 7PK has "Empty Catch Block" which has an association with empty exception block (CWE-1069); in this case, the exception has performed the check, but does not handle. In PLOVER there is "Unchecked Return Value" which is CWE-252, but unlike "Empty Catch Block" there isn't even a check of the issue - and "Unchecked Error Condition" implies lack of a check. For CLASP, "Uncaught Exception" (CWE-248) is associated with incorrect error propagation - uncovered in CWE 3.2 and earlier, at least. There are other issues related to error handling and checks.
CWE-252: Unchecked Return Value
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.
Two common programmer assumptions are "this function call can never fail" and "it doesn't matter if this function call fails". If an attacker can force the function to fail or otherwise return a value that is not expected, then the subsequent program logic could lead to a vulnerability, because the product is not in a state that the programmer assumes. For example, if the program calls a function to drop privileges but does not check the return code to ensure that privileges were successfully dropped, then the program will continue to operate with the higher privileges.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 Consider the following code segment: (bad code)
Example Language: C
char buf[10], cp_buf[10];
fgets(buf, 10, stdin); strcpy(cp_buf, buf); The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy(). 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: C
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 The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc(). (bad code)
Example Language: C
buf = (char*) malloc(req_size);
strncpy(buf, xfer, req_size); The traditional defense of this coding error is: "If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or allow the program to die with a segmentation fault when it tries to dereference the null pointer." This argument ignores three important considerations:
Example 4 The following examples read a file into a byte array. (bad code)
Example Language: C#
char[] byteArray = new char[1024];
for (IEnumerator i=users.GetEnumerator(); i.MoveNext() ;i.Current()) { String userName = (String) i.Current(); }String pFileName = PFILE_ROOT + "/" + userName; StreamReader sr = new StreamReader(pFileName); sr.Read(byteArray,0,1024);//the file is always 1k bytes sr.Close(); processPFile(userName, byteArray); (bad code)
Example Language: Java
FileInputStream fis;
byte[] byteArray = new byte[1024]; for (Iterator i=users.iterator(); i.hasNext();) { String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName; FileInputStream fis = new FileInputStream(pFileName); fis.read(byteArray); // the file is always 1k bytes fis.close(); processPFile(userName, byteArray); The code loops through a set of users, reading a private data file for each user. The programmer assumes that the files are always 1 kilobyte in size and therefore ignores the return value from Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data from the previous user and treat it as though it belongs to the attacker. Example 5 The following code does not check to see if the string returned by getParameter() is null before calling the member function compareTo(), potentially causing a NULL dereference. (bad code)
Example Language: Java
String itemName = request.getParameter(ITEM_NAME);
if (itemName.compareTo(IMPORTANT_ITEM) == 0) { ... }... The following code does not check to see if the string returned by the Item property is null before calling the member function Equals(), potentially causing a NULL dereference. (bad code)
Example Language: Java
String itemName = request.Item(ITEM_NAME);
if (itemName.Equals(IMPORTANT_ITEM)) { ... }... The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved. Example 6 The following code shows a system property that is set to null and later dereferenced by a programmer who mistakenly assumes it will always be defined. (bad code)
Example Language: Java
System.clearProperty("os.name");
... String os = System.getProperty("os.name"); if (os.equalsIgnoreCase("Windows 95")) System.out.println("Not supported"); The traditional defense of this coding error is: "I know the requested value will always exist because.... If it does not exist, the program cannot perform the desired behavior so it doesn't matter whether I handle the error or allow the program to die dereferencing a null value." But attackers are skilled at finding unexpected paths through programs, particularly when exceptions are involved. Example 7 The following VB.NET code does not check to make sure that it has read 50 bytes from myfile.txt. This can cause DoDangerousOperation() to operate on an unexpected value. (bad code)
Example Language: C#
Dim MyFile As New FileStream("myfile.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
Dim MyArray(50) As Byte MyFile.Read(MyArray, 0, 50) DoDangerousOperation(MyArray(20)) In .NET, it is not uncommon for programmers to misunderstand Read() and related methods that are part of many System.IO classes. The stream and reader classes do not consider it to be unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested. Example 8 It is not uncommon for Java programmers to misunderstand read() and related methods that are part of many java.io classes. Most errors and unusual events in Java result in an exception being thrown. But the stream and reader classes do not consider it unusual or exceptional if only a small amount of data becomes available. These classes simply add the small amount of data to the return buffer, and set the return value to the number of bytes or characters read. There is no guarantee that the amount of data returned is equal to the amount of data requested. This behavior makes it important for programmers to examine the return value from read() and other IO methods to ensure that they receive the amount of data they expect. Example 9 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: C
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr; char hostname[64]; in_addr_t inet_addr(const char *cp); /*routine that ensures user_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); If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119). Example 10 The following function attempts to acquire a lock in order to perform operations on a shared resource. (bad code)
Example Language: C
void f(pthread_mutex_t *mutex) {
pthread_mutex_lock(mutex);
/* access shared resource */ pthread_mutex_unlock(mutex); However, the code does not check the value returned by pthread_mutex_lock() for errors. If pthread_mutex_lock() cannot acquire the mutex for any reason, the function may introduce a race condition into the program and result in undefined behavior. In order to avoid data races, correctly written programs must check the result of thread synchronization functions and appropriately handle all errors, either by attempting to recover from them or reporting them to higher levels. (good code)
Example Language: C
int f(pthread_mutex_t *mutex) {
int result;
result = pthread_mutex_lock(mutex); if (0 != result) return result;
/* access shared resource */ return pthread_mutex_unlock(mutex);
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-690: Unchecked Return Value to NULL Pointer Dereference
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not check for an error after calling a function that can return with a NULL pointer if the function fails, which leads to a resultant NULL pointer dereference.
While unchecked return value weaknesses are not limited to returns of NULL pointers (see the examples in CWE-252), functions often return NULL to indicate an error status. When this error condition is not checked, a NULL pointer dereference can occur.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Undetermined Prevalence) C++ (Undetermined Prevalence) Example 1 The code below makes a call to the getUserName() function but doesn't check the return value before dereferencing (which may cause a NullPointerException). (bad code)
Example Language: Java
String username = getUserName();
if (username.equals(ADMIN_USER)) { ... }Example 2 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: C
void host_lookup(char *user_supplied_addr){
struct hostent *hp;
in_addr_t *addr; char hostname[64]; in_addr_t inet_addr(const char *cp); /*routine that ensures user_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); If an attacker provides an address that appears to be well-formed, but the address does not resolve to a hostname, then the call to gethostbyaddr() will return NULL. Since the code does not check the return value from gethostbyaddr (CWE-252), a NULL pointer dereference (CWE-476) would then occur in the call to strcpy(). Note that this code is also vulnerable to a buffer overflow (CWE-119).
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-394: Unexpected Status Code or Return Value
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product does not properly check when a function or operation returns a value that is legitimate for the function, but is not expected by the product.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence)
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Relationship
Usually primary, but can be resultant from issues such as behavioral change or API abuse. This can produce resultant vulnerabilities.
CWE-134: Use of Externally-Controlled Format String
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product uses a function that accepts a format string as an argument, but the format string originates from an external source.
When an attacker can modify an externally-controlled format string, this can lead to buffer overflows, denial of service, or data representation problems. It should be noted that in some circumstances, such as internationalization, the set of format strings is externally controlled by design. If the source of these format strings is trusted (e.g. only contained in library files that are only modifiable by the system administrator), then the external control might not itself pose a vulnerability. This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (CWE-1003)
Relevant to the view "Seven Pernicious Kingdoms" (CWE-700)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Often Prevalent) C++ (Often Prevalent) Perl (Rarely Prevalent) Example 1 The following program prints a string provided as an argument. (bad code)
Example Language: C
#include <stdio.h>
void printWrapper(char *string) { printf(string); int main(int argc, char **argv) { char buf[5012]; memcpy(buf, argv[1], 5012); printWrapper(argv[1]); return (0); The example is exploitable, because of the call to printf() in the printWrapper() function. Note: The stack buffer was added to make exploitation more simple. Example 2 The following code copies a command line argument into a buffer using snprintf(). (bad code)
Example Language: C
int main(int argc, char **argv){
char buf[128]; }... snprintf(buf,128,argv[1]); This code allows an attacker to view the contents of the stack and write to the stack using a command line argument containing a sequence of formatting directives. The attacker can read from the stack by providing more formatting directives, such as %x, than the function takes as arguments to be formatted. (In this example, the function takes no arguments to be formatted.) By using the %n formatting directive, the attacker can write to the stack, causing snprintf() to write the number of bytes output thus far to the specified argument (rather than reading a value from the argument, which is the intended behavior). A sophisticated version of this attack will use four staggered writes to completely control the value of a pointer on the stack. Example 3 Certain implementations make more advanced attacks even easier by providing format directives that control the location in memory to read from or write to. An example of these directives is shown in the following code, written for glibc: (bad code)
Example Language: C
printf("%d %d %1$d %1$d\n", 5, 9);
This code produces the following output: 5 9 5 5 It is also possible to use half-writes (%hn) to accurately control arbitrary DWORDS in memory, which greatly reduces the complexity needed to execute an attack that would otherwise require four staggered writes, such as the one mentioned in the first example.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
Applicable Platform This weakness is possible in any programming language that support format strings. Research Gap
Format string issues are under-studied for languages other than C. Memory or disk consumption, control flow or variable alteration, and data corruption may result from format string exploitation in applications written in other languages such as Perl, PHP, Python, etc.
Other While Format String vulnerabilities typically fall under the Buffer Overflow category, technically they are not overflowed buffers. The Format String vulnerability is fairly new (circa 1999) and stems from the fact that there is no realistic way for a function that takes a variable number of arguments to determine just how many arguments were passed in. The most common functions that take a variable number of arguments, including C-runtime functions, are the printf() family of calls. The Format String problem appears in a number of ways. A *printf() call without a format specifier is dangerous and can be exploited. For example, printf(input); is exploitable, while printf(y, input); is not exploitable in that context. The result of the first call, used incorrectly, allows for an attacker to be able to peek at stack memory since the input string will be used as the format specifier. The attacker can stuff the input string with format specifiers and begin reading stack values, since the remaining parameters will be pulled from the stack. Worst case, this improper use may give away enough control to allow an arbitrary value (or values in the case of an exploit program) to be written into the memory of the running program. Frequently targeted entities are file names, process names, identifiers. Format string problems are a classic C/C++ issue that are now rare due to the ease of discovery. One main reason format string vulnerabilities can be exploited is due to the %n operator. The %n operator will write the number of characters, which have been printed by the format string therefore far, to the memory pointed to by its argument. Through skilled creation of a format string, a malicious user may use values on the stack to create a write-what-where condition. Once this is achieved, they can execute arbitrary code. Other operators can be used as well; for example, a %9999s operator could also trigger a buffer overflow, or when used in file-formatting functions like fprintf, it can generate a much larger output than intended.
CWE-477: Use of Obsolete Function
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe code uses deprecated or obsolete functions, which suggests that the code has not been actively reviewed or maintained.
As programming languages evolve, functions occasionally become obsolete due to:
Functions that are removed are usually replaced by newer counterparts that perform the same task in some different and hopefully improved way. This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "Software Development" (CWE-699)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following code uses the deprecated function getpw() to verify that a plaintext password matches a user's encrypted password. If the password is valid, the function sets result to 1; otherwise it is set to 0. (bad code)
Example Language: C
...
getpw(uid, pwdline); for (i=0; i<3; i++){ cryptpw=strtok(pwdline, ":"); }pwdline=0; result = strcmp(crypt(plainpw,cryptpw), cryptpw) == 0; ... Although the code often behaves correctly, using the getpw() function can be problematic from a security standpoint, because it can overflow the buffer passed to its second parameter. Because of this vulnerability, getpw() has been supplanted by getpwuid(), which performs the same lookup as getpw() but returns a pointer to a statically-allocated structure to mitigate the risk. Not all functions are deprecated or replaced because they pose a security risk. However, the presence of an obsolete function often indicates that the surrounding code has been neglected and may be in a state of disrepair. Software security has not been a priority, or even a consideration, for very long. If the program uses deprecated or obsolete functions, it raises the probability that there are security problems lurking nearby. Example 2 In the following code, the programmer assumes that the system always has a property named "cmd" defined. If an attacker can control the program's environment so that "cmd" is not defined, the program throws a null pointer exception when it attempts to call the "Trim()" method. (bad code)
Example Language: Java
String cmd = null;
... cmd = Environment.GetEnvironmentVariable("cmd"); cmd = cmd.Trim(); Example 3 The following code constructs a string object from an array of bytes and a value that specifies the top 8 bits of each 16-bit Unicode character. (bad code)
Example Language: Java
...
String name = new String(nameBytes, highByte); ... In this example, the constructor may not correctly convert bytes to characters depending upon which charset is used to encode the string represented by nameBytes. Due to the evolution of the charsets used to encode strings, this constructor was deprecated and replaced by a constructor that accepts as one of its parameters the name of the charset used to encode the bytes for conversion.
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-457: Use of Uninitialized Variable
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe code uses a variable that has not been initialized, leading to unpredictable or unintended results.
In some languages such as C and C++, stack variables are not initialized by default. They generally contain junk data with the contents of stack memory before the function was invoked. An attacker can sometimes control or read these contents. In other languages or conditions, a variable that is not explicitly initialized can be given a default value that has security implications, depending on the logic of the program. The presence of an uninitialized variable can sometimes indicate a typographic error in the code.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Languages C (Sometimes Prevalent) C++ (Sometimes Prevalent) Perl (Often Prevalent) PHP (Often Prevalent) Class: Not Language-Specific (Undetermined Prevalence) Example 1 This code prints a greeting using information stored in a POST request: (bad code)
Example Language: PHP
if (isset($_POST['names'])) {
$nameArray = $_POST['names']; }echo "Hello " . $nameArray['first']; This code checks if the POST array 'names' is set before assigning it to the $nameArray variable. However, if the array is not in the POST request, $nameArray will remain uninitialized. This will cause an error when the array is accessed to print the greeting message, which could lead to further exploit. Example 2 The following switch statement is intended to set the values of the variables aN and bN before they are used: (bad code)
Example Language: C
int aN, Bn;
switch (ctl) { case -1:
aN = 0;
bN = 0; break; case 0: aN = i;
bN = -i; break; case 1: aN = i + NEXT_SZ;
bN = i - NEXT_SZ; break; default: aN = -1;
aN = -1; break; repaint(aN, bN); In the default case of the switch statement, the programmer has accidentally set the value of aN twice. As a result, bN will have an undefined value. Most uninitialized variable issues result in general software reliability problems, but if attackers can intentionally trigger the use of an uninitialized variable, they might be able to launch a denial of service attack by crashing the program. Under the right circumstances, an attacker may be able to control the value of an uninitialized variable by affecting the values on the stack prior to the invocation of the function. Example 3 This example will leave test_string in an unknown condition when i is the same value as err_val, because test_string is not initialized (CWE-456). Depending on where this code segment appears (e.g. within a function body), test_string might be random if it is stored on the heap or stack. If the variable is declared in static memory, it might be zero or NULL. Compiler optimization might contribute to the unpredictability of this address. (bad code)
Example Language: C
char *test_string;
if (i != err_val) { test_string = "Hello World!";
}printf("%s", test_string); When the printf() is reached, test_string might be an unexpected address, so the printf might print junk strings (CWE-457). To fix this code, there are a couple approaches to making sure that test_string has been properly set once it reaches the printf(). One solution would be to set test_string to an acceptable default before the conditional: (good code)
Example Language: C
char *test_string = "Done at the beginning";
if (i != err_val) { test_string = "Hello World!";
}printf("%s", test_string); Another solution is to ensure that each branch of the conditional - including the default/else branch - could ensure that test_string is set: (good code)
Example Language: C
char *test_string;
if (i != err_val) { test_string = "Hello World!";
}else { test_string = "Done on the other side!";
}printf("%s", test_string);
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
CWE-597: Use of Wrong Operator in String Comparison
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterThe product uses the wrong operator when comparing a string, such as using "==" when the .equals() method should be used instead.
In Java, using == or != to compare two strings for equality actually compares two objects for equality rather than their string values for equality. Chances are good that the two references will never be equal. While this weakness often only affects program correctness, if the equality is used for a security decision, the unintended comparison result could be leveraged to affect program security.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (CWE-1000)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
Example 1 In the example below, two Java String objects are declared and initialized with the same string values. 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 example below, three JavaScript variables are declared and initialized with the same values. Note that JavaScript will change a value between numeric and string as needed, which is the reason an integer is included with the strings. An if statement is used to determine whether the values are the same. (bad code)
Example Language: JavaScript
<p id="ieq3s1" type="text">(i === s1) is FALSE</p>
<p id="s4eq3i" type="text">(s4 === i) is FALSE</p> <p id="s4eq3s1" type="text">(s4 === s1) is FALSE</p> var i = 65; var s1 = '65'; var s4 = new String('65'); if (i === s1) { document.getElementById("ieq3s1").innerHTML = "(i === s1) is TRUE";
}if (s4 === i) { document.getElementById("s4eq3i").innerHTML = "(s4 === i) is TRUE";
}if (s4 === s1) { document.getElementById("s4eq3s1").innerHTML = "(s4 === s1) is TRUE";
}However, the body of the if statement will not be executed, as the "===" compares both the type of the variable AND the value. As the types of the first comparison are number and string, it fails. The types in the second are int and reference, so this one fails as well. The types in the third are reference and string, so it also fails. While the variables above contain the same values, they are contained in different types, so the document.getElementById... statement will not be executed in any of the cases. To compare object values, the previous code is modified and shown below to use the "==" for value comparison so the comparison in this example executes the HTML statement: (good code)
Example Language: JavaScript
<p id="ieq2s1" type="text">(i == s1) is FALSE</p>
<p id="s4eq2i" type="text">(s4 == i) is FALSE</p> <p id="s4eq2s1" type="text">(s4 == s1) is FALSE</p> var i = 65; var s1 = '65'; var s4 = new String('65'); if (i == s1) { document.getElementById("ieq2s1").innerHTML = "(i == s1) is TRUE";
}if (s4 == i) { document.getElementById("s4eq2i").innerHTML = "(s4 == i) is TRUE";
}if (s4 == s1) { document.getElementById("s4eq2s1").innerHTML = "(s4 == s1) is TRUE";
}Example 3 In the example below, two PHP variables are declared and initialized with the same numbers - one as a string, the other as an integer. Note that PHP will change the string value to a number for a comparison. An if statement is used to determine whether the values are the same. (bad code)
Example Language: PHP
var $i = 65;
var $s1 = "65"; if ($i === $s1) { echo '($i === $s1) is TRUE'. "\n";
}else { echo '($i === $s1) is FALSE'. "\n";
}However, the body of the if statement will not be executed, as the "===" compares both the type of the variable AND the value. As the types of the first comparison are number and string, it fails. While the variables above contain the same values, they are contained in different types, so the TRUE portion of the if statement will not be executed. To compare object values, the previous code is modified and shown below to use the "==" for value comparison (string converted to number) so the comparison in this example executes the TRUE statement: (good code)
Example Language: PHP
var $i = 65;
var $s1 = "65"; if ($i == $s1) { echo '($i == $s1) is TRUE'. "\n";
}else { echo '($i == $s1) is FALSE'. "\n";
}
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
More information is available — Please edit the custom filter or select a different filter. |
Use of the Common Weakness Enumeration (CWE™) and the associated references from this website are subject to the Terms of Use. CWE is sponsored by the U.S. Department of Homeland Security (DHS) Cybersecurity and Infrastructure Security Agency (CISA) and managed by the Homeland Security Systems Engineering and Development Institute (HSSEDI) which is operated by The MITRE Corporation (MITRE). Copyright © 2006–2024, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation. |