EDIT: Have modified it - it was erroneously stripping off single - characters when it should only be wiping --, plus some other regexp tweaks
I've been working on some sites that haven't been properly validating user input and as a result all kinds of nastiness has been going on behind the scenes (e.g. UNION SELECT'ing to pull out admin details). I knocked together a function to sanitise user input and wanted to get some feedback (mainly as my regexp is hazy).
I designed it so that words like "SELECT", "DELETE", etc would be ok to pass so long as they weren't passed in combination with others to make up an SQL command (e.g. SELECT x FROM, DELETE FROM, etc)
If anyone has any optimisations or suggestions for the above I'd be very grateful if they'd share their knowledge 
I've been working on some sites that haven't been properly validating user input and as a result all kinds of nastiness has been going on behind the scenes (e.g. UNION SELECT'ing to pull out admin details). I knocked together a function to sanitise user input and wanted to get some feedback (mainly as my regexp is hazy).
I designed it so that words like "SELECT", "DELETE", etc would be ok to pass so long as they weren't passed in combination with others to make up an SQL command (e.g. SELECT x FROM, DELETE FROM, etc)
Code:
Function SQLSafe(sTxt)
'User input sanitizer to remove risk of SQL injection
'by Darren Coleman ([email protected])
'version 1.03 - 10/09/2008
' 1.00 - Initial release
' 1.01 - Modified regexp to wipe rest of string if SQL command sequence detected
' 1.02 - Modified SQL sequence checks to handle multiple spaces between commands
' 1.03 - Fixed broken "--" detection (was deleting all - characters), tweaked regexp slightly
Dim uberSQLInjExp
Set uberSQLInjExp = New RegExp
'The following regexp will match HTML tags, sequence combinations of
'SQL commands as well as the more obvious control characters & SQL terminators
With uberSQLInjExp
.Pattern = "<[^>]+>|" & _
"SELECT((.|\s)*?)FROM((.|\s)*?)$|" & _
"UPDATE((.|\s)*?)SET((.|\s)*?)$|" & _
"INSERT[\s]+INTO((.|\s)*?)$|" & _
"DELETE[\s]+FROM((.|\s)*?)$|" & _
"(DROP|CREATE|ALTER|TRUNCATE)[\s]+TABLE[\s]+((.|\s)*?)$|" & _
"UNION[\s]+(ALL|SELECT){1}[\s]+((.|\s)*?)$|" & _
"[;|\r?\n|\r|\x00|\x1a]|[-]{2}"
.IgnoreCase = True
.Global = True
End With
SQLSafe = uberSQLInjExp.Replace(sTxt,"")
'Double-quote any single quotes in the text
SQLSafe = Replace(SQLSafe,"'","''")
Set uberSQLInjExp = Nothing
End Function

Last edited: