Home » Java » Core Java » Handling Injection Attacks in Java

About Eidher Julian

Eidher Julian Cadavid
Eidher Julian is a Systems Engineer and Software Engineering Specialist with 13+ years of experience as a Java developer. He is an Oracle Certified Associate and SOA Certified Architect.

Handling Injection Attacks in Java

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:

A patch to the SQL injection

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

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:

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

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:

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:

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

@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:

For more information see: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html

Published on Java Code Geeks with permission by Eidher Julian, partner at our JCG program. See the original article here: Handling Injection Attacks in Java Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
1 Comment Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
St1mpy
St1mpy
1 month ago

Good article