Sql injection script - asp-classic

This title of the question may seem to be previously asked and answered but its different scenario for me. I use this script to stop sql injection in my ASP site. As per my knowledge or injecting script i have tried everything . Is it still possible to break through this code or do you feel this is fine .
Here is the script
<%
Function IsInject(strCheck, boolForm)
IsInject = False
If Not boolForm And Len(strCheck) > 50 Then IsInject = True
' Dim sCmdList, arrCmds, i
If boolForm Then
sCmdList = "declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast("
Else
sCmdList = "update,union,select,drop,declare,varchar,convert,delete,create,is_srvrolemember,ar(,cast(,char("
End If
arrCmds = Split(sCmdList, ",")
For i = 0 To UBound(arrCmds)
If Instr(UCase(CStr(strCheck)), UCase(arrCmds(i))) > 0 Then
IsInject = True
Exit For
End If
Next
Erase arrCmds
End Function
Function CleanInject(strClean, boolInt)
If boolInt Then CleanInject = CInt(strClean) Else CleanInject = Replace(strClean, "'", "''")
End Function
'-----------------------------------------------------------
'redirect user if specific IP
'Dim ipaddress, bFBIRedirect, sInjectType
bFBIRedirect = True
ipaddress = Request.ServerVariables("REMOTE_ADDR")
Select Case ipaddress
Case "90.120.206.10"
Case Else
bFBIRedirect = False
End Select
If bFBIRedirect Then Response.Redirect "http://www.fbi.gov"
'-----------------------------------------------------------
'Dim bIsInject, sHackString
bIsInject = False
If Not bInject Then
' Dim qsItm
For Each qsItm In Request.QueryString
If IsInject(Request.QueryString(qsItm), False) Then
bIsInject = True
sHackString = qsItm & "=" & Request.QueryString(qsItm)
sHackType = "QueryString"
sInjectType = "qs-" & Request.QueryString(qsItm)
Exit For
End If
Next
End If
If Not bInject Then
' Dim frmItm
' For Each frmItm In Request.Form
' If IsInject(Request.Form(frmItm), True) Then
' bIsInject = True
' sHackString = Request.Form(frmItm)
' sHackString = frmItm & "=" & Request.Form(frmItm)
' sHackType = "Form"
' Exit For
' End If
' Next
End If
If bIsInject Then
Session("hacktype") = sHackType
Session("hackstr") = sHackString
Session("thepagefrom") = Request.ServerVariables("PATH_INFO")
Session("theip") = Request.ServerVariables("REMOTE_ADDR")
' Dim arrWhereAt, iWhereAt, sRedirect
arrWhereAt = Split(Request.ServerVariables("PATH_INFO"), "/")
iWhereAt = UBound(arrWhereAt)
sRedirect = "unknownerror.asp?ip=" & Request.ServerVariables("REMOTE_ADDR") & "&err=" & sInjectType & "&pg=" & Request.ServerVariables("PATH_INFO")
If iWhereAt = 1 Then sRedirect = "../" & sRedirect
If iWhereAt = 2 Then sRedirect = "../../" & sRedirect
If iWhereAt = 3 Then sRedirect = "../../../" & sRedirect
Response.Redirect sRedirect
End If
%>

Using blacklists to remove commands is not really a good idea. You have to make sure you cover all possible commands, and still someone might sneak something past. This would also probably fail if you get data from a user that is not an attack, but still contains an attack string. Example "Back in the days of the Soviet Union".
As Nikolai suggests, see if you can find some type of prepared statements to use. Or find a really good library to properly escape data for you.

