We have inherited an old website with almost 2000 different hand built SQL strings taking the variables directly from httprequests. The site is compromised by SQL injection attack regularly. Obviously this site should have been coded using SQL parameters to avoid this security nightmare, but due to the workload involved changing these we are looking for another way of ‘cleaning’ the incoming requests.
Main Clean Function :-
Public Function myRequest(ByRef Request As HttpRequest, ByVal param As String) As String
Return CleanRequest(Request(param))
End Function
Public Function CleanRequest(ByVal requestString As String) As String
Dim badChars() As String = {"select", "drop", ";", "--", "insert", "delete", "xp_", "update"}
Dim newChars As String = requestString
For i = 0 To UBound(badChars)
newChars = Replace(newChars, badChars(i), "", 1, -1, vbTextCompare)
Next
CleanRequest = Replace(newChars, "'", "''")
End Function
Called as so :-
Dim details As DataSet
detailsSQL = "select * from mytable where tableid = '" & myRequest(Request, "tableid") & "'"
details = sql.sqlSelect(detailsSQL)
Note that the code is structured and named as it is for easy find & replace. With this code in place though the site continues to be regularly compromised. Can anyone recommend additions to the main ‘clean’ function that will help stop these injection attacks?
I think the only reliable way you will prevent SQL Injection would be to put the hard work in and convert all the requests to use SQL Parameters.
However, to answer your question your clean method seems to be missing the fundamental trigger for SQL Injection – unescaped characters. At the moment your site is still susceptible to various types of attacks, for example:
At the very least, make sure you are escaping any bad characters. Be warned though, this isn’t always enough, so I re-iterate if you want to completely eradicate SQL Injection – use SQL Parameters.