After reading a great article about SQL Injections I set off to create the definitive solution for this old (and often undermined) security issue.
I believe the following ASP functions will stop all known types of SQL Injections, but I cannot guarantee they will work for your system so USE THIS CODE AT YOUR OWN RISK.
1. Safe SQL String
This function will protect against SQL Injections on string fields. Namely, any of following:
' or 1=1--
" or 1=1--
or 1=1--
' or 'a'='a
" or "a"="a
') or ('a'='a
' This function encrypts all characters known to be used in a SQL Injection
Function SQLSafeString(ByVal s)
' Declarations
Dim bad, x, y
bad = Array( _
"select", "drop", "insert", "delete", "update", "xp_", _
"--", "..", "{", "}", "[", "]", "<", ">", _
"(", ")", "#", "%", "*", "&", "+", "'", "`", """", _
"/", "\", ":", ";", "=", "?", "|", "$", "!", "^" _
)
' First we mark the bad characters
For Each x In bad
If InStr(1, s, x) Then
s = Replace(s, x, "_C1_" & ASC(Left(x,1)) & "_C2_" & Mid(x,2))
End If
Next
' Then we add the code to
s = Replace(s, "_C1_", "'+CHAR(")
s = Replace(s, "_C2_", ")+'")
' Return safe string
SQLSafeString = s
End Function
2. SQL Safe Number
This will protect you against attacks like these:
0 or 1=1--
0; drop/select/update/insert ... --
' This function will return a number or 0. No text/symbols allowed at all.
Function SQLSafeNumber(ByVal n)
' Trap errors
Err.Clear() : On Error Resume Next
' Try to create a number
n = CDbl(n)
' If error (ie.: has text or bad symbols)
If Err.Number<>0 Then n = 0 : Err.Clear()
' Return safe number
SQLSafeNumber = n
End Function
0 comments:
Post a Comment