2006-04-13 - SQL Injection
2006-04-13 - SQL Injection
Michael Anderson
Enterprise Architecture Services
April 2006
SQL Injection - Introduction
Assume an application (web or even just a client/server app) prompts for a user
input value (we'll use name)
As part of the application, a SQL string is constructed similar to the following:
String sql = “select * from Products where ProductName = '” + name + “'”
Think about what happens if someone enters the following as the value for name:
John
A' or 1=1--
The results of the last input would be the following query passed into the database:
select * from Products where ProductName = 'A' or 1=1--'
This would result in all values being returned from Products, obviously not what we
want!
What about the following values for name:
A'; delete from Products;--
A'; drop table Products;--
A'; exec master..xp_cmdshell 'dir';--
The “attacker” does not even need to know the structure of the database prior,
almost all of this can be discovered with simple techniques (assuming that database
errors are returned to the user)
Having can be used to determine the columns (and thus tables) being
used
Sum can be used to determine field types
Things like @@version can provide system information
For anyone thinking single quotes are the problem, think again! What about the
following query (where id is numeric):
String sql = “select * from Products where ProductId = ” + id
The same attack still works with any of the following:
5 or 1=1--
5; delete from Products;--
5; drop table Products;--
5; exec master..xp_cmdshell 'dir';--
If proper application programming techniques are used, the call would look more like
the following:
CallableStatement cs = connection.prepareCall(“{call sp_getProductById(?)}”);
cs.setString(1, id);
cs.execute();
By using better application programming techniques, combined with better database
programming techniques, we've solved the problem! Haven't we?
It is already good practice to utilize dynamic SQL sparingly, this is for both security
concerns, and for performance (i.e. caching)
What happens if the Stored Procedure is itself utilizing dynamic SQL?
A good example of this is the stored procedure being evaluated for
returning a dynamic result set of translated labels
Moving the problem to within the stored procedure does not remove the problem!
Without eliminating all use of dynamic SQL, we are still at risk