rather doing that I think I would use ADO Parameter object when creating SQL queries, the second best thing is to do type conversion of the inputfields for the dynamic SQL queries, such as converting strings to SQL strings (replace any ' with two ''), making sure number is a number etc.

Related

Invalid procedure call or argument: 'Mid'

I have a function (see below) and it works perfectly. I recently moved my code to another server and i did not change anything in it. It fails to run on new server.
Microsoft VBScript runtime error '800a0005'
Invalid procedure call or argument: 'Mid'
/calculate.asp, line 416
When i checked the line 416, i got this:
Dim result3: result3 = Mid(o3.responseText, Basla3, Bitir3)
and this is the complete function:
<%
Function xyz()
Dim o3: Set o3 = Server.CreateObject("MSXML2.ServerXMLHTTP")
Dim o_date3: o_date3 = split(EndingDate, ".")
Dim s_date3
If (Len(o_date3(2)) = 4) Then
s_date3 = o_date3(2)
Else
s_date3 = "20" & o_date3(2)
End If
If (Len(o_date3(1)) = 2) Then
s_date3 = s_date3 & o_date3(1)
Else
s_date3 = s_date3 & "0" & o_date3(1)
End If
If (Len(o_date3(0)) = 2) Then
s_date3 = s_date3 & o_date3(0)
Else
s_date3 = s_date3 & "0" & o_date3(0)
End If
Dim s3: s3 = "<soapenv:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:urn=""urn:AntTransferWSIntf-IAntTransferWS""><soapenv:Header/><soapenv:Body><urn:EURCurrency soapenv:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><DateStr xsi:type=""xsd:string"">" + s_date3 + "</DateStr></urn:EURCurrency></soapenv:Body></soapenv:Envelope>"
o3.Open "POST", serviceUrl, False
o3.setRequestHeader "Content-Type", "text/xml"
o3.setRequestHeader "Connection", "close"
o3.setRequestHeader "SOAPAction", " "
o3.send s3
Dim hataVarMiBasla3: hataVarMiBasla3 = (InStr(1, o3.responseText, "<faultstring>", vbTextCompare)) + 13
If (hataVarMiBasla3 > 13) Then
Dim hataVarMiBitir3: hataVarMiBitir3 = (InStr(1, o3.responseText, "</faultstring>", vbTextCompare)) - hataVarMiBasla3
Dim hata3: hata3 = Mid(o3.responseText, hataVarMiBasla3, hataVarMiBitir3)
KurGetir = hata3
Else
Dim Basla3: Basla3 = (InStr(1, o3.responseText, """xsd:double"">", vbTextCompare)) + 13
Dim Bitir3: Bitir3 = (InStr(1, o3.responseText, "</return>", vbTextCompare)) - Basla3
Dim result3: result3 = Mid(o3.responseText, Basla3, Bitir3)
xyz = CDbl(Replace(result3, ".", mstrComma))
End If
Set o3 = Nothing
End Function
%>
Why am i receiving this error?
Mid struct from MSDN
Mid(string, start[, length])
Not official reference but according to my experience, you get that error if
start is less than or equal to zero.
length is less than zero (if it is not missed in the Mid call)
Have a look at the error line and related ones.
Dim Basla3: Basla3 = (InStr(1, o3.responseText, """xsd:double"">", vbTextCompare)) + 13
Dim Bitir3: Bitir3 = (InStr(1, o3.responseText, "</return>", vbTextCompare)) - Basla3
Dim result3: result3 = Mid(o3.responseText, Basla3, Bitir3)
Lets suppose o3.responseText is empty because your code does not check whether the response is empty.
Basla3 can not be less than 13 according to InStr() + 13, so it's not the problem.
However it seems like Bitir3 can be less then zero according to InStr() - Basla3 (Basla3 evaluated as 13).
Continuing with the assumption, (InStr(1, o3.responseText, "</return>", vbTextCompare)) evaluated as 0, then with - Basla3 it will be evaluated as -13. Tada! rule 2 violated, length cannot be less than zero.
The problem with your code is, there is no check response length nor response status.
If the response is empty, consider the following:
Your new server may have connectivity problems unlike the old one.
The API which you have is authorized for the old server's IP address only.
In a nutshell, you should optimize the code and be sure that there is an xml response.
At least use something like that:
o3.Send
If o3.readyState = 4 And o3.status = 200 Then
If Len(o3.responseText) > 0 Then
'response is ready to parse
Else
'response status is ok but empty
End If
Else
'request failed
End If
BTW, due to your request is a soap call, I'd highly recommend done the job by parsing xml response using DomDocument etc.
Replacing decimal points, using Mid & InStr pair to check node existence are just trouble and bad practice also.
If I were to take a guess.
VBScript gives strange errors when your "MID" function has to deal with special characters, or what it thinks are non-string values.
So, o3.responseText probably contains text that it doesn't like.

asp classic : checking values in an array

I am making a simple questionnaire for a client in Classic ASP.
The idea is that there will be 10 questions. The user registers and is being sent to the first question. When this is answered they move on to the 2nd question etc.
Questions can be skipped and returned to at a later date, and each question can only be answered once.
I have a comma separated list in the database of each question a user has answered.
So, a user logs in and an array is created with the list of answered questions.
What would be the best way to loop through this list and go to the first unanswered question?
An example of the array of answered questions would look something like this "1,4,6"
so this user would have answered questions number 1, 4 and 6. When a user logs in I'd like to direct them to the first unanswered question, in this case 2. Once the second question is answered the user would be redirected to the next unanswered question.
Any suggestions please?
#Dog, I think this offers the functionality you are looking for.
Tip: See this answer for information on downloading Microsoft's authoritative WSH reference as a Windows help file.
Option Explicit
Dim oQsm : Set oQsm = New QuestionStatusManager
With oQsm
.NumberOfQuestions = 10
.RestoreStatus("1,4,6")
.MarkQuestionAnswered(2)
WScript.Echo "Questions " & .ToString() & " have been answered."
WScript.Echo "Next unanswered question is: " & .GetNextUnansweredQuestion()
End With
Set oQsm = Nothing
' ------------------------------------------------------------------------
Class QuestionStatusManager
Private m_nNumberOfQuestions
Private m_aQuestionList()
Sub Class_Initialize()
m_nNumberOfQuestions = -1
End Sub
Sub Class_Terminate()
Erase m_aQuestionList
End Sub
Public Property Let NumberOfQuestions(n)
Dim bValid : bValid = False
If IsNumeric(n) Then
If n = CInt(n) Then
bValid = True
End If
End If
If Not bValid Then
Err.Raise vbObjectError + 1, "", _
"Value '" & n & "' is not an integer."
End If
m_nNumberOfQuestions = CInt(n)
ReDim m_aQuestionList(n)
End Property
Public Property Get NumberOfQuestions()
CheckState
NumberOfQuestions = m_nNumberOfQuestions
End Property
Private Sub CheckState()
If m_nNumberOfQuestions = -1 Then
Err.Raise vbObjectError + 1, "", _
"Property 'NumberOfQuestions' has not been set."
End If
End Sub
Sub RestoreStatus(sAlreadyAnswered)
CheckState
Dim aAlreadyAnswered : aAlreadyAnswered = Split(sAlreadyAnswered, ",")
Dim i
For i = 0 To UBound(m_aQuestionList)
m_aQuestionList(i) = False
Next
For i = 0 To UBound(aAlreadyAnswered)
m_aQuestionList(CInt(aAlreadyAnswered(i))) = True
Next
End Sub
Sub MarkQuestionAnswered(n)
Dim sDesc
CheckState
On Error Resume Next
m_aQuestionList(n) = True
If Err Or n = 0 Then
sDesc = Err.Description
On Error GoTo 0
Err.Raise vbObjectError + 1, "", _
"Can't mark question number '" & n & "' as answered: " & sDesc
End If
End Sub
Function GetNextUnansweredQuestion()
CheckState
Dim i
For i = 1 To UBound(m_aQuestionList)
If Not m_aQuestionList(i) Then
GetNextUnansweredQuestion = i
Exit Function
End If
Next
GetNextUnansweredQuestion = -1
End Function
Function ToString()
CheckState
Dim sDelim : sDelim = ""
Dim i
ToString = ""
For i = 1 To UBound(m_aQuestionList)
If m_aQuestionList(i) Then
ToString = ToString & sDelim & CStr(i)
sDelim = ","
End If
Next
End Function
End Class

Microsoft VBScript runtime error '800a0009'

I recently inherited a website in ASP, which I am not familiar with. Yesterday, one of the pages began to throw an error:
Microsoft VBScript runtime error '800a0009'
Subscript out of range: 'i'
default.asp, line 19
Here is the code from lines 13-27:
<%
set rs = Server.CreateObject("ADODB.Recordset")
rs.open "SELECT * FROM VENDORS_LIST_TBL WHERE inStr('"& dVendorStr &"','|'&ID&'|')", Cn
DIM dTitle(100), dDescription(100), dLink(100)
i = 0 : Do while NOT rs.EOF : i = i + 1
dTitle(i) = rs.fields.item("dTitle").value
dDescription(i) = rs.fields.item("dDescription").value
dLink(i) = rs.fields.item("dLink").value : if dLink(i) <> "" then dTitle(i) = "" & dTitle(i) & ""
if NOT rs.EOF then rs.movenext
Loop
x = i
rs.Close : Set rs = Nothing
%>
Any ideas on what's going on here and how I can fix it?
Thank you!
You've declared dTitle, dDescription and dLink as Arrays with a size of 100. As you are walking through the recordset, you are assigning elements to those arrays. It would appear that you have more than 100 records in your recordset, so the logic is trying to do something like:
dTitle(101) = rs.fields.item("dTitle").value
This will throw an error because your array isn't big enough to hold all of your data.
The "solution" you chose is not very good. What if within 2 years there will be more than 500? You will forget all about this and waste hours yet again.
Instead of fixed size arrays you can just use dynamic arrays:
DIM dTitle(), dDescription(), dLink()
ReDim dTitle(0)
ReDim dDescription(0)
ReDim dLink(0)
i = 0
Do while NOT rs.EOF
i = i + 1
ReDim Preserve dTitle(i)
ReDim Preserve dDescription(i)
ReDim Preserve dLink(i)
dTitle(i) = rs.fields.item("dTitle").value
dDescription(i) = rs.fields.item("dDescription").value
dLink(i) = rs.fields.item("dLink").value
If (Not(IsNull(dLink(i)))) And (dLink(i) <> "") Then
dTitle(i) = "" & dTitle(i) & ""
End If
rs.movenext
Loop
This will start with one (empty) item in each array - for some reason the code seems to need this - then on each iteration one more item will be added, preserving the others.
Note that I've also fixed small issue that might have caused trouble - in case of NULL value in "dLink" field, you would get blank anchors in your HTML because NULL is not empty string in VBScript.
This how GetRows can be used to achieve the same goal.
<%
Function VendorSearch(sVendor)
Dim cn: Set cn = SomeLibraryFunctionThatOpensAConnection()
Dim cmd: Set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT dTitle, dDescription, dLink FROM VENDORS_LIST_TBL WHERE inStr(?,'|'&ID&'|')"
cmd.Parameters.Append cmd.CreateParameter("Vendor", adVarChar, adParamInput, Len(sVendor), sVendor)
Set cmd.ActiveConnection = cn
Dim rs : Set rs = cmd.Execute()
VendorSearch = rs.GetRows()
rs.Close()
cn.Close()
End Function
Dim arrVendor : arrVendor = VendorSearch(dVendorStr)
Const cTitle = 0, cDesc = 1, cLink = 2
Dim i
For i = 0 To UBound(arrVendor, 2)
If IsNull(arrVendor(cLink, i) Or arrVendor(cLink, i) = "" Then
arrVendor(cTitle, i) = "" & arr(cTitle, i) & ""
End If
Next
%>
Notes:
The Select statement contains only those fields required in the results, the use of * should be avoided
A parameterised command is used to avoid SQL Injection threat from SQL contactenation.
Constants used for field indices into the resulting 2 dimensional array.
Whilst this code replicates the original munging of the title value this is here as an example only. In reality construction of HTML should be left as late as possible and outputing of all such strings as title and description should be passed through Server.HTMLEncode before sending to the response.

ASP grab two parameters from referral url

Hi I am using a code to get the referral URL as you can see below:
sRef = encode(Request.ServerVariables("HTTP_REFERER"))
The code above is getting the following URL:
http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545
From that url I want to grab ONLY the ADV and LOC (Request.querystring doesnt work because this is a script which is run when the form is submitted)
So to cut the story short, by using the referral URL, i want to get out the values for the adv and loc parameters.
Any help please on how I can do this?
Below is the code I am currently using but I have a problem. The parameters which are after the loc, is showing as well. I want something dynamic. Also the values of the adv and loc can be longer.
<%
sRef = Request.ServerVariables("HTTP_REFERER")
a=instr(sRef, "adv")+4
b=instr(sRef, "&loc")
response.write(mid(sRef ,a,b-a))
response.write("<br>")
response.write(mid(sRef ,b+5))
%>
Here is something to get you started; it uses regular expressions to get all URL variables for you. You can use the split() function to split them on the "=" sign and get a simple array, or put them in a dictionary or whatever.
Dim fieldcontent : fieldcontent = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
Dim regEx, Matches, Item
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = True
regEx.MultiLine = False
regEx.Pattern = "(\?|&)([a-zA-Z0-9]+)=([^&])"
Set Matches = regEx.Execute(fieldcontent)
For Each Item in Matches
response.write(Item.Value & "<br/>")
Next
Set regEx = Nothing
substring everything after the ?.
Split on "&"
Iterate the array to find "adv=" and "loc="
Below is the code:
Dim fieldcontent
fieldcontent = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
fieldcontent = mid(fieldcontent,instr(fieldcontent,"?")+1)
Dim params
params = Split(fieldcontent,"&")
for i = 0 to ubound(params) + 1
if instr(params(i),"adv=")>0 then
advvalue = mid(params(i),len("adv=")+1)
end if
if instr(params(i),"loc=")>0 then
locvalue = mid(params(i),5)
end if
next
You can use the following generic function:
function getQueryStringValueFromUrl(url, key)
dim queryString, queryArray, i, value
' check if a querystring is present
if not inStr(url, "?") > 0 then
getQueryStringValueFromUrl = empty
end if
' extract the querystring part from the url
queryString = mid(url, inStr(url, "?") + 1)
' split the querystring into key/value pairs
queryArray = split(queryString, "&")
' see if the key is present in the pairs
for i = 0 to uBound(queryArray)
if inStr(queryArray(i), key) = 1 then
value = mid(queryArray(i), len(key) + 2)
end if
next
' return the value or empty if not found
getQueryStringValueFromUrl = value
end function
In your case:
dim url
url = "http://www.rzammit.com/pages/linux-form.asp?adv=101&loc=349&websync=233344-4555665-454&ptu=454545"
response.write "ADV = " & getQueryStringValueFromUrl(url, "adv") & "<br />"
response.write "LOC = " & getQueryStringValueFromUrl(url, "loc")

ASP.Net String Split not working

Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.

Resources