Introduction

This document has for objective to provide some tips to handle Injection into Java application code.

Sample codes used in tips are located here.

What is Injection ?

Injection in OWASP Top 10 is defined as following:

Consider anyone who can send untrusted data to the system, including external users, internal users, and administrators.

General advices to prevent Injection

The following point can be applied, in a general way, to prevent Injection issue:

  • Apply Input Validation (using whitelist approach) combined with Output Sanitizing+Escaping on user input/output.
  • If you need to interact with system, try to use API features provided by your technology stack (Java / .Net / PHP…) instead of building command.
    Additional advices are provided on this cheatsheet.

Specific Injection types

Examples in this section will be provided in Java technology (see Maven project associated) but advices are applicable to others technologies like .Net / PHP / Ruby / Python…

SQL

Symptom

Injection of this type occur when the application use untrusted user input to build a SQL query using a String and execute it.

How to prevent

Use Query Parameterization in order to prevent injection.

Example

  1. /*No DB framework used here in order to show the real use of
  2. Prepared Statement from Java API*/
  3. /*Open connection with H2 database and use it*/
  4. Class.forName("org.h2.Driver");
  5. String jdbcUrl = "jdbc:h2:file:" + new File(".").getAbsolutePath() + "/target/db";
  6. try (Connection con = DriverManager.getConnection(jdbcUrl)) {
  7. /* Sample A: Select data using Prepared Statement*/
  8. String query = "select * from color where friendly_name = ?";
  9. List<String> colors = new ArrayList<>();
  10. try (PreparedStatement pStatement = con.prepareStatement(query)) {
  11. pStatement.setString(1, "yellow");
  12. try (ResultSet rSet = pStatement.executeQuery()) {
  13. while (rSet.next()) {
  14. colors.add(rSet.getString(1));
  15. }
  16. }
  17. }
  18. Assert.assertEquals(1, colors.size());
  19. Assert.assertTrue(colors.contains("yellow"));
  20. /* Sample B: Insert data using Prepared Statement*/
  21. query = "insert into color(friendly_name, red, green, blue) values(?, ?, ?, ?)";
  22. int insertedRecordCount;
  23. try (PreparedStatement pStatement = con.prepareStatement(query)) {
  24. pStatement.setString(1, "orange");
  25. pStatement.setInt(2, 239);
  26. pStatement.setInt(3, 125);
  27. pStatement.setInt(4, 11);
  28. insertedRecordCount = pStatement.executeUpdate();
  29. }
  30. Assert.assertEquals(1, insertedRecordCount);
  31. /* Sample C: Update data using Prepared Statement*/
  32. query = "update color set blue = ? where friendly_name = ?";
  33. int updatedRecordCount;
  34. try (PreparedStatement pStatement = con.prepareStatement(query)) {
  35. pStatement.setInt(1, 10);
  36. pStatement.setString(2, "orange");
  37. updatedRecordCount = pStatement.executeUpdate();
  38. }
  39. Assert.assertEquals(1, updatedRecordCount);
  40. /* Sample D: Delete data using Prepared Statement*/
  41. query = "delete from color where friendly_name = ?";
  42. int deletedRecordCount;
  43. try (PreparedStatement pStatement = con.prepareStatement(query)) {
  44. pStatement.setString(1, "orange");
  45. deletedRecordCount = pStatement.executeUpdate();
  46. }
  47. Assert.assertEquals(1, deletedRecordCount);
  48. }

References

JPA

Symptom

Injection of this type occur when the application use untrusted user input to build a JPA query using a String and execute it. It's quite similar to SQL injection but here the altered language is not SQL but JPA QL.

How to prevent

Use Java Persistence Query Language Query Parameterization in order to prevent injection.

Example

  1. EntityManager entityManager = null;
  2. try {
  3. /* Get a ref on EntityManager to access DB */
  4. entityManager = Persistence.createEntityManagerFactory("testJPA").createEntityManager();
  5. /* Define parameterized query prototype using named parameter to enhance readability */
  6. String queryPrototype = "select c from Color c where c.friendlyName = :colorName";
  7. /* Create the query, set the named parameter and execute the query */
  8. Query queryObject = entityManager.createQuery(queryPrototype);
  9. Color c = (Color) queryObject.setParameter("colorName", "yellow").getSingleResult();
  10. /* Ensure that the object obtained is the right one */
  11. Assert.assertNotNull(c);
  12. Assert.assertEquals(c.getFriendlyName(), "yellow");
  13. Assert.assertEquals(c.getRed(), 213);
  14. Assert.assertEquals(c.getGreen(), 242);
  15. Assert.assertEquals(c.getBlue(), 26);
  16. } finally {
  17. if (entityManager != null && entityManager.isOpen()) {
  18. entityManager.close();
  19. }
  20. }

References

Operating System

Symptom

Injection of this type occur when the application use untrusted user input to build a Operating System command using a String and execute it.

How to prevent

Use technology stack API in order to prevent injection.

Example

  1. /* The context taken is, for example, to perform a PING against a computer.
  2. * The prevention is to use the feature provided by the Java API instead of building
  3. * a system command as String and execute it */
  4. InetAddress host = InetAddress.getByName("localhost");
  5. Assert.assertTrue(host.isReachable(5000));

References

XML: XPath Injection

Symptom

Injection of this type occur when the application use untrusted user input to build a XPath query using a String and execute it.

How to prevent

Use XPath Variable Resolver in order to prevent injection.

Example

Variable Resolver implementation.

  1. /**
  2. * Resolver in order to define parameter for XPATH expression.
  3. *
  4. */
  5. public class SimpleVariableResolver implements XPathVariableResolver {
  6. private final Map<QName, Object> vars = new HashMap<QName, Object>();
  7. /**
  8. * External methods to add parameter
  9. *
  10. * @param name Parameter name
  11. * @param value Parameter value
  12. */
  13. public void addVariable(QName name, Object value) {
  14. vars.put(name, value);
  15. }
  16. /**
  17. * {@inheritDoc}
  18. *
  19. * @see javax.xml.xpath.XPathVariableResolver#resolveVariable(javax.xml.namespace.QName)
  20. */
  21. public Object resolveVariable(QName variableName) {
  22. return vars.get(variableName);
  23. }
  24. }

Code using it to perform XPath query.

  1. /*Create a XML document builder factory*/
  2. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  3. /*Disable External Entity resolution for differents cases*/
  4. //Do not performed here in order to focus on variable resolver code
  5. //but do it for production code !
  6. /*Load XML file*/
  7. DocumentBuilder builder = dbf.newDocumentBuilder();
  8. Document doc = builder.parse(new File("src/test/resources/SampleXPath.xml"));
  9. /* Create and configure parameter resolver */
  10. String bid = "bk102";
  11. SimpleVariableResolver variableResolver = new SimpleVariableResolver();
  12. variableResolver.addVariable(new QName("bookId"), bid);
  13. /*Create and configure XPATH expression*/
  14. XPath xpath = XPathFactory.newInstance().newXPath();
  15. xpath.setXPathVariableResolver(variableResolver);
  16. XPathExpression xPathExpression = xpath.compile("//book[@id=$bookId]");
  17. /* Apply expression on XML document */
  18. Object nodes = xPathExpression.evaluate(doc, XPathConstants.NODESET);
  19. NodeList nodesList = (NodeList) nodes;
  20. Assert.assertNotNull(nodesList);
  21. Assert.assertEquals(1, nodesList.getLength());
  22. Element book = (Element)nodesList.item(0);
  23. Assert.assertTrue(book.getTextContent().contains("Ralls, Kim"));

References

HTML/JavaScript/CSS

Symptom

Injection of this type occur when the application use untrusted user input to build a HTTP response and sent it to browser.

How to prevent

Either apply strict input validation (whitelist approach) or use output sanitizing+escaping if input validation is not possible (combine both every time is possible).

Example

  1. /*
  2. INPUT WAY: Receive data from user
  3. Here it's recommended to use strict input validation using whitelist approach.
  4. In fact, you ensure that only allowed characters are part of the input received.
  5. */
  6. String userInput = "You user login is owasp-user01";
  7. /* First we check that the value contains only expected character*/
  8. Assert.assertTrue(Pattern.matches("[a-zA-Z0-9\\s\\-]{1,50}", userInput));
  9. /* If the first check pass then ensure that potential dangerous character
  10. that we have allowed for business requirement are not used in a dangerous way.
  11. For example here we have allowed the character '-', and, this can
  12. be used in SQL injection so, we
  13. ensure that this character is not used is a continuous form.
  14. Use the API COMMONS LANG v3 to help in String analysis...
  15. */
  16. Assert.assertEquals(0, StringUtils.countMatches(userInput.replace(" ", ""), "--"));
  17. /*
  18. OUTPUT WAY: Send data to user
  19. Here we escape + sanitize any data sent to user
  20. Use the OWASP Java HTML Sanitizer API to handle sanitizing
  21. Use the OWASP Java Encoder API to handle HTML tag encoding (escaping)
  22. */
  23. String outputToUser = "You <p>user login</p> is <strong>owasp-user01</strong>";
  24. outputToUser += "<script>alert(22);</script><img src='#' onload='javascript:alert(23);'>";
  25. /* Create a sanitizing policy that only allow tag '<p>' and '<strong>'*/
  26. PolicyFactory policy = new HtmlPolicyBuilder().allowElements("p", "strong").toFactory();
  27. /* Sanitize the output that will be sent to user*/
  28. String safeOutput = policy.sanitize(outputToUser);
  29. /* Encode HTML Tag*/
  30. safeOutput = Encode.forHtml(safeOutput);
  31. String finalSafeOutputExpected = "You <p>user login</p> is <strong>owasp-user01</strong>";
  32. Assert.assertEquals(finalSafeOutputExpected, safeOutput);

References

LDAP

A dedicated cheatsheet has been created.

NoSQL

Symptom

Injection of this type occur when the application use untrusted user input to build a NoSQL API call expression.

How to prevent

As there many NoSQL database system and each one use a API for call, it's important to ensure that user input received and used to build the API call expression do not contains any character that have a special meaning in the target API syntax. This in order to avoid that it will be used to escape the initial call expression in order to create another one based on crafted user input. It's also important to not use string concatenation to build API call expression but use the API to create the expression.

Example - MongoDB

  1. /* Here use MongoDB as target NoSQL DB */
  2. String userInput = "Brooklyn";
  3. /* First ensure that the input do no contains any special characters
  4. for the current NoSQL DB call API,
  5. here they are: ' " \ ; { } $
  6. */
  7. //Avoid regexp this time in order to made validation code
  8. //more easy to read and understand...
  9. ArrayList<String> specialCharsList = new ArrayList<String>() { {
  10. add("'");
  11. add("\"");
  12. add("\\");
  13. add(";");
  14. add("{");
  15. add("}");
  16. add("$");
  17. } };
  18. specialCharsList.forEach(specChar -> Assert.assertFalse(userInput.contains(specChar)));
  19. //Add also a check on input max size
  20. Assert.assertTrue(userInput.length() <= 50);
  21. /* Then perform query on database using API to build expression */
  22. //Connect to the local MongoDB instance
  23. try(MongoClient mongoClient = new MongoClient()){
  24. MongoDatabase db = mongoClient.getDatabase("test");
  25. //Use API query builder to create call expression
  26. //Create expression
  27. Bson expression = eq("borough", userInput);
  28. //Perform call
  29. FindIterable<org.bson.Document> restaurants = db.getCollection("restaurants").find(expression);
  30. //Verify result consistency
  31. restaurants.forEach(new Block<org.bson.Document>() {
  32. @Override
  33. public void apply(final org.bson.Document doc) {
  34. String restBorough = (String)doc.get("borough");
  35. Assert.assertTrue("Brooklyn".equals(restBorough));
  36. }
  37. });
  38. }

References

Log Injection

Symptom

Log Injection occurs when an application includes untrusted data in an application log message (e.g., an attacker can cause an additional log entry that looks like it came from a completely different user, if they can inject CRLF characters in the untrusted data). More information about this attack is available on the OWASP Log Injection page.

How to prevent

To prevent an attacker from writing malicious content into the application log, apply defenses such as:

  • Filter the user input used to prevent injection of Carriage Return (CR) or Line Feed (LF) characters.
  • Limit the size of the user input value used to create the log message.
  • Make sure all XSS defenses are applied when viewing log files in a web browser.

Example using Log4j2

Configuration of a logging policy to roll on 10 files of 5MB each, and encode/limit the log message using the Pattern encode{}{CRLF}, introduced in Log4j2 v2.10.0, and the -500m message size limit.:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Configuration status="error" name="SecureLoggingPolicy">
  3. <Appenders>
  4. <RollingFile name="RollingFile" fileName="App.log" filePattern="App-%i.log" ignoreExceptions="false">
  5. <PatternLayout>
  6. <!-- Encode any CRLF chars in the message and limit its
  7. maximum size to 500 characters -->
  8. <Pattern>%d{ISO8601} %-5p - %encode{ %.-500m }{CRLF}%n</Pattern>
  9. </PatternLayout>
  10. <Policies>
  11. <SizeBasedTriggeringPolicy size="5MB"/>
  12. </Policies>
  13. <DefaultRolloverStrategy max="10"/>
  14. </RollingFile>
  15. </Appenders>
  16. <Loggers>
  17. <Root level="debug">
  18. <AppenderRef ref="RollingFile"/>
  19. </Root>
  20. </Loggers>
  21. </Configuration>

Usage of the logger at code level:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
...
// No special action needed because security actions are 
// performed at the logging policy level
Logger logger = LogManager.getLogger(MyClass.class);
logger.info(logMessage);
...

Example using Logback with the OWASP Security Logging library

Configuration of a logging policy to roll on 10 files of 5MB each, and encode/limit the log message using the CRLFConverter, provided by the OWASP Security Logging Project, and the -500msg message size limit:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- Define the CRLFConverter -->
    <conversionRule conversionWord="crlf" converterClass="org.owasp.security.logging.mask.CRLFConverter" />
    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>App.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <fileNamePattern>App-%i.log</fileNamePattern>
            <minIndex>1</minIndex>
            <maxIndex>10</maxIndex>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>5MB</maxFileSize>
        </triggeringPolicy>
        <encoder>
            <!-- Encode any CRLF chars in the message and limit 
                 its maximum size to 500 characters -->
            <pattern>%relative [%thread] %-5level %logger{35} - %crlf(%.-500msg) %n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="RollingFile" />
    </root>
</configuration>

You also have to add the OWASP Security Logging dependency to your project.

Usage of the logger at code level:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
// No special action needed because security actions 
// are performed at the logging policy level
Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.info(logMessage);
...

References

Note that the default Log4j2 encode{} encoder is HTML, which does NOT prevent log injection. 

It prevents XSS attacks against viewing logs using a browser. 

OWASP recommends defending against XSS attacks in such situations in the log viewer application itself, 
not by preencoding all the log messages with HTML encoding as such log entries may be used/viewed in many 
other log viewing/analysis tools that don't expect the log data to be pre-HTML encoded.