Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL injections with prepared statements?

If I remember correctly, I think Jeff has mentioned in the Stack Overflow podcast a possible weakness in SQL prepared statements. I'm wondering what kind(s) of weakness(es) did he refer to? Was it possibly just about inappropriate usage thereof, or something more sinister?

The podcast, to my remembering, didn't go deeper into the subject, it was just a pass-by-remark.

like image 879
Henrik Paul Avatar asked Mar 24 '09 17:03

Henrik Paul


People also ask

Is prepared statement Safe?

So using prepared statements is safe from SQL injection, as long as you aren't just doing unsafe things elsewhere (that is constructing SQL statements by string concatenation).

What is prepared statements with parameterized queries?

In database management systems (DBMS), a prepared statement or parameterized statement is a feature used to pre-compile SQL code, separating it from data. Benefits of prepared statements are: efficiency, because they can be used repeatedly without re-compiling. security, by reducing or eliminating SQL injection attacks.

When should prepared statements not be used?

It is easy: If you know the string comes from your application and cannot be manipulated by a user, then there is no need for prepared statements, because there is nothing to inject. If you are not sure (bad, but in greater projects not avoidable) use prepared statement.


2 Answers

I think what he said was that, when you use Prepared Statements, SQL server could cache your query execution plan, so, even if you modify some of the parameters on the executing query, the server could pick the wrong (probably cached) execution plan that would perform very badly.

He also mentioned a new feature of SQL Server 2008 to force the engine to re-evaluate execution plans that he used to overcome this situation.

With Prepared Statements, the only issue I have is this. Consider the following Java Code:

String sql = "select * from table where name like ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "PATTERN%");
ResultSet rs = pstmt.executeQuery();

Here you would expect that, if you have an index on table(name) it will be used by the query plan. Well, it won't. Because PraparedStatement must precompile and expect the worst: '%PATTERN%', for example. So, it won't optimize. It took me a while to figure this one out. It was causing my database to suffer. :(

Hope it helps.

like image 53
Pablo Santa Cruz Avatar answered Oct 21 '22 04:10

Pablo Santa Cruz


Beyond the normal sql injection (what we might call first order) attack there are secondary levels. For example its not uncommon to have stored procedures use string concatenation to build a query which it then executes. If result of retrieved field values are included in such a concatenation then there is a danger of injection.

like image 22
AnthonyWJones Avatar answered Oct 21 '22 06:10

AnthonyWJones