Prev Next

Java / XML

How do you prevent Injection attacks?

Defending against SQL Injection-JDBC Prepared statements: The Java platform includes a defensive measure to protect yourself against the SQL injection attacks: JDBC prepared statements. JDBC prepared statements to work by precomputing the SQL query into a binary database proprietary format.

Prior to execution, user data is bound to the pre-computed query, and finally, the query is executed. Any reserved control characters or words passed by attackers are considered user data and not part of the SQL statement. Following is a safer SQL example:

//Prevent SQL Injection
String query = "SELECT * FROM users WHERE Name=?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1,userName);
ResultSet results = pstmt.executeQuery(); 

Encoding reserved control sequences within untrusted Input: Proper encoding of data needed to mitigate untrusted input attacks as user may input vulnerable script/malicious code.

To defend against these attacks, reserved character sequences must not be conflated with user data. Specifically, less than and greater than reserved characters in HTML must be changed to their corresponding HTML entity references -- \< and \> respectively. Reserved characters such as ;/?:@=&, unsafe characters such as blank/empty space, "<>#%{}|\^~[]` require encoding.

XML parser defence: XML external entity (XXE) attacks are used to exfiltrate sensitive data, execute server-side port scanning and perform denial-of-service and other attacks by leveraging an XML external entity reference.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
  <!ELEMENT foo ANY >
  <!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<foo>&xxe;</foo>

For example, the above XML fragment leveraged to exfilterated password file, the password file content will be dumped in to browser.

The best way to defend against XXE attacks is to leverage the security features provided by XML parsers. Specific defenses vary between XML parser implementations, but the platform offers a provision to configure security settings by passing arguments to DocumentBuilderFactory.setFeature().

More Related questions...

Show more question and Answers...


Comments & Discussions