Status: Draft View ID: 629 (View: Graph)
Developers This view outlines the most important issues as identified by the OWASP Top Ten (2007 version), providing a good starting point for web application developers who want to code more securely. Software Customers This view outlines the most important issues as identified by the OWASP Top Ten (2007 version), providing customers with a way of asking their software developers to follow minimum expectations for secure code. Educators Since the OWASP Top Ten covers the most frequently encountered issues, this view can be used by educators as training material for students.
The relationships in this view are a direct extraction of the CWE mappings that are in the 2007 OWASP document. CWE has changed since the release of that document. "Top 10 2007". OWASP. 2007-05-18. <http:/ View Components View Components A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z
Status: Incomplete Weakness ID: 639 (Weakness Base)Summary The system's access control functionality does not prevent one user from gaining access to another user's records by modifying the key value identifying the record. Extended Description Retrieval of a user record occurs in the system based on some key value that is under user control. The key would typically identify a user related record stored in the system and would be used to lookup that record for presentation to the user. It is likely that an attacker would have to be an authenticated user in the system. However, the authorization process would not properly check the data access operation to ensure that the authenticated user performing the operation has sufficient entitlements to perform the requested data access, hence bypassing any other authorization checks present in the system. One manifestation of this weakness would be if a system used sequential or otherwise easily guessable session ids that would allow one user to easily switch to another user's session and view/modify their data. Access control checks for specific user data or functionality can be bypassed. Horizontal escalation of privilege is possible (one user can view/modify information of another user) Vertical escalation of privilege is possible if the user controlled key is actually an admin flag allowing to gain administrative access The key used internally in the system to identify the user record can be externally controlled. For example attackers can look at places where user specific data is retrieved (e.g. search screens) and determine whether the key for the item being looked up is controllable externally. The key may be a hidden field in the HTML form field, might be passed as a URL parameter or as an unencrypted cookie variable, then in each of these cases it will be possible to tamper with the key value. Make sure that the key that is used in the lookup of a specific user's record is not controllable externally by the user or that any tampering can be detected. Use encryption in order to make it more difficult to guess other legitimate values of the key or associate a digital signature with the key so that the server can verify that there has been no tampering.. Ensure that access control mechanisms cannot be bypassed by ensuring that the user has sufficient privilege to access the record that is being requested given his authenticated identity on each and every data access.
Submissions Evgeny Lebanidze. Cigital. 2008-01-30. (External Submission) Modifications CWE Content Team. MITRE. 2008-09-08. (Internal) updated Common_Consequences, Relationships,
Type CWE Content Team. MITRE. 2008-10-14. (Internal) updated Description CWE Content Team. MITRE. 2009-03-10. (Internal) updated Relationships CWE Content Team. MITRE. 2009-05-27. (Internal) updated Relationships Status: Incomplete Weakness ID: 288 (Weakness Base)Summary A product requires authentication, but the product has an alternate path or channel that does not require authentication. This is often seen in web applications that assume that access to a particular CGI program can only be obtained through a "front" screen, when the supporting programs are directly accessible. But this problem is not just in web apps.
Funnel all access through a single choke point to simplify how users can access a resource. For every access, perform a check to determine if the user has permissions to access the resource.
Submissions PLOVER. (Externally Mined) Modifications CWE Content Team. MITRE. 2008-09-08. (Internal) updated Description, Modes_of_Introduction, Name,
Relationships, Observed_Example, Relationship_Notes, Taxonomy_Mappings,
Type CWE Content Team. MITRE. 2008-11-24. (Internal) updated Observed_Examples Previous Entry Names Authentication Bypass by
Alternate Path/Channel (changed
2008-09-09)Status: Draft Compound Element ID: 352 (Compound Element Variant: Composite)Summary The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. Extended Description When a web server is designed to receive a request from a client without any mechanism for verifying that it was intentionally sent, then it might be possible for an attacker to trick a client into making an unintentional request to the web server which will be treated as an authentic request. This can be done via a URL, image load, XMLHttpRequest, etc. and can result in data disclosure or unintended code execution. 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. HTML Example: <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. // 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: HTML Example: <SCRIPT> function SendAttack () { form.email = "attacker@example.com"; // send to profile.php form.submit(); } </SCRIPT> <BODY
onload="javascript:SendAttack();"> <form action="http://victim.example.com/profile.php"
id="form" method="post"> <input type="hidden" name="firstname"
value="Funny"> <input type="hidden" name="lastname"
value="Joke"> <br/> <input type="hidden" name="email"> </form> Notice how the form contains hidden fields, so when it is loaded into the browser, the user will not notice it. Because SendAttack() is defined in the body's onload attribute, it will be automatically called when the victim loads the web page. Assuming that the user is already logged in to victim.example.com, profile.php will see that a valid user session has been established, then update the email address to the attacker's own address. At this stage, the user's identity has been compromised, and messages sent through this profile could be sent to the attacker's address.
Architecture and Design Use anti-CSRF packages such as the OWASP CSRFGuard. Implementation Ensure that your application is free of cross-site scripting issues (CWE-79), because most CSRF defenses can be bypassed using attacker-controlled script. Architecture and Design Generate a unique nonce for each form, place the nonce into the form, and verify the nonce upon receipt of the form. Be sure that the nonce is not predictable (CWE-330). Note that this can be bypassed using XSS (CWE-79). Architecture and Design Identify especially dangerous operations. When the user performs a dangerous operation, send a separate confirmation request to ensure that the user intended to perform that operation. Note that this can be bypassed using XSS (CWE-79). Architecture and Design Use the "double-submitted cookie" method as described by Felten and Zeller. Note that this can probably be bypassed using XSS (CWE-79). Architecture and Design Use the ESAPI Session Management control. This control includes a component for CSRF. Architecture and Design Do not use the GET method for any request that triggers a state change. Implementation Check the HTTP Referer header to see if the request originated from an expected page. This could break legitimate functionality, because users or proxies may have disabled sending the Referer for privacy reasons. Note that this can be bypassed using XSS (CWE-79). An attacker could use XSS to generate a spoofed Referer, or to generate a malicious request from a page whose Referer would be allowed. Testing Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules. Use OWASP CSRFTester to identify potential issues.
This issue was under-reported in CVE until around 2008, when it began to gain prominence. It is likely to be present in most web applications. The CSRF topology is multi-channel: 1. Attacker (as outsider) to intermediary (as user). The interaction point is either an external or internal channel. 2. Intermediary (as user) to server (as victim). The activation point is an internal channel.
Peter W. "Cross-Site Request Forgeries (Re: The Dangers of Allowing Users
to Post Images)". Bugtraq. <http:/ Edward W. Felten and
William Zeller. "Cross-Site Request Forgeries: Exploitation and
Prevention". 2008-10-18. <http:/ Robert Auger. "CSRF - The Cross-Site Request Forgery (CSRF/XSRF)
FAQ". <http:/ "Cross-site request forgery". Wikipedia. 2008-12-22. <http:/ Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Alternate_Terms, Description, Relationships,
Other_Notes, Relationship_Notes, Taxonomy_Mappings CWE Content Team. MITRE. 2009-01-12. (Internal) updated Applicable_Platforms, Description,
Likelihood_of_Exploit, Observed_Examples, Other_Notes,
Potential_Mitigations, References, Relationship_Notes, Relationships,
Research_Gaps, Theoretical_Notes CWE Content Team. MITRE. 2009-03-10. (Internal) updated Potential_Mitigations Tom Stracener. 2009-05-20. (External) Added demonstrative example for
profile. CWE Content Team. MITRE. 2009-05-27. (Internal) updated Demonstrative_Examples,
Related_Attack_Patterns Status: Incomplete Weakness ID: 425 (Weakness Base)Summary The web application fails to adequately enforce appropriate authorization on all restricted URLs, scripts or files. Extended Description Web applications susceptible to direct request attacks often make the false assumption that such resources can only be reached through a given navigation path and so only apply authorization at certain points in the path. forced browsing The "forced browsing" term could be misinterpreted to include weaknesses such as CSRF or XSS, so its use is discouraged. If forced browsing is possible, an attacker may be able to directly access a sensitive page by entering a URL similar to the following. JSP Example: http://somesite.com/someapplication/admin.jsp
Apply appropriate access control authorizations for each access to all restricted URLs, scripts or files. Consider using MVC based frameworks such as Struts.
Overlaps Modification of Assumed-Immutable Data (MAID), authorization errors, container errors; often primary to other weaknesses such as XSS and SQL injection. "Forced browsing" is a step-based manipulation involving the omission of one or more steps, whose order is assumed to be immutable. The application does not verify that the first step was performed successfully before the second step. The consequence is typically "authentication bypass" or "path disclosure," although it can be primary to all kinds of weaknesses, especially in languages such as PHP, which allow external modification of assumed-immutable variables.
Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Potential_Mitigations,
Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Alternate_Terms, Relationships,
Relationship_Notes, Taxonomy_Mappings,
Theoretical_Notes CWE Content Team. MITRE. 2008-10-14. (Internal) updated Description Status: Incomplete Weakness ID: 203 (Weakness Class)Summary A discrepancy information leak is an information leak in which the product behaves differently, or sends different responses, in a way that reveals security-relevant information about the state of the product, such as whether a particular operation was successful or not. Compartmentalize your system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Setup generic response for error condition. The error page should not disclose information about the success or failure of a sensitive operation. For instance, the login page should not confirm that the login is correct and the password incorrect. The attacker who tries random account name may be able to guess some of them. Confirming that the account exists would make the login page more susceptible to brute force attack.
Status: Draft Weakness ID: 209 (Weakness Base)Summary The software generates an error message that includes sensitive information about its environment, users, or associated data. Extended Description The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness (CWE-22) might yield the full pathname of the installed application. In turn, this could be used to select the proper number of ".." sequences to navigate to the targeted file. An attack using SQL injection (CWE-89) might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query. Confidentiality Often this will either reveal sensitive information which may be used for a later attack or private information stored in the server. Example 1: In the following example, you are passing much more data than is needed. Java Example: try { /.../ } catch (Exception e) { System.out.println(e); } Another example is passing the SQL exceptions to a WebUser without filtering. Example 2: The following code generates an error message that leaks the full pathname of the configuration file. Perl Example: $ConfigDir = "/home/myprog/config"; $uname = GetUserInput("username"); # avoid CWE-22, CWE-78, others. ExitError("Bad hacker!") if ($uname !~ /^\w+$/); $file = "$ConfigDir/$uname.txt"; if (! (-e $file)) { ExitError("Error: $file does not exist"); } ... If this code is running on a server, such as a web application, then the person making the request should not know what the full pathname of the configuration directory is. By submitting a username that does not produce a $file that exists, an attacker could get this pathname. It could then be used to exploit path traversal or symbolic link following problems that may exist elsewhere in the application.
Implementation Ensure that error messages only contain minimal information that are useful to their intended audience, and nobody else. The messages need to strike the balance between being too cryptic and not being cryptic enough. They should not necessarily reveal the methods that were used to determine the error. Such detailed information can help an attacker craft another attack that now will pass through the validation filters. If errors must be tracked in some detail, capture them in log messages - but consider what could occur if the log messages can be viewed by attackers. Avoid recording highly sensitive information such as passwords in any form. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a username is valid or not. Implementation Handle exceptions internally and do not display errors containing potentially sensitive information to a user. Build and Compilation Debugging information should not make its way into a production release. Testing Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the program under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself. Testing Stress-test the software by calling it simultaneously from a large number of threads or processes, and look for evidence of any unexpected behavior. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. System Configuration Where available, configure the environment to use less verbose error messages. For example, in PHP, disable the display_errors setting during configuration, or at runtime using the error_reporting() function. System Configuration Create default error pages or messages that do not leak any information.
Submissions CLASP. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Applicable_Platforms, Common_Consequences,
Relationships, Other_Notes, Taxonomy_Mappings CWE Content Team. MITRE. 2008-10-14. (Internal) updated Relationships CWE Content Team. MITRE. 2009-01-12. (Internal) updated Demonstrative_Examples, Description, Name,
Observed_Examples, Other_Notes, Potential_Mitigations, Relationships,
Time_of_Introduction CWE Content Team. MITRE. 2009-03-10. (Internal) updated Demonstrative_Examples, Potential_Mitigations,
Relationships Previous Entry Names Error Message Information
Leaks (changed
2009-01-12)Status: Draft Weakness ID: 472 (Weakness Base)Summary The web application does not sufficiently verify inputs that are assumed to be immutable but are actually externally controllable, such as hidden form fields. Extended Description If a web product does not properly protect assumed-immutable values from modification in hidden form fields, parameters, cookies, or URLs, this can lead to modification of critical data. Web applications often mistakenly make the assumption that data passed to the client in hidden fields or cookies is not susceptible to tampering. Failure to validate portions of data that are user-controllable can lead to the application processing incorrect, and often malicious, input. Here, a web application uses the value of a hidden form field (accountID) without having done any input validation because it was assumed to be immutable. Java Example: String accountID = request.getParameter("accountID"); User user = getUserFromID(Long.parseLong(accountID));
Assume all input is malicious. Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the data to be diplayed or stored. Use an "accept known good" validation strategy. Input (specifically, unexpected CRLFs) that is not appropriate should not be processed into HTTP headers. Use and specify a strong input/output encoding (such as ISO 8859-1 or UTF 8). Do not rely exclusively on blacklist validation to detect malicious input or to encode output. There are too many variants to encode a character; you're likely to miss some variants. Inputs should be decoded and canonicalized to the application's current internal representation before being validated. Make sure that your application does not decode the same input twice. Such errors could be used to bypass whitelist schemes by introducing dangerous inputs after they have been checked. This is a primary weakness for many other weaknesses and functional consequences, including XSS, SQL injection, path disclosure, and file inclusion. For example, custom cookies commonly store session data or persistent data across sessions. This kind of session data is normally involved in security related decisions on the server side, such as user authentication and access control. Thus, the cookies might contain sensitive data such as user credentials and privileges. This is a dangerous practice, as it can often lead to improper reliance on the value of the client-provided cookie by the server side application. Without appropriate protection mechanisms, the client can easily tamper with cookies. Reliance on the cookies without detailed validation can lead to problems such as SQL injection. If you use cookie values for security related decisions on the server side, manipulating the cookies might lead to violations of security policies such as authentication bypassing, user impersonation and privilege escalation. In addition, storing sensitive data in the cookie without appropriate protection can also lead to disclosure of sensitive user data, especially data stored in persistent cookies. Hidden fields should not be trusted as secure parameters. An attacker can intercept and alter hidden fields in a post to the server as easily as user input fields. An attacker can simply parse the HTML for the substring < input type "hidden" or even just "hidden". Hidden field values displayed later in the session, such as on the following page, can open a site up to cross-site scripting attacks. This is a technology-specific MAID problem.
Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Potential_Mitigations,
Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Description, Relationships, Other_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-01-12. (Internal) updated Relationships Previous Entry Names Web Parameter
Tampering (changed
2008-04-11)Status: Draft Weakness ID: 311 (Weakness Base)Summary The failure to encrypt data passes up the guarantees of confidentiality, integrity, and accountability that properly implemented encryption conveys. Confidentiality Properly encrypted data channels ensure data confidentiality. Integrity Properly encrypted data channels ensure data integrity. Accountability Properly encrypted data channels ensure accountability. C Example: server.sin_family = AF_INET; hp = gethostbyname(argv[1]); if (hp==NULL) error("Unknown host"); memcpy( (char *)&server.sin_addr,(char
*)hp->h_addr,hp->h_length); if (argc < 3) port = 80; else port = (unsigned short)atoi(argv[3]); server.sin_port =
htons(port); if (connect(sock, (struct sockaddr *)&server, sizeof
server) < 0) error("Connecting"); ... while ((n=read(sock,buffer,BUFSIZE-1))!=-1) { write(dfd,password_buffer,n); ... Java Example: try { URL u = new URL("http://www.importantsecretsite.org/"); HttpURLConnection hu = (HttpURLConnection)
u.openConnection(); hu.setRequestMethod("PUT"); hu.connect(); OutputStream os = hu.getOutputStream(); hu.disconnect();
} catch (IOException e) { //... Requirements specification: require that encryption be integrated into the system. Architecture and Design Ensure that encryption is properly integrated into the system design, not simply as a drop-in replacement for sockets. If the application does not use a secure channel, such as SSL, to exchange sensitive information, it is possible for an attacker with access to the network traffic to sniff packets from the connection and uncover the data. This attack is not technically difficult, but does require physical access to some portion of the network over which the sensitive data travels. This access is usually somewhere near where the user is connected to the network (such as a colleague on the company network) but can be anywhere along the path from the user to the end server. Omitting the use of encryption in any program which transfers data over a network of any kind should be considered on par with delivering the data sent to each user on the local networks of both the sender and receiver. Worse, this omission allows for the injection of data into a stream of communication between two parties -- with no means for the victims to separate valid data from invalid. In this day of widespread network attacks and password collection sniffers, it is an unnecessary risk to omit encryption from the design of any system which might benefit from it.
Submissions CLASP. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Common_Consequences, Relationships, Other_Notes,
Taxonomy_Mappings Previous Entry Names Failure to Encrypt
Data (changed
2008-04-11)Failure to Preserve OS Command Structure ('OS Command Injection') Status: Draft Weakness ID: 78 (Weakness Base)Summary The software uses externally-supplied input to dynamically construct all or part of a command, which is then passed to the operating system for execution, but the software does not sufficiently enforce which commands and arguments are specified. Extended Description This could allow attackers to execute unexpected, dangerous commands directly on the operating system. This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process fails to follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage. There are at least two subtypes of OS command injection: 1) The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing. 2) The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line. From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input. The "OS command injection" phrase carries different meanings to different people. For some, it refers to any type of attack that can allow the attacker to execute OS commands of his or her choosing. This usage could include untrusted search path weaknesses (CWE-426) that cause the application to find and execute an attacker-controlled program. For others, it only refers to the first variant, in which the attacker injects command separators into arguments for an application-controlled program that is being invoked. Further complicating the issue is the case when argument injection (CWE-88) allows alternate command-line switches or options to be inserted into the command line, such as an "-exec" switch whose purpose may be to execute the subsequent argument as a command (this -exec switch exists in the UNIX "find" command, for example). In this latter case, however, CWE-88 could be regarded as the primary weakness in a chain with CWE-78. Confidentiality Integrity Availability Non-Repudiation Attackers could execute unauthorized commands, which could then be used to disable the software, or read and modify data for which the attacker does not have permissions to access directly. Since the targeted application is directly executing the commands instead of the attacker, any malicious activities may appear to come from the application or the application's owner. Example 1: This example is a web application that intends to perform a DNS lookup of a user-supplied domain name. It is subject to the first variant of OS command injection. Perl Example: 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: cwe.mitre.org%20%3B%20/bin/ls%20-l The "%3B" sequence decodes to the ";" character, and the %20 decodes to a space. The open() statement would then process a string like this: /path/to/nslookup cwe.mitre.org ; /bin/ls -l As a result, the attacker executes the "/bin/ls -l" command and gets a list of all the files in the program's working directory. The input could be replaced with much more dangerous commands, such as installing a malicious program on the server. Example 2: The example below reads the name of a shell script to execute from the system properties. It is subject to the second variant of OS command injection. Java Example: String script = System.getProperty("SCRIPTNAME"); if (script != null) System.exec(script); If an attacker has control over this property, then he or she could modify the property to point to a dangerous program.
Architecture and Design If at all possible, use library calls rather than external processes to recreate the desired functionality. Architecture and Design Run your code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which commands can be executed by your software. Examples include the Unix chroot jail and AppArmor. In general, managed code may provide some protection. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of your application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails. Architecture and Design For any data that will be used to generate a command to be executed, keep as much of that data out of external control as possible. For example, in web applications, this may require storing the command locally in the session's state instead of sending it out to the client in a hidden form field. Architecture and Design Use languages, libraries, or frameworks that make it easier to generate properly encoded output. Examples include the ESAPI Encoding control. Implementation Properly quote arguments and escape any special characters within those arguments. If some special characters are still needed, wrap the arguments in quotes, and escape all other characters that do not pass a strict whitelist. Be careful of argument injection (CWE-88). Implementation If the program to be executed allows arguments to be specified within an input file or from standard input, then consider using that mode to pass arguments instead of the command line. Implementation If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. Some languages offer multiple functions that can be used to invoke commands. Where possible, identify any function that invokes a command shell using a single string, and replace it with a function that requires individual arguments. These functions typically perform appropriate quoting and filtering of arguments. For example, in C, the system() function accepts a string that contains the entire command to be executed, whereas execl(), execve(), and others require an array of strings, one for each argument. In Windows, CreateProcess() only accepts one command at a time. In Perl, if system() is provided with an array of arguments, then it will quote each of the arguments. Implementation Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use a whitelist). Reject any input that does not strictly conform to specifications, or transform it into something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks. Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the input for further processing. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue." When constructing OS command strings, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping. Note that proper output encoding, escaping, and quoting is the most effective solution for preventing OS command injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent OS command injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, when invoking a mail program, you might need to allow the subject field to contain otherwise-dangerous inputs like ";" and ">" characters, which would need to be escaped or otherwise handled. In this case, stripping the character might reduce the risk of OS command injection, but it would produce incorrect behavior because the subject field would not be recorded as the user intended. This might seem to be a minor inconvenience, but it could be more important when the program relies on well-structured subject lines in order to pass messages to other components. Even if you make a mistake in your validation (such as forgetting one out of 100 input fields), appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not done in isolation, input validation is still a useful technique, since it may significantly reduce your attack surface, allow you to detect some attacks, and provide other security benefits that proper encoding does not address. Testing Implementation Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible. Testing Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. Operation Run the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force you to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184). Operation Use runtime policy enforcement to create a whitelist of allowable commands, then prevent use of any command that does not appear in the whitelist. Technologies such as AppArmor are available to do this. System Configuration Assign permissions to the software system that prevent the user from accessing/opening privileged files. Run the application with the lowest privileges possible (CWE-250).
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.
A weakness where the code path has: 1. start statement that accepts input 2. end statement that executes an operating system command where a. the input is used as a part of the operating system command b. the input is undesirable Where "input is undesirable" is defined through the following
scenarios: 1. input not validated 2. input incorrectly validated G. Hoglund and
G. McGraw. "Exploiting Software: How to Break Code". Addison-Wesley. February 2004. Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction KDM Analytics. 2008-08-01. (External) added/updated white box definitions Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Relationships, Other_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2008-10-14. (Internal) updated Description CWE Content Team. MITRE. 2008-11-24. (Internal) updated Observed_Examples, Relationships,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-01-12. (Internal) updated Common_Consequences, Demonstrative_Examples,
Description, Likelihood_of_Exploit, Name, Observed_Examples, Other_Notes,
Potential_Mitigations, Relationships, Research_Gaps,
Terminology_Notes CWE Content Team. MITRE. 2009-03-10. (Internal) updated Potential_Mitigations CWE Content Team. MITRE. 2009-05-27. (Internal) updated Name,
Related_Attack_Patterns Previous Entry Names OS Command
Injection (changed
2008-04-11) Failure to Sanitize Data into
an OS Command (aka 'OS Command Injection') (changed
2009-01-12) Failure to Preserve OS
Command Structure (aka 'OS Command
Injection') (changed
2009-05-27)Status: Draft Weakness ID: 89 (Weakness Base)Summary The application dynamically generates an SQL query based on user input, but it does not sufficiently prevent that input from modifying the intended structure of the query. Extended Description Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data. This can be used to alter query logic to bypass security checks, or to insert additional statements that modify the back-end database, possibly including execution of system commands. SQL injection has become a common issue with database-driven web sites. The flaw is easily detected, and easily exploited, and as such, any site or software package with even a minimal user base is likely to be subject to an attempted attack of this kind. This flaw depends on the fact that SQL makes no real distinction between the control and data planes. This weakness typically appears in data-rich applications that save user inputs in a database. Confidentiality Since SQL databases generally hold sensitive data, loss of confidentiality is a frequent problem with SQL injection vulnerabilities. Authentication If poor SQL commands are used to check user names and passwords, it may be possible to connect to a system as another user with no previous knowledge of the password. Authorization If authorization information is held in a SQL database, it may be possible to change this information through the successful exploitation of a SQL injection vulnerability. Integrity Just as it may be possible to read sensitive information, it is also possible to make changes or even delete this information with a SQL injection attack. The application dynamically generates queries that contain user input. Example 1: In 2008, a large number of web servers were compromised using the same SQL injection attack string. This single string worked against many different programs. The SQL injection was then used to modify the web sites to serve malicious code. [1] Example 2: The following code dynamically constructs and executes a SQL query that searches for items matching a specified name. The query restricts the items displayed to those where owner matches the user name of the currently-authenticated user. C# Example: ... string userName = ctx.getAuthenticatedUserName(); string query = "SELECT * FROM items WHERE owner = '" + userName +
"' AND itemname = '" + ItemName.Text + "'"; sda = new SqlDataAdapter(query, conn); DataTable dt = new DataTable(); sda.Fill(dt); ... The query that this code intends to execute follows: SELECT * FROM items WHERE owner = <userName> AND
itemname = <itemName>; However, because the query is constructed dynamically by concatenating a constant base query string and a user input string, the query only behaves correctly if itemName does not contain a single-quote character. If an attacker with the user name wiley enters the string: name' OR 'a'='a for itemName, then the query becomes the following: SELECT * FROM items WHERE owner = 'wiley' AND itemname = 'name' OR
'a'='a'; The addition of the: OR 'a'='a' condition causes the WHERE clause to always evaluate to true, so the query becomes logically equivalent to the much simpler query: 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: name'; DELETE FROM items; -- for itemName, then the query becomes the following two queries: SQL Example: 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 name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a Then the following three valid statements will be created: SELECT * FROM items WHERE owner = 'wiley' AND itemname =
'name'; DELETE FROM items; SELECT * FROM items WHERE 'a'='a'; One traditional approach to preventing SQL injection attacks is to handle them as an input validation problem and either accept only characters from a whitelist of safe values or identify and escape a blacklist of potentially malicious values. Whitelisting can be a very effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. As is almost always the case, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can: - Target fields that are not quoted - Find ways to bypass the need for certain escaped meta-characters - Use stored procedures to hide the injected meta-characters. Manually escaping characters in input to SQL queries can help, but it will not make your application secure from SQL injection attacks. Another solution commonly proposed for dealing with SQL injection attacks is to use stored procedures. Although stored procedures prevent some types of SQL injection attacks, they fail to protect against many others. For example, the following PL/SQL procedure is vulnerable to the same SQL injection attack shown in the first example. 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: SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='$user_input'
ORDER BY PRICE Where $user_input is taken from the user and unfiltered. If the user provides the string: ' exec master..xp_cmdshell 'vol' -- The query will take the following form: " SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='' exec
master..xp_cmdshell 'vol' --' ORDER BY PRICE Now, this query can be broken down into: [1] a first SQL query: SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='' [2] a second SQL query, which executes a shell command: exec master..xp_cmdshell 'vol' [3] an MS SQL comment: --' ORDER BY PRICE As can be seen, the malicious input changes the semantics of the query into a query, a shell command execution and a comment. Example 5: This code intends to print a message summary given the message ID. PHP Example: $id = $_COOKIE["mid"]; mysql_query("SELECT MessageID, Subject FROM messages WHERE
MessageID = '$id'"); The programmer may have skipped any input validation on $id under the assumption that attackers cannot modify the cookie. However, this is easy to do with custom client code or even in the web browser. While $id is wrapped in single quotes in the call to mysql_query(), an attacker could simply change the incoming mid cookie to: 1432' or '1' = '1 This would produce the resulting query: SELECT MessageID, Subject FROM messages WHERE MessageID = '1432' or '1' = '1' Not only will this retrieve message number 1432, it will retrieve all other messages. In this case, the programmer could apply a simple modification to the code to eliminate the SQL injection: PHP Example: $id = intval($_COOKIE["mid"]); mysql_query("SELECT MessageID, Subject FROM messages WHERE
MessageID = '$id'"); However, if this code is intended to support multiple users with different message boxes, the code would need an access control check (CWE-285) to ensure that the application user has the permission to see that message. Example 6: This example attempts to take a last name provided by a user and enter it into a database. Perl Example: $userKey = getUserID(); $name = getUserInput(); # ensure only letters, hyphens and apostrophe are allowed $name = whiteList($name, "^a-zA-z'-$"); $query = "INSERT INTO last_names VALUES('$userKey',
'$name')"; While the programmer applies a whitelist to the user input, it has shortcomings. First of all, the user is still allowed to provide hyphens which are used as comment structures in SQL. If a user specifies -- then the remainder of the statement will be treated as a comment, which may bypass security logic. Furthermore, the whitelist permits the apostrophe which is also a data / command separator in SQL.. If a user supplies a name with an apostrophe, they may be able to alter the structure of the whole statement and even change control flow of the program, possibly accessing or modifying confidential information. In this situation, both the hyphen and apostrophe are legitimate characters for a last name and permitting them is required. Instead, a programmer may want to use a prepared statement or apply an encoding routine to the input to prevent any data / directive misinterpretations.
Architecture and Design Requirements Use languages, libraries, or frameworks that make it easier to generate properly encoded output. For example, consider using persistence layers such as Hibernate or Enterprise Java Beans, which can provide significant protection against SQL injection if used properly. Architecture and Design If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using "exec" or similar functionality, since you may re-introduce the possibility of SQL injection. Architecture and Design Follow the principle of least privilege when creating user accounts to a SQL database. The database users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data. Use the strictest permissions possible on all database objects, such as execute-only for stored procedures. Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Implementation If you need to use dynamically-generated query strings in spite of the risk, use proper encoding and escaping of inputs. Instead of building your own implementation, such features may be available in the database or programming language. For example, the Oracle DBMS_ASSERT package can check or enforce that parameters have certain properties that make them less vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C and PHP. Implementation Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use a whitelist). Reject any input that does not strictly conform to specifications, or transform it into something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks. Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the input for further processing. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue." When constructing SQL query strings, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping. Note that proper output encoding, escaping, and quoting is the most effective solution for preventing SQL injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent SQL injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, the name "O'Reilly" would likely pass the validation step, since it is a common last name in the English language. However, it cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded. When feasible, it may be safest to disallow meta-characters entirely, instead of escaping them. This will provide some defense in depth. After the data is entered into the database, later processes may neglect to escape meta-characters before use, and you may not have control over those processes. Testing Implementation Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible. Testing Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. Operation Use an application firewall that can detect attacks against this weakness. This might not catch all attacks, and it might require some effort for customization. However, it can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth.
SQL injection can be resultant from special character mismanagement, MAID, or blacklist/whitelist problems. It can be primary to authentication errors.
A weakness where the code path has: 1. start statement that accepts input 2. end statement that performs an SQL command where a. the input is part of the SQL command and b. the input is undesirable Where "input is undesirable" is defined through the following
scenarios: 1. input not validated 2. input incorrectly validated M. Howard and
D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003. Steven Friedl. "SQL Injection Attacks by Example". 2007-10-10. <http:/ Ferruh Mavituna. "SQL Injection Cheat Sheet". 2007-03-15. <http:/ David Litchfield, Chris Anley, John Heasman
and Bill Grindlay. "The Database Hacker's Handbook: Defending Database
Servers". Wiley. 2005-07-14. David Litchfield. "The Oracle Hacker's Handbook: Hacking and Defending
Oracle". Wiley. 2007-01-30. Microsoft. "SQL Injection". December 2008. <http:/ Microsoft Security Vulnerability Research &
Defense. "SQL Injection Attack". <http:/ Michael Howard. "Giving SQL Injection the Respect it Deserves". 2008-05-15. <http:/ Submissions PLOVER. (Externally Mined) 7 Pernicious Kingdoms. (Externally Mined) CLASP. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction KDM Analytics. 2008-08-01. (External) added/updated white box definitions Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Applicable_Platforms, Common_Consequences,
Modes_of_Introduction, Name, Relationships, Other_Notes, Relationship_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2008-10-14. (Internal) updated Description CWE Content Team. MITRE. 2008-11-24. (Internal) updated Observed_Examples CWE Content Team. MITRE. 2009-01-12. (Internal) updated Demonstrative_Examples, Description,
Enabling_Factors_for_Exploitation, Modes_of_Introduction, Name,
Observed_Examples, Other_Notes, Potential_Mitigations, References,
Relationships CWE Content Team. MITRE. 2009-03-10. (Internal) updated Potential_Mitigations CWE Content Team. MITRE. 2009-05-27. (Internal) updated Demonstrative_Examples, Name,
Related_Attack_Patterns Previous Entry Names SQL
Injection (changed
2008-04-11) Failure to Sanitize Data into
SQL Queries (aka 'SQL Injection') (changed
2008-09-09) Failure to Sanitize Data
within SQL Queries (aka 'SQL Injection') (changed
2009-01-12) Failure to Preserve SQL Query
Structure (aka 'SQL Injection') (changed
2009-05-27)Failure to Preserve Web Page Structure ('Cross-site Scripting') Status: Draft Weakness ID: 79 (Weakness Base)Summary The software does not sufficiently validate, filter, escape, and encode user-controllable input before it is placed in output that is used as a web page that is served to other users. Extended Description Cross-site scripting (XSS) vulnerabilities occur when: 1. Untrusted data enters a web application, typically from a web request. 2. The web application dynamically generates a web page that contains this untrusted data. 3. During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc. 4. A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data. 5. Since the script comes from a web page that was sent by the web server, the web browser executes the malicious script in the context of the web server's domain. 6. This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain. There are three main kinds of XSS: The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a user to supply dangerous content to a vulnerable web application, which is then reflected back to the user and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to victims. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces victims to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the user, the content is executed and proceeds to transfer private information, such as cookies that may include session information, from the user's machine to the attacker or perform other nefarious activities. The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. The dangerous data is subsequently read back into the application and included in dynamic content. Stored XSS exploits occur when an attacker injects dangerous content into a data store that is later read and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible. 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. XSS CSS "CSS" was once used as the acronym for this problem, but this could cause confusion with "Cascading Style Sheets," so usage of this acronym has declined significantly. Languages All Architectural Paradigms Web-based (Often) Technology Classes Web-Server (Often) Platform Notes XSS flaws are very common in web applications since they require a great deal of developer discipline to avoid them. Confidentiality The most common attack performed with cross-site scripting involves the disclosure of information stored in user cookies. Typically, a malicious user will craft a client-side script, which -- when parsed by a web browser -- performs some activity (such as sending all site cookies to a given E-mail address). This script will be loaded and run by each user visiting the web site. Since the site requesting to run the script has access to the cookies in question, the malicious script does also. Access Control In some circumstances it may be possible to run arbitrary code on a victim's computer when cross-site scripting is combined with other flaws. Confidentiality Integrity Availability The consequence of an XSS attack is the same regardless of whether it is stored or reflected. The difference is in how the payload arrives at the server. XSS can cause a variety of problems for the end user that range in severity from an annoyance to complete account compromise. Some cross-site scripting vulnerabilities can be exploited to manipulate or steal cookies, create requests that can be mistaken for those of a valid user, compromise confidential information, or execute malicious code on the end user systems for a variety of nefarious purposes. Other damaging attacks include the disclosure of end user files, installation of Trojan horse programs, redirecting the user to some other page or site, running "Active X" controls (under Microsoft Internet Explorer) from sites that a user perceives as trustworthy, and modifying presentation of content. Cross-site scripting attacks may occur anywhere that possibly malicious users are allowed to post unregulated material to a trusted web site for the consumption of other valid users, commonly on places such as bulletin-board web sites which provide web based mailing list-style functionality. It is relatively easy for an attacker to find XSS vulnerabilities. Some of these vulnerabilities can be found using scanners, and some exist in older web application servers. Example 1: This example covers 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. JSP Example: <% 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. ASP.NET Example: ... protected System.Web.UI.WebControls.TextBox Login; protected System.Web.UI.WebControls.Label EmployeeID; ... EmployeeID.Text = Login.Text; ... (HTML follows) ... <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. 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. This mechanism of exploiting vulnerable web applications is known as Reflected XSS. Example 2: This example covers 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. JSP Example: <% ... 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. ASP.NET Example: 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; This code functions correctly when the values of name are well-behaved, but it does nothing to prevent exploits if they are not. 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. This type of exploit, known as Stored XSS, is particularly insidious because the indirection caused by the data store makes it more difficult to identify the threat and increases the possibility that the attack will affect multiple users. XSS got its start in this form with web sites that offered a "guestbook" to visitors. Attackers would include JavaScript in their guestbook entries, and all subsequent visitors to the guestbook page would execute the malicious code. As the examples demonstrate, XSS vulnerabilities are caused by code that includes unvalidated data in an HTTP response. To summarize the basic points of Stored XSS: A source outside the application stores dangerous data in a database or other data store The dangerous data is subsequently read back into the application as trusted data The data is then included in dynamic content.
Architecture and Design Use languages, libraries, or frameworks that make it easier to generate properly encoded output. Examples include Microsoft's Anti-XSS library, the OWASP ESAPI Encoding module, and Apache Wicket. Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server. Implementation Architecture and Design Understand the context in which your data will be used and the encoding that will be expected. This is especially important when transmitting data between different components, or when generating outputs that can contain multiple encodings at the same time, such as web pages or multi-part mail messages. Study all expected communication protocols and data representations to determine the required encoding strategies. For any data that will be output to another web page, especially any data that was received from external inputs, use the appropriate encoding on all non-alphanumeric characters. This encoding will vary depending on whether the output is part of the HTML body, element attributes, URIs, JavaScript sections, Cascading Style Sheets, etc. Note that HTML Entity Encoding is only appropriate for the HTML body. Implementation Use and specify a strong character encoding such as ISO-8859-1 or UTF-8. When an encoding is not specified, the web browser may choose a different encoding by guessing which encoding is actually being used by the web page. This can open you up to subtle XSS attacks related to that encoding. See CWE-116 for more mitigations related to encoding/escaping. Implementation With Struts, you should write all data from form beans with the bean's filter attribute set to true. Implementation To help mitigate XSS attacks against the user's session cookie, set the session cookie to be HttpOnly. In browsers that support the HttpOnly feature (such as more recent versions of Internet Explorer and Firefox), this attribute can prevent the user's session cookie from being accessible to malicious client-side scripts that use document.cookie. This is not a complete solution, since HttpOnly is not supported by all browsers. More importantly, XMLHTTPRequest and other powerful browser technologies provide read access to HTTP headers, including the Set-Cookie header in which the HttpOnly flag is set. Implementation Assume all input is malicious. Use an "accept known good" input validation strategy (i.e., use a whitelist). Reject any input that does not strictly conform to specifications, or transform it into something that does. Use a blacklist to reject any unexpected inputs and detect potential attacks. Use a standard input validation mechanism to validate all input for length, type, syntax, and business rules before accepting the input for further processing. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if you are expecting colors such as "red" or "blue." When dynamically constructing web pages, use stringent whitelists that limit the character set based on the expected value of the parameter in the request. All input should be validated and cleansed, not just parameters that the user is supposed to specify, but all data in the request, including hidden fields, cookies, headers, the URL itself, and so forth. A common mistake that leads to continuing XSS vulnerabilities is to validate only fields that are expected to be redisplayed by the site. It is common to see data from the request that is reflected by the application server or the application that the development team did not anticipate. Also, a field that is not currently reflected may be used by a future developer. Therefore, validating ALL parts of the HTTP request is recommended. Note that proper output encoding, escaping, and quoting is the most effective solution for preventing XSS, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent XSS, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, in a chat application, the heart emoticon ("<3") would likely pass the validation step, since it is commonly used. However, it cannot be directly inserted into the web page because it contains the "<" character, which would need to be escaped or otherwise handled. In this case, stripping the "<" might reduce the risk of XSS, but it would produce incorrect behavior because the emoticon would not be recorded. This might seem to be a minor inconvenience, but it would be more important in a mathematical forum that wants to represent inequalities. Even if you make a mistake in your validation (such as forgetting one out of 100 input fields), appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not done in isolation, input validation is still a useful technique, since it may significantly reduce your attack surface, allow you to detect some attacks, and provide other security benefits that proper encoding does not address. Ensure that you perform input validation at well-defined interfaces within the application. This will help protect the application even if a component is reused or moved elsewhere. Testing Implementation Use automated static analysis tools that target this type of weakness. Many modern techniques use data flow analysis to minimize the number of false positives. This is not a perfect solution, since 100% accuracy and coverage are not feasible. Testing Use dynamic tools and techniques that interact with the software using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The software's operation may slow down, but it should not become unstable, crash, or generate incorrect results. Testing Use the XSS Cheat Sheet (see references) to launch a wide variety of attacks against your web application. The Cheat Sheet contains many subtle XSS variations that are specifically targeted against weak XSS defenses. Operation Use an application firewall that can detect attacks against this weakness. This might not catch all attacks, and it might require some effort for customization. However, it can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth. The same origin policy states that browsers should limit the resources accessible to scripts running on a given web site , or "origin", to the resources associated with that web site on the client-side, and not the client-side resources of any other sites or "origins". The goal is to prevent one site from being able to modify or read the contents of an unrelated site. Since the World Wide Web involves interactions between many sites, this policy is important for browsers to enforce. The Domain of a website when referring to XSS is roughly equivalent to the resources associated with that website on the client-side of the connection. That is, the domain can be thought of as all resources the browser is storing for the user's interactions with this particular site. Resultant (where the weakness
is typically related to the presence of some other
weaknesses)
Jeremiah Grossman, Robert "RSnake" Hansen, Petko "pdp" D. Petkov, Anton Rager
and Seth Fogie. "XSS Attacks". Syngress. 2007. "Cross-site scripting". Wikipedia. 2008-08-26. <http:/ M. Howard and
D. LeBlanc. "Writing Secure Code". 2nd Edition. Microsoft. 2003. RSnake. "XSS (Cross Site Scripting) Cheat Sheet". <http:/ Microsoft. "Mitigating Cross-site Scripting With HTTP-only
Cookies". <http:/ Mark Curphey, Microsoft. "Anti-XSS 3.0 Beta and CAT.NET Community Technology Preview now
Live!". <http:/ "OWASP Enterprise Security API (ESAPI) Project". <http:/ Ivan Ristic. "XSS Defense HOWTO". <http:/ OWASP. "Web Application Firewall". <http:/ Web Application Security Consortium. "Web Application Firewall Evaluation Criteria". <http:/ RSnake. "Firefox Implements httpOnly And is Vulnerable to
XMLHTTPRequest". 2007-07-19. "XMLHttpRequest allows reading HTTPOnly
cookies". Mozilla. <https:/ "Apache Wicket". <http:/ Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Alternate_Terms, Applicable_Platforms,
Background_Details, Common_Consequences, Description, Relationships,
Other_Notes, References, Taxonomy_Mappings,
Weakness_Ordinalities CWE Content Team. MITRE. 2009-01-12. (Internal) updated Alternate_Terms, Applicable_Platforms,
Background_Details, Common_Consequences, Demonstrative_Examples,
Description, Detection_Factors, Enabling_Factors_for_Exploitation, Name,
Observed_Examples, Other_Notes, Potential_Mitigations, References,
Relationships CWE Content Team. MITRE. 2009-03-10. (Internal) updated Potential_Mitigations CWE Content Team. MITRE. 2009-05-27. (Internal) updated Name Previous Entry Names Cross-site Scripting
(XSS) (changed
2008-04-11) Failure to Sanitize
Directives in a Web Page (aka 'Cross-site scripting'
(XSS)) (changed
2009-01-12) Failure to Preserve Web Page
Structure (aka 'Cross-site
Scripting') (changed
2009-05-27)Status: Draft Weakness ID: 93 (Weakness Base)Summary The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not properly sanitize CRLF sequences from inputs. If user input data that eventually makes it to a log message isn't checked for CRLF characters, it may be possible for an attacker to forge entries in a log file. Java Example: logger.info("User's street address: " +
request.getParameter("streetAddress"));
Avoid using CRLF as a special sequence. Appropriately filter or quote CRLF sequences in user-controlled input.
Probably under-studied, although gaining more prominence in 2005 as a result of interest in HTTP response splitting.
Ulf Harnhammar. "CRLF Injection". Bugtraq. 2002-05-07. <http:/ Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Relationships, Other_Notes, Taxonomy_Mappings,
Weakness_Ordinalities CWE Content Team. MITRE. 2009-03-10. (Internal) updated References CWE Content Team. MITRE. 2009-05-27. (Internal) updated Name Previous Entry Names CRLF
Injection (changed
2008-04-11) Failure to Sanitize CRLF
Sequences (aka 'CRLF Injection') (changed
2009-05-27)Failure to Sanitize Data into a Control Plane ('Command Injection') Status: Draft Weakness ID: 77 (Weakness Class)Summary The software fails to adequately filter command (control plane) syntax from user-controlled input (data plane) and then allows potentially injected commands to execute within its context. Access Control Command injection allows for the execution of arbitrary commands and code by the attacker. Example 1: The following simple program accepts a filename as a command line argument and displays the contents of the file back to the user. The program is installed setuid root because it is intended for use as a learning tool to allow system administrators in-training to inspect privileged system files without giving them the ability to modify them or damage the system. C Example: int main(char* 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. Example 2: The following code is from an administrative web application designed 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. ... 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 3: The following code from a system utility uses the system property APPHOME to determine the directory in which it is installed and then executes an initialization script based on a relative path from the specified directory. ... String home = System.getProperty("APPHOME"); String cmd = home + INITCMD; java.lang.Runtime.getRuntime().exec(cmd); ... The code above allows an attacker to execute arbitrary commands with the elevated privilege of the application by modifying the system property APPHOME to point to a different path containing a malicious version of INITCMD. Because the program does not validate the value read from the environment, if an attacker can control the value of the system property APPHOME, then they can fool the application into running malicious code and take control of the system. Example 4: The following code is from a web application that allows users access to an interface through which they can update their password on the system. Part of the process for updating passwords in certain network environments is to run a make command in the /var/yp directory, the code for which is shown below. ... System.Runtime.getRuntime().exec("make"); ... The problem here is that the program does not specify an absolute path for make and fails to clean its environment prior to executing the call to Runtime.exec(). If an attacker can modify the $PATH variable to point to a malicious binary called make and cause the program to be executed in their environment, then the malicious binary will be loaded instead of the one intended. Because of the nature of the application, it runs with the privileges necessary to perform system operations, which means the attacker's make will now be run with these privileges, possibly giving the attacker complete control of the system. Example 5: 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: C Example: #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: $ ./catWrapper Story.txt When last we left our heroes... However, if we add a semicolon and another command to the end of this line, the command is executed by catWrapper with no complaint: $ ./catWrapper Story.txt; ls 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. Architecture and Design If at all possible, use library calls rather than external processes to recreate the desired functionality Implementation Utilize black-list parsing to filter non-relevant command syntax from all input. Implementation Ensure that all external commands called from the program are statically created, or -- if they must take input from a user -- that the input and final line generated are vigorously white-list checked. Run time: Run time policy enforcement may be used in a white-list fashion to prevent use of any non-sanctioned commands. Assign permissions to the software system that prevents the user from accessing/opening privileged files. Command injection is a common problem with wrapper programs. Often, parts of the command to be run are controllable by the end user. If a malicious user injects a character (such as a semi-colon) that delimits the end of one command and the beginning of another, he may then be able to insert an entirely new and unrelated command to do whatever he pleases. The most effective way to deter such an attack is to ensure that the input provided by the user adheres to strict rules as to what characters are acceptable. As always, white-list style checking is far preferable to black-list style checking. Dynamically generating operating system commands that include user input as parameters can lead to command injection attacks. An attacker can insert operating system commands or modifiers in the user input that can cause the request to behave in an unsafe manner. Such vulnerabilities can be very dangerous and lead to data and system compromise. If no validation of the parameter to the exec command exists, an attacker can execute any command on the system the application has the privilege to access. Command injection vulnerabilities take two forms: 1. An attacker can change the command that the program executes: the attacker explicitly controls what the command is. 2. An attacker can change the environment in which the command executes: the attacker implicitly controls what the command means. In this case we are primarily concerned with the first scenario, in which an attacker explicitly controls the command that is executed. Command injection vulnerabilities of this type occur when: 1. Data enters the application from an untrusted source. 2. The data is part of a string that is executed as a command by the application. 3. By executing the command, the application gives an attacker a privilege or capability that the attacker would not otherwise have.
G. Hoglund and
G. McGraw. "Exploiting Software: How to Break Code". Addison-Wesley. February 2004. Submissions 7 Pernicious Kingdoms. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Common_Consequences, Relationships, Other_Notes,
Taxonomy_Mappings, Weakness_Ordinalities CWE Content Team. MITRE. 2009-05-27. (Internal) updated Demonstrative_Examples,
Name Previous Entry Names Command
Injection (changed
2008-04-11) Failure to Sanitize Data into
a Control Plane (aka 'Command
Injection') (changed
2009-05-27)Status: Draft Weakness ID: 90 (Weakness Base)Summary The software does not sufficiently sanitize special elements that are used in LDAP queries or responses, allowing attackers to modify the syntax, contents, or commands of the LDAP query before it is executed. In the code excerpt below, user input data (address) isn't properly sanitized before it's used to construct an LDAP query. Java Example: context = new InitialDirContext(env); String searchFilter = "StreetAddress=" + address; NamingEnumeration answer = context.search(searchBase,
searchFilter, searchCtls); Assume all input is malicious. Use an appropriate combination of black lists and white lists to filter or quote LDAP syntax from user-controlled input. Factors: resultant to special character mismanagement, MAID, or blacklist/whitelist problems. Can be primary to authentication and verification errors.
Under-reported. This is likely found very frequently by third party code auditors, but there are very few publicly reported examples.
Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Applicable_Platforms, Relationships, Other_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-05-27. (Internal) updated Name Previous Entry Names LDAP
Injection (changed
2008-04-11) Failure to Sanitize Data into
LDAP Queries (aka 'LDAP Injection') (changed
2009-05-27)Status: Draft Weakness ID: 285 (Weakness Base)Summary The software does not perform or incorrectly performs access control checks across all potential execution paths. Extended Description When access control checks are not applied consistently - or not at all - users are able to access data or perform actions that they should not be allowed to perform. This can lead to a wide range of problems, including information leaks, denial of service, and arbitrary code execution. Availability Confidentiality Integrity Allowing access to unauthorized users can result in an attacker gaining access to the sensitive resources being protected, possibly modifying or removing them, or performing unauthorized actions. Architecture and Design Divide your application into anonymous, normal, privileged, and administrative areas. Reduce the attack surface by carefully mapping roles with data and functionality. Use role-based access control (RBAC) to enforce the roles at the appropriate boundaries. Note that this approach may not protect against horizontal authorization, i.e., it will not protect a user from attacking others with the same role. Architecture and Design Ensure that you perform access control checks related to your business logic. These may be different than the access control checks that you apply to the resources that support your business logic. Architecture and Design Use authorization frameworks such as the JAAS Authorization Framework and the OWASP ESAPI Access Control feature. Architecture and Design For web applications, make sure that the access control mechanism is enforced correctly at the server side on every page. Users should not be able to access any unauthorized functionality or information by simply requesting direct access to that page. One way to do this is to ensure that all pages containing sensitive information are not cached, and that all such pages restrict access to requests that are accompanied by an active and authenticated session token associated with a user who has the required permissions to access that page. Testing Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules. System Configuration Installation Use the access control capabilities of your operating system and server environment and define your access control lists accordingly. Use a "default deny" policy when defining these ACLs.
NIST. "Role Based Access Control and Role Based
Security". <http:/ Submissions 7 Pernicious Kingdoms. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Relationships, Other_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-01-12. (Internal) updated Common_Consequences, Description,
Likelihood_of_Exploit, Name, Other_Notes, Potential_Mitigations, References,
Relationships CWE Content Team. MITRE. 2009-03-10. (Internal) updated Potential_Mitigations CWE Content Team. MITRE. 2009-05-27. (Internal) updated Description,
Related_Attack_Patterns Previous Entry Names Missing or Inconsistent
Access Control (changed
2009-01-12)Status: Draft Weakness ID: 287 (Weakness Class)Summary When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct. authentification An alternate term is "authentification", which appears to be most commonly used by people from non-English-speaking countries.
Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Alternate_Terms, Common_Consequences,
Relationships, Relationship_Notes, Taxonomy_Mappings CWE Content Team. MITRE. 2008-10-14. (Internal) updated Relationships CWE Content Team. MITRE. 2009-01-12. (Internal) updated Name CWE Content Team. MITRE. 2009-05-27. (Internal) updated Description,
Related_Attack_Patterns Previous Entry Names Authentication
Issues (changed
2008-04-11) Insufficient
Authentication (changed
2009-01-12)Improper Control of Filename for Include/Require Statement in PHP Program ('PHP File Inclusion') Status: Draft Compound Element ID: 98 (Compound Element Base: Composite)Summary The PHP application receives input from an upstream component, but it does not restrict or incorrectly restricts the input before its usage in "require," "include," or similar functions. Extended Description In certain versions and configurations of PHP, this can allow an attacker to specify a URL to a remote location from which the software will obtain the code to execute. In other cases in association with path traversal, the attacker can specify a local file that may contain executable statements that can be parsed by PHP.
Assume all input is malicious. Use an appropriate combination of black lists and white lists to ensure only valid and expected input is processed by the system.
This is frequently a functional consequence of other weaknesses. It is usually multi-factor with other factors (e.g. MAID), although not all inclusion bugs involve assumed-immutable data. Direct request weaknesses frequently play a role. Can overlap directory traversal in local inclusion problems. Under-researched and under-reported. Other interpreted languages with "require" and "include" functionality could also product vulnerable applications, but as of 2007, PHP has been the focus. Any web-accessible language that uses executable file extensions is likely to have this type of issue, such as ASP, since .asp extensions are typically executable. Languages such as Perl are less likely to exhibit these problems because the .pl extension isn't always configured to be executable by the web server.
Shaun Clowes. "A Study in Scarlet". <http:/ Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Relationships, Relationship_Notes, Research_Gaps,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-01-12. (Internal) updated Relationships CWE Content Team. MITRE. 2009-03-10. (Internal) updated Relationships CWE Content Team. MITRE. 2009-05-27. (Internal) updated Description, Name Previous Entry Names PHP File
Inclusion (changed
2008-04-11) Insufficient Control of
Filename for Include/Require Statement in PHP Program (aka 'PHP
File Inclusion') (changed
2009-05-27)Improper Sanitization of Directives in Dynamically Evaluated Code ('Eval Injection') Status: Incomplete Weakness ID: 95 (Weakness Base)Summary The software receives input from an upstream component, but it does not sanitize or incorrectly sanitizes code syntax before using the input in a dynamic evaluation call (e.g. "eval"). Extended Description This may allow an attacker to execute arbitrary code, or at least modify what code can be executed. This weakness is prevalent in handler/dispatch procedures that might want to invoke a large number of functions, or set a large number of variables. edit-config.pl: This CGI script is used to modify settings in a configuration file. Perl Example: 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: add_key(",","); system("/bin/ls"); This would produce the following string in handleConfigAction(): 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.
Refactor your code so that it does not need to use eval() at all. Assume all input is malicious. Use an appropriate combination of black lists and white lists to ensure only valid and expected input is processed by the system. Factors: special character errors can play a role in increasing the variety of code that can be injected, although some vulnerabilities do not require special characters at all, e.g. when a single function without arguments can be referenced and a terminator character is not necessary.
This issue is probably under-reported. Most relevant CVEs have been for Perl and PHP, but eval injection applies to most interpreted languages. Javascript eval injection is likely to be heavily under-reported.
Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Applicable_Platforms, Description,
Modes_of_Introduction, Relationships, Other_Notes, Taxonomy_Mappings,
Weakness_Ordinalities CWE Content Team. MITRE. 2009-01-12. (Internal) updated Description, Observed_Examples, Other_Notes,
Research_Gaps CWE Content Team. MITRE. 2009-05-27. (Internal) updated Alternate_Terms, Applicable_Platforms,
Demonstrative_Examples, Description, Name, References Previous Entry Names Direct Dynamic Code
Evaluation ('Eval Injection') (changed
2008-04-11) Insufficient Control of
Directives in Dynamically Evaluated Code (aka 'Eval
Injection') (changed
2009-05-27)Status: Incomplete Weakness ID: 200 (Weakness Class)Summary An information leak is the intentional or unintentional disclosure of information to an actor that is not explicitly authorized to have access to that information. Extended Description The information either (1) is regarded as sensitive within the product's own functionality, such as a private message; or (2) provides information about the product or its environment that could be useful in an attack but is normally not available to the attacker, such as the installation path of a product that is remotely accessible. Many information leaks are resultant (e.g. path disclosure in PHP script error), but they can also be primary (e.g. timing discrepancies in crypto). There are many different types of problems that involve information leaks. Their severity can range widely depending on the type of information that is leaked. Compartmentalize your system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area. Resultant (where the weakness
is typically related to the presence of some other
weaknesses)
Submissions PLOVER. (Externally Mined) Modifications Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction CWE Content Team. MITRE. 2008-09-08. (Internal) updated Likelihood_of_Exploit, Relationships,
Taxonomy_Mappings, Weakness_Ordinalities CWE Content Team. MITRE. 2008-10-14. (Internal) updated Description Status: Draft Weakness ID: 215 (Weakness Variant)Summary The application contains debugging code that can leak sensitive information to untrusted parties. The following code reads a "debugEnabled" system property and writes sensitive debug information to the client browser if true. JSP Example: <% if (Boolean.getBoolean("debugEnabled")) { %> User account number: <%= acctNo %> <% } %>
Do not leave debug statements that could be executed in the source code. Assure that all debug information is eradicated before releasing the software. Architecture and Design Compartmentalize your system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Submissions PLOVER. (Externally Mined) Modifications Sean Eidemiller. Cigital. 2008-07-01. (External) added/updated demonstrative
examples Eric Dalci. Cigital. 2008-07-01. (External) updated Time_of_Introduction Veracode. 2008-08-15. (External) Suggested OWASP Top Ten 2004
mapping CWE Content Team. MITRE. 2008-09-08. (Internal) updated Relationships, Relationship_Notes,
Taxonomy_Mappings CWE Content Team. MITRE. 2009-05-27. (Internal) updated Demonstrative_Examples Status: Incomplete Weakness ID: 522 (Weakness Base)Summary This weakness occurs when the application transmits or stores authentication credentials and uses an insecure method that is susceptible to unauthorized interception and/or retrieval. |
