Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: done editing, phew!

Many programs accept untrusted data originating from unvalidated users, network connections, and other untrusted sources and then pass the (modified or unmodified) data to across a trust boundary to a different trusted domain. Frequently the data is in the form of a string with some internal syntactic structure, which the subsystem must parse. Such data must be sanitized, both because the subsystem may be unprepared to handle the malformed input, and also because unsanitized input may include an injection attack.

ConsequentlyIn particular, programs must sanitize all string data that is passed to parsers or command interpreters or parsers so that the resulting string is innocuous in the context in which it will be parsed or interpreted.

Many parsers and command interpreters and parsers provide their own sanitization and validation APIsmethods. When available, their use is preferred over homegrown custom sanitization techniques, as homegrown sanitization can often neglect special cases or hidden complexities in the parser. Another problem with custom sanitization code is that it may not be adequately maintained when new capabilities are added to the command interpreter or parser software.

SQL Injection

An SQL injection vulnerability arises when the original SQL query can be altered to form an altogether different query. Execution of this altered query may result in information leaks or data modification. The primary means of preventing SQL injection are sanitizing and validating and sanitizing user untrusted input, and parameterizing the query.

Suppose a database contains usernames user names and passwords used to allow authenticate users to authenticate to of the system. The usernames user names have a string size limit of 8. The passwords have a size limit of 20.

An SQL command to authenticate a user would might take the form:

Code Block
SELECT * FROM db_user WHERE username=<USERNAME> AND password=<PASSWORD>

If it returns any records, the username user name and password are valid.

However, if an attacker can substitute any strings for <USERNAME> and <PASSWORD>, they can perform an SQL injection by using the following string for <USERNAME>:

...

If validuser is actually a valid user name, this SELECT statement will select the validuser record in the table. The hashed password will is never be checked because the expression '1'='1' is always true. Consequently the attacker is granted the access of validuser.

...

This time, the '1'='1' tautology disables both username user name and password validation, and the attacker is falsely logged in without knowing a login ID or password.

...

This noncompliant code example shows JDBC code to authenticate a user to a system. The password is passed as a char array, the database connection is created, and then the passwords are hashed , all to comply with MSC05-J. Store passwords using a hash function and MSC10-J. Limit the lifetime of sensitive data.

...

This compliant solution uses a PreparedStatement instead of java.sql.Statement. This code also validates the length of the username argument, preventing an attacker from submitting an arbitrarily long usernameuser name.

Code Block
bgColor#ccccff
class Login {
  public void doPrivilegedAction(String username, char[] password) throws SQLException {
    Connection connection = getConnection(); 
    if (connection == null) {
      // handle error
    }
    String pwd = hashPassword(password);
   
    // Ensure that the length of user usernamename is legitimate  
    if ((username.length() >= 8) {
      // Handle error
    }
	    
    String sqlString = "select * from db_user where username=? and password=?";
    PreparedStatement stmt = connection.prepareStatement(sqlString);
    stmt.setString(1, username);
    stmt.setString(2, pwd);
    ResultSet rs = stmt.executeQuery();
    if (!rs.next()) {
      throw new SecurityException("User name or Password incorrect");
    } 

    // Authenticated; proceed
  } 
}

Use PreparedStatement's the set*() methods of the PreparedStatement class to enforce strong type checking. This mitigates the SQL injection vulnerability because the input is properly escaped by automatic entrapment within double quotes. Note that Prepared Statements prepared statements must be used even with queries that insert data into the database.

...

Because of its platform independence, flexibility and relative simplicity, the extensible markup language (XML) has found use in applications ranging from remote procedure calls to systematic storage, exchange and retrieval of data. However, because of its versatility, XML is vulnerable to a wide spectrum of attacks. One such attack is called XML Injection.

When a A user who has the ability to add structured XML as input , he can override the contents of an XML document by injecting XML tags in data fields. These tags are interpreted and classified by an XML parser as executable content and as a result, may cause certain data members to be unintentionally overridden.

Consider the following XML code snippet from an online store application, designed primarily to query a backend back-end database. The user has the ability to specify the quantity of an item , available for purchase.

Code Block
<item>
  <description>Widget</description>
  <price>500.0</price>
  <quantity>1</quantity>
</item>

A malicious user inputs might input the following string instead of a simple number in the quantity field.

...

Compliant Solution (Whitelisting)

Depending on the applicationspecific data and command interpreter or parser to which data is being sent, different methods may must be used to sanitize the untrusted user -specified data. This compliant solution uses whitelisting to sanitize the input. In this compliant solution, the method requires that the quantity field must be a number between 0 and 9.

...

An XML document can be dynamically constructed from smaller logical blocks called entities. Entities can be either internal, external, or parameter-based. External entities allow the inclusion of XML data from external files.

...

An attacker may attempt to cause denial of service or program crashes by manipulating the URI of the entity to refer to special files existing on the local file system, for example, by specifying /dev/random or /dev/tty as input URIs. This severely affects the behavior of the program by crashing or blocking it may crash or block the program indefinitely. This is called an XML External Entity (XXE) attack. Because inclusion of replacement text from an external entity is optional, not all XML processors are vulnerable to external entity attacks.

...

This noncompliant code example attempts to parse the file evil.xml, reports any errors, and exits. However, a SAX or a DOM parser will attempt to access the url URL specified by the SYSTEM attribute, which means it will try attempt to read the contents of the local /dev/tty file. On POSIX system, reading this file causes the program to block until input data is supplied to the machine's console. Consequently, an attacker can use this malicious XML file to cause the program to hang.

...

Search for other vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

Wiki Markup
\[[OWASP 2005|AA. Bibliography#OWASP 05]\] 
\[[OWASP 2007|AA. Bibliography#OWASP 07]\]
\[[OWASP 2008|AA. Bibliography#OWASP 08]\] [Testing for XML Injection (OWASP-DV-008)|http://www.owasp.org/index.php/Testing_for_XML_Injection_%28OWASP-DV-008%29]
Wiki Markup
\[[OWASP 2005|AA. Bibliography#OWASP 05]\] 
\[[OWASP 2007|AA. Bibliography#OWASP 07]\]
\[[W3C 2008|AA. Bibliography#W3C 08]\] 4.4.3 Included If Validating

...