...
Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker's hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
Defenses:
1.SQL Injection Prevention Cheat Sheet
1.1. Prepared Statements (with Parameterized Queries)https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Primary_Defenses
...
1.1.1 Safe Java Prepared Statement Example
The following code example uses a PreparedStatement, Java's implementation of a parameterized query, to execute the same database query.
String custname = request.getParameter("customerName"); // This should REALLY be validated too
// perform input validation to detect attacks
String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
PreparedStatement pstmt = connection.prepareStatement( query );
pstmt.setString( 1, custname);
ResultSet results = pstmt.executeQuery( );
1.
...
2. Hibernate Query Language (HQL) Prepared Statement (Named Parameters) Examples
First is an unsafe HQL Statement
...
Code Block |
---|
Query safeHQLQuery = session.createQuery("from Inventory where productID=:productid"); safeHQLQuery.setParameter("productid", userSuppliedParameter); |
1.
...
3 Stored Procedures
Code Block |
---|
String custname = request.getParameter("customerName"); // This should REALLY be validated try { *CallableStatement cs = connection.prepareCall("{call sp_getAccountBalance\(?)}");* cs.setString(1, custname); ResultSet results = cs.executeQuery(); // ... result set handling } catch (SQLException se) |
1.
...
4 Escaping All User Supplied Input
This second technique is to escape user input before putting it in a query. However, this methodology is frail compared to using parameterized queries and we cannot guarantee it will prevent all SQL Injection in all situations. This technique should only be used, with caution, to retrofit legacy code in a cost effective way. Applications built from scratch, or applications requiring low risk tolerance should be built or re-written using parameterized queries.
...
Secure Coding - Encode and Escape
...
https://www.securecoding.cert.org/confluence/display/java/IDS51-J.+Properly+encode+or+escape+output3.1 Use ESAPI database encoders for:
https://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/esapi/codecs/Codec.html
...
3.2 Escaping Dynamic Queries: Turn off character replacement
...
1.3.2.1 Escaping Wildcard characters in Like Clauses
...
...
The LIKE keyword allows for text scanning searches. In Oracle, the underscore '_' character matches only one character, while the ampersand '%' is used to match zero or more occurrences of any characters. These characters must be escaped in LIKE clause criteria. For example:
...
Code Block |
---|
SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/'; SELECT name FROM emp WHERE id LIKE '%%%' ESCAPE '\'; |
...