I’ve had someone point out that using a private method to handle query execution for all queries done by a single class increases the risk of SQL injection attacks.
An example of this method might look like this (below). I have omitted some specifics so as not to distract anyone on implementation.
If you want to talk implementation, please feel free to in the comments. The security review did not comment on the contents of the method, but mainly the fact that it should not be its own method.
Note, queryText is generated from a protected static final string containing SQL text for a prepared statement. The ?’s in the prepared statement text are set using PreparedStatement’s setString (or set whatever) method. The variables that are set on the prepared statement come into the caller method as strongly typed as possible.
queryText is then passed to the private method.
private ResultSet executeQuery(PreparedStatement stmt) throws SQLException {
// Declare result set variable
try{
try{
// execute statement and store in variable
}
catch(SQLException se){
// log, close connection, do any special processing, rethrow se
}
}
finally{
// This finally block is here to ensure the connection closes if
// some special processing (not shown) in the other try generates a runtime exception
// close connection and statement properly
}
// return result set
}
The recommended alternative was to basically inline the same code in each method that does a query.
I did not post this to security.stackexchange.com because I believe it qualifies as a specific security programming problem.
I can think of no reason why duplicating this code (from a private method) into many classes would add any protection. Would it?
Thank you
Having a central (un-duplicated) place for executing queries is a good idea. Both from a code-maintainability and from a security standpoint. Why have code that could have problems multiple times? It only means that you’ll have to maintain it multiple times!
What seems important to me (and which has changed by an edit of the question) is that it should be as hard as possible to execute hand-built SQL Strings with it.
You could, for example, replace any
Stringparameters (which you had initially, but since then replace with aPreparedStatement) with a custom enum:Then you can write your method like this:
This way you can be pretty sure that you (or anyone else on your team) don’t accidentally passes in a self-build
Stringinto your method.If necessary this approach could be extended to handle different parameter types but for many cases using
setObject()works just fine.For increased modularity you could extract an interface from that enum and allow multiple enums to define queries (for example if you have separate modules in your project). But this has the drawback that malicious (or clueless) developers could use dynamic non-enum implementations of
SQLQueryto get their manually-built SQL strings into that method.