Can I avoid all SQL-injection attacks by using parameters?
And don't worry about any thing in SQL injection in this case?
Or are there some types of these attacks which require more care on the part of the programmer?
views:
187answers:
6No, you can't avoid all SQL injection attacks by using parameters. Dynamic SQL is the real issue, and this can occur in stored procedures as well as in your application code.
E.g., this is prone to a SQL injection attack: your parameterized query passes a username to a stored procedure, and within the stored procedure the parameter is concatenated to a SQL command and then executed.
For an example of many kinds of SQL injection attacks, see this SQL Injection Cheat Sheet. You will see that simply escaping single quotes is just scratching the surface, and that there are many ways around that.
If you are going to build a dynamic sql query with those parameters (passed to a stored procedure, for example) then there's a chance of sql injection if precautions are not taken.
Yes and no. Yes, if all of your SQL statements are indeed static and use only parameters, then you're 100% protected from SQL injection attacks.
The problem comes when the parameters themselves are used to construct dynamic SQL statements. An example would be a stored procedure that generates a SQL statement dynamically for querying a multitude of different options, where a single monolithic statement would be impractical. While there are better solutions to this problem, this is a common one.
You can always minimize the risk of SQL injection by using prepared statements, provided your database engine supports them.
Anyway, prepared statements is probably the most secure way of blocking SQL injections.
Yes you can avoid all SQL-injection attacks by using parameters, as long as you use parameters exclusively all the way down the call stack. For example:
- Your app code calls a stored procedure or dynamic SQL in the database. That must use parameters to pass all values.
- The stored procedure or dynamic SQL internally constructs a call to another stored procedure or dynamic SQL statement. That must also use parameters to pass all values.
- Repeat ad-infinitum until you run out of code.
If you are programming in SQL Server, you can use sp_executesql
to execute dynamic SQL, and it will let you define and pass parameterised values to the statement being executed.
The problem is building the SQL statement dynamically.
For example, you might want to order the result based on the column the user selected. In most databases, you can't use parameters here ("ORDER BY ?" doesn't work). So you have to "ORDER BY " + column. Now, if "column" is a String, then the user of your web-application could inject code there (which is not easy, but possible).