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: http://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.

4

1 回答 1

8

使用参数化查询。如果您不使用连接来将您的 SQL 语句组合在一起,那么单引号会为您处理好。例子:

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

您当前使用的方法不安全。假设您在 ASP 页面中嵌入了以下动态 SQL:

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

现在假设有人决定尝试将以下内容塞入查询字符串(或表单,或者你有什么):

1; DROP TABLE dbo.Students;

用单引号替换此字符串如何帮助您避免 SQL 注入?在您知道的情况下,您可能会这样做:

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

所以现在你无论如何都必须重新编写这段代码,并找出导致你被注入的数据类型不是字符串的情况。

SQL 注入并不是仅仅通过利用单引号来定义的。根据您构建 SQL 字符串的方式,可能还有十几种其他方法可以做到这一点。如果您只想通过保护这些情况来感到安全,那取决于您。我不会。我会用类型安全正确地参数化所有查询。消除所有问题,即使前期成本可能很大,您也会在晚上睡得更好。

于 2012-09-26T15:17:47.630 回答