Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

A1 Injection

...

The following code example uses a PreparedStatement, Java’s implementation of a parameterized query, to execute the same database query.

Code Block

String custname = request.getParameter("customerName"); // This should REALLY be validated too
// perform input validation to detect attacks
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );*
pstmt.setString( 1, custname);*
ResultSet results = pstmt.executeQuery( );

1.1. Safe Java Prepared Statement ExampleThe following code example uses a PreparedStatement, Java's implementation of a parameterized query, to execute the same database query.

Code Block
  String custname = request.getParameter("customerName"); // This should REALLY be validated too
// perform input validation to detect attacks
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );

h5. 1.2. Hibernate Query Language (HQL) Prepared Statement (Named Parameters) Examples

 First is an unsafe HQL Statement

Code Block

 Query unsafeHQLQuery = session.createQuery("from Inventory where productID='"userSuppliedParameter"'");

 Here is a safe version of the same query using named parameters: 

Code Block

Query safeHQLQuery = session.createQuery("from Inventory where productID=:productid");

 safeHQLQuery.setParameter("productid", userSuppliedParameter);

Defense Option 2: Stored Procedures

Code Block

String custname = request.getParameter("customerName"); // This should REALLY be validated

 try {

                    *CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance\(?)}");*

                    cs.setString(1, custname);

                    ResultSet results = cs.executeQuery();                             

                    // ... result set handling

 } catch (SQLException se)

Defense Option 3: White List Input Validation

Various parts of SQL queries aren't legal locations for the use of bind variables, such as the names of tables or columns, and the sort order indicator (ASC or DESC). In such situations, input validation or query redesign is the most appropriate defense. For the names of tables or columns, ideally those values come from the code, and not from user parameters. But if user parameter values are used to make different for table names and column names, then the parameter values should be mapped to the legal/expected table or column names to make sure unvalidated user input doesn't end up in the query. Please note, this is a symptom of poor design and a full re-write should be considered if time allows. Here is an example of table name validation.

Code Block
  String tableName;
switch(PARAM):
case "Value1": tableName = "fooTable";
break;
case "Value2": tableName = "barTable";
break;
...
default      : throw new InputValidationException("unexpected value provided for table name");

The tableName can then be directly appended to the SQL query since it is now known to be one of the legal and expected values for a table name in this query. Keep in mind that generic table validation functions can lead to data loss as table names are used in queries where they are not expected.

For something simple like a sort order, it would be best if the user supplied input is converted to a boolean, and then that boolean is used to select the safe value to append to the query. This is a very standard need in dynamic query creation. For example:

Code Block
 public String someMethod(boolean sortOrder) {

 String SQLquery = "some SQL ... order by Salary " + (sortOrder ? "ASC" : "DESC");
 ...

Any time user input can be converted to a non-String, like a date, numeric, boolean, enumerated type, etc. before it is appended to a query, or used to select a value to append to the query, this ensures it is safe to do so.

Input validation is also recommended as a secondary defense in ALL cases, even when using bind variables as is discussed later in this article. More techniques on how to implement strong white list input validation is described in the Input Validation Cheat Sheet.

Defense Option 4: Escaping All User Supplied Input

...

The LIKE keyword allows for text scanning searches. In Oracle, the underscore '_' character matches only one character, while the ampersand '%' is used to match zero or more occurrences of any characters. These characters must be escaped in LIKE clause criteria. For example:
Code Block

SELECT name FROM emp
WHERE id LIKE '%/_%' ESCAPE '/';
SELECT name FROM emp
WHERE id LIKE '%%%' ESCAPE '\';

...

Detailed XXE Prevention guidance for a number of languages and commonly used XML parsers in those languages is provided below.

JAXP DocumentBuilderFactory and SAXParserFactory

...

For a syntax highlighted code snippet for SAXParserFactory, click here.import javax.xml.parsers.DocumentBuilderFactory;

Code Block

import javax.xml.parsers.ParserConfigurationException; // catching unsupported features
...

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
      // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
      // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
      String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
      dbf.setFeature(FEATURE, true);
 
      // If you can't completely disable DTDs, then at least do the following:
      // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
      // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
      // JDK7+ - http://xml.org/sax/features/external-general-entities   
      FEATURE = "http://xml.org/sax/features/external-general-entities";
      dbf.setFeature(FEATURE, false);
 
      // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
      // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
      // JDK7+ - http://xml.org/sax/features/external-parameter-entities   
      FEATURE = "http://xml.org/sax/features/external-parameter-entities";
      dbf.setFeature(FEATURE, false);

      // Disable external DTDs as well
      FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd"
      dbf.setFeature(FEATURE, false);
 
      // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference below)
      dbf.setXIncludeAware(false);
      dbf.setExpandEntityReferences(false);

      // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
      // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
      // (http://cwe.mitre.org/data/definitions/918.html) and denial
      // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."
 
      // remaining parser logic
      ...


      catch (ParserConfigurationException e) {
            // This should catch a failed setFeature feature
            logger.info("ParserConfigurationException was thrown. The feature '" +
                        FEATURE +
                        "' is probably not supported by your XML processor.");
            ...
        }
      catch (SAXException e) {
            // On Apache, this should be thrown when disallowing DOCTYPE
            logger.warning("A DOCTYPE was passed into the XML document");
            ...
        }
     catch (IOException e) {
            // XXE that points to a file that doesn't exist
            logger.error("IOException occurred, XXE may still possible: " + e.getMessage());
            ...
        }

...

https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet

A 1.3. ORM Mappers

In most cases, using ORM mapper such as Hibernate will protect you from SQL Injection since all database calls are implemented with prepared statements. In Hibernate, avoid code such as:

Code Block

Query query = session.createQuery("SELECT * FROM TABLE WHERE SOMEVAL = ' + user_supplied_variable + "'");

Use binding syntax instead:

Code Block

Query query = session.createQuery("SELECT * FROM TABLE WHERE SOMEVAL= :someval";
query.setString(":someval", user_supplied_variable);

...

Use positive validation to eliminate all but valid username and other dynamic inputs. The following code is vulnerable to LDAP injection:

Code Block

String principal = "cn=" + getParameter("username") + ", ou=Users, o=example";
String password = getParameter("password");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password);
// Create the initial context
DirContext ctx = new InitialDirContext(env);


//Instead, implement code for LDAP as follows: 


// if the username contains LDAP specials, stop now
if ( containsLDAPspecials(getParameter("username")) ) {
       
    throw new javax.naming.AuthenticationException();
}
String principal = "cn=" + getParameter("username") + ", ou=Users, o=example";
String password = getParameter("password");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principal);
env.put(Context.SECURITY_CREDENTIALS, password);
// Create the initial context
DirContext ctx = new InitialDirContext(env);

...