0

We have some classic ASP pages that connect to a MS SQL server database. To prevent SQL injection, we just replace all single quotes with a double single quote. This seems to be the method prescribed here: https://web.archive.org/web/20211020150656/https://www.4guysfromrolla.com/webtech/061902-1.shtml

This still feels dangerous to me. Is there any way to escape the single quote with any other character, potentially opening up the SQL Injection?

EDIT:) We currently have a lot of old code that uses this single quote to double single quote replacement. If that is sufficient to prevent SQL injection, then we won't change anything. My real question is if this method insecure.

Jeffrey
  • 1,837
  • 5
  • 25
  • 40
  • possible duplicate of [Classic ASP SQL Injection Protection](http://stackoverflow.com/questions/149848/classic-asp-sql-injection-protection) – RichardTheKiwi Sep 28 '12 at 21:46

1 Answers1

8

Use a parameterized query. If you don't use concatenation to glom your SQL statements together, the single quotes are taken care of for you. Example:

Set objCommand = CreateObject("ADODB.Command")
With objCommand
.CommandText = "INSERT dbo.Table(Column) values (?)"
.CommandType = adCmdText
.ActiveConnection = "Connection string" or existing open connection
.Parameters.Append .CreateParameter("@p1", adVarChar, adParamInput, 50, "O'Brien")
.Execute
Set .ActiveConnection = Nothing
End With

The method you're currently relying on is not secure. Let's say you have the following dynamic SQL embedded in your ASP page:

sql = "SELECT Name FROM dbo.Students WHERE Id = " & Request("StudentId") 

Now let's say someone decided to try to jam the following into the querystring (or form, or what have you):

1; DROP TABLE dbo.Students;

How does replacing this string with single quotes help you avoid SQL injection? In cases where you know, you could potentially do:

sql = "SELECT Name FROM dbo.Students WHERE Id = " & CLng(Request("StudentId"))

So now you have to go in and re-write this code anyway, and find cases where the data type that is opening you up to injection isn't a string.

SQL injection is not defined solely by exploiting single quotes. There are probably a dozen other ways to do this depending on how you are constructing your SQL strings. If you want to feel safe by just protecting those cases, that's up to you. I wouldn't. I would properly parameterize all queries with type safety. Eliminates all the issues and you will sleep better at night even though the up-front cost may be large.

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
  • This is definitely the way I would write it today. However, I just really need to know if the way we have things currently is a security concern. – Jeffrey Sep 26 '12 at 15:24
  • @Jeffrey related: http://stackoverflow.com/questions/149848/classic-asp-sql-injection-protection http://blog.securestate.com/post/2008/09/30/Classic-ASP-SQL-Injection-Prevention.aspx – Aaron Bertrand Sep 26 '12 at 15:26