Versions Compared

Key

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

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.

...

Many command interpreters and parsers provide their own sanitization and validation methods. When available, their use is preferred over custom sanitization techniques , as because 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.

...

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 untrusted input , and parameterizing the query.

...

Unfortunately, this code example permits an SQL injection attack , because the SQL statement sqlString accepts unsanitized input arguments. The attack scenario outlined above would work as described.

Code Block
bgColor#FFcccc
class Login {
  public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver());
    String dbConnection = PropertyManager.getProperrty("db.connection");
    // can hold some value like "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
    return DriverManager.getConnection(dbConnection);
  }

  String hashPassword(char[] password) {
    // create hash of password
  }

  public void doPrivilegedAction(String username, char[] password) throws SQLException {
    Connection connection = getConnection(); 
    if (connection == null) {
      // handle error
    }
    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 Passwordpassword incorrect");
    } 

    // Authenticated; proceed
  } 
}

Compliant Solution (PreparedStatement)

...

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 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 Passwordpassword incorrect");
    } 

    // Authenticated; proceed
  } 
}

Use 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 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.

A user who has the ability to add structured XML as input 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 overridden.

...

Code Block
bgColor#ccccff
private void createXMLStream(BufferedOutputStream outStream, String quantity) {
  // Write XML string if quantity contains numbers only (white-listingwhitelisting)
  // Black-listingBlacklisting of invalid characters can also be done in conjunction
  
  if (!Pattern.matches("[0-9]+", quantity)) {
    // Format violation
  }

  String xmlString = "<item>\n<description>Widget</description>\n<price>500</price>\n" +
                     "<quantity>" + quantity + "</quantity></item>";
  outStream.write(xmlString.getBytes());
  outStream.flush();
}

...

Wiki Markup
According to XML W3C Recommendation \[[W3C 2008|AA. Bibliography#W3C 08]\], Section 4.4.3, "Included If Validating,"

When an XML processor recognizes a reference to a parsed entity, to validate the document, the processor MUST include its replacement text. If the entity is external, and the processor is not attempting to validate the XML document, the processor MAY, but need not, include the entity's replacement text.

...

Code Block
bgColor#FFcccc
class XXE {
  private static void receiveXMLStream(InputStream inStream, 
                                       DefaultHandler defaultHandler)
      throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(inStream, defaultHandler);
  }
  
  public static void main(String[] args)
      throws ParserConfigurationException, SAXException, IOException {
    receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
  }
}

Unfortunately, this program is subject to a remote XXE attack , if the evil.xml file contains the following:

...

Code Block
bgColor#ccccff
class CustomResolver implements EntityResolver {
  public InputSource resolveEntity(String publicId, String systemId)
    throws SAXException, IOException {

    // check 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 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 Entity Resolver, an XML reader needs to be created
    XMLReader reader = saxParser.getXMLReader(); 
    reader.setEntityResolver(new CustomResolver());
    reader.setErrorHandler(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());
  }
}

...

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]
\[[W3C 2008|AA. Bibliography#W3C 08]\] 4.4.3 Included If Validating

...