...
Many command interpreters and parsers provide their own sanitization and validation methods. When available, their use is preferred over custom sanitization techniques because custom-developed 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.
...
A SQL command to authenticate a user might take the following form:
Code Block |
---|
SELECT * FROM db_user WHERE username='<USERNAME>' AND password='<PASSWORD>' |
...
When injected into the command, the command becomes:
Code Block |
---|
SELECT * FROM db_user WHERE username='validuser' OR '1'='1' AND password=<PASSWORD> |
If validuser
is a valid user name, this SELECT
statement selects the validuser
record in the table. The password is never checked because username='validuser'
is true; consequently, the items after the OR
are not tested. As long as the components after the OR
generate a syntactically correct SQL expression, the attacker is granted the access of validuser
.
Likewise, an attacker could supply a string for <PASSWORD>
such as:
Code Block |
---|
' OR '1'='1 |
This would yield the following command:
...
Code Block | ||
---|---|---|
| ||
class Login { public Connection getConnection() throws SQLException { DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver()); String dbConnection = PropertyManager.getProperty("db.connection"); // canCan hold some value like // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>" return DriverManager.getConnection(dbConnection); } String hashPassword(char[] password) { // createCreate hash of password } public void doPrivilegedAction(String username, char[] password) throws SQLException { Connection connection = getConnection(); if (connection == null) { // handleHandle error } try { String pwd = hashPassword(password); String sqlString = "SELECT * FROM db_user WHERE username = '" + username + "' AND password = '" + pwd + "'"; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sqlString); if (!rs.next()) { throw new SecurityException( "User name or password incorrect" ); } // Authenticated; proceed } finally { try { connection.close(); } catch (SQLException x) { // forwardForward to handler } } } } |
Compliant Solution (PreparedStatement
)
Fortunately, the JDBC library provides an API for building SQL commands that sanitize untrusted data. The java.sql.PreparedStatement
class properly escapes input strings, preventing SQL injection when used properlycorrectly. This is an example of component-based sanitization.
...
Code Block | ||
---|---|---|
| ||
public void doPrivilegedAction( String username, char[] password ) throws SQLException { Connection connection = getConnection(); if (connection == null) { // Handle error } try { String pwd = hashPassword(password); // Ensure that the length of user name 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 } finally { try { connection.close(); } catch (SQLException x) { // forwardForward to handler } } } |
Use the set*()
methods of the PreparedStatement
class to enforce strong type checking. This technique mitigates the SQL injection vulnerability because the input is properly escaped by automatic entrapment within double quotes. Note that prepared statements must be used even with queries that insert data into the database.
...
Depending on the specific data and command interpreter or parser to which data is being sent, appropriate methods must be used to sanitize untrusted user input. 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.
...
Using a schema or DTD to validate XML is convenient when receiving XML that may have been loaded with unsanitized input. If such an XML string has not yet been built, sanitizing input before constructing XML yields better performance.
XML External Entity Attacks
...
An XML document can be dynamically constructed from smaller logical blocks called entities. Entities can be internal, external, or parameter-based. External entities allow the inclusion of XML data from external files.
According to XML W3C Recommendation [W3C 2008], Section section 4.4.3, "Included If Validating":
...
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 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 may also violate rule ERR01-J. Do not allow exceptions to expose sensitive information if the information contained in the exceptions is sensitive.
...
This compliant solution defines a CustomResolver
class that implements the interface org.xml.sax.EntityResolver
. This interface enables a SAX application to customize handling of external entities. The setEntityResolver()
method registers the instance with the corresponding SAX driver. The customized handler uses a simple whitelist for external entities. The resolveEntity()
method returns an empty InputSource
when an input fails to resolve to any of the specified, safe entity source paths. Consequently, when parsing malicious input, the empty InputSource
returned by the custom resolver causes a java.net.MalformedURLException
to be thrown. Note that you must create an XMLReader
object on which to set the custom entity resolver.
This Following is an example of component-based sanitization.:
Code Block | ||
---|---|---|
| ||
class CustomResolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // checkCheck for known good entities String entityPath = "/home/username/java/xxe/file"; if (systemId.equals(entityPath)) { System.out.println("Resolving entity: " + publicId + " " + systemId); return new InputSource(entityPath); } else { return new InputSource(); // Disallow unknown entities // by returning a blank path } } } class XXE { private static void receiveXMLStream(InputStream inStream, DefaultHandler defaultHandler) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); // To set the Entityentity Resolverresolver, an XML reader needs to be created XMLReader reader = saxParser.getXMLReader(); reader.setEntityResolver(new CustomResolver()); reader.setContentHandler(defaultHandler); InputSource is = new InputSource(inStream); reader.parse(is); } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler()); } } |
...
Tool | Version | Checker | Description | |||||
---|---|---|---|---|---|---|---|---|
Fortify | 1.0 | HTTP_Response_Splitting | Implemented | |||||
Coverity | 1.0 | FB.SQL_PREPARED_STATEMENT_GENERATED_ | Implemented | |||||
Findbugs | 1.0 | SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE | Implemented | |||||
Fortify | 1.0 | HTTP_Response_Splitting | Implemented | |||||
Klocwork | SV.DATA.BOUND | Implemented | Findbugs | 1.0SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE | Implemented |
Related Vulnerabilities
CVE-2008-2370 describes a vulnerability in Apache Tomcat 4.1.0 through 4.1.37, 5.5.0 through 5.5.26, and 6.0.0 through 6.0.16. When a RequestDispatcher
is used, Tomcat performs path normalization before removing the query string from the URI, which allows remote attackers to conduct directory traversal attacks and read arbitrary files via a .. (dot dot) in a request parameter.
...
CERT Perl Secure Coding Standard | IDS33-PL. Sanitize untrusted data passed across a trust boundary |
Injection [RST] | |
CWE-116. , Improper encoding or escaping of output |
Bibliography
A Guide to Building Secure Web Applications and Web Services | |
[W3C 2008] | 4.4.3, Included If Validating |
...