Handling Injection Attacks in Java
Tags: java, injection, sqlinjection, xxeinjection
Published: 2021-03-14 03:21:53

An injection attack is the insertion of malicious data from the client to the application using SQL or XXE (XML External Entity).
It is important to prevent injection attacks because it allows attackers to spoof identity, tamper with existing data, disclosure all the data, destroy the data, become the administrator, etc.

#SQL Injection

If the attacker introduces something like ' or 1=1 -- the application could display data from the database:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/555ip8rnfurapt3xkzs4.png)

#A patch to the SQL injection

The flaw is because the field (accountName) is concatenated to the SQL statement:

```java
String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";

Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
```

To patch this flaw you must use Immutable Queries, Static Queries, Parameterized Queries, or Stored Procedures. For the previous example the best solution is a parameterized query:

```java
final String query = "SELECT * FROM user_data WHERE last_name = ?";

try {
  PreparedStatement statement = connection.prepareStatement(query,
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
  statement.setString(1, accountName);
  ResultSet results = statement.executeQuery(query);
  ...
} catch (SQLException sqle) {
  ...
}
```

Now, if you try to inject SQL you get an exception.

#XXE Injection

If you have a service that receives an XML, somebody could change that XML (using Burp Suite) in order to access local resources, execute code remotely, disclose files, or execute a DoS attack ([using a Billion laughs attack](https://en.wikipedia.org/wiki/Billion_laughs_attack)).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2svu66ywgnl2jwaa0pm4.png)

You may say "no worries, I use JSON in my REST services". However, the attacker could change the content type of the request body and send the same XML. For instance, next we have the request of a service caught by Burp Suite (ellipsis is used to omit irrelevant information):

```
...
Content-Type: application/json
...

{"text":"test"}
```

It is as easy as to change the Content-Type to XML and the payload to perform the attack:

```
...
Content-Type: application/xml
...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
  <!ELEMENT foo ANY>
  <!ENTITY xxe SYSTEM "../../">
]>
<comment>
  <text>&xxe;</text>
</comment>
```
This service is used to post a comment, but now we have posted a directory of the server:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2ab5r5ggmjhpxq7yxqu.png)

After some tries, you could print the content of an important file (like passwords or configurations).

#A patch to the XXE injection

You can validate the input, the content type, or instruct your parser to ignore DTD (document type definition). See the setProperty invocation:

```java
protected Comment parseXml(String xml) throws Exception {
  JAXBContext jc = JAXBContext.newInstance(Comment.class);

  XMLInputFactory xif = XMLInputFactory.newFactory();
  xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);

  XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(XML));

  Unmarshaller unmarshaller = jc.createUnmarshaller();
  return (Comment) unmarshaller.unmarshal(xsr);
}
```

For Spring REST Services, you can specify the consumes = MediaType.APPLICATION_JSON_VALUE:

```java
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public AttackResult createNewUser(@RequestBody String commentStr, @RequestHeader("Content-Type") String contentType) throws Exception {
        ...
}
```

Now, the attacker cannot send XML:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3sz6h9gf8tokt219nmg5.png)

For more information see: [https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html)