<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jephens Tech. &#187; t-sql</title>
	<atom:link href="http://www.jephens.com/tag/t-sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jephens.com</link>
	<description>Keeping Computers Happy Since 1997</description>
	<lastBuildDate>Tue, 22 Nov 2011 04:33:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Cleaning Up After a SQL Injection Attack, Part 2</title>
		<link>http://www.jephens.com/2009/12/27/cleaning-up-after-a-sql-injection-attack-part-2/</link>
		<comments>http://www.jephens.com/2009/12/27/cleaning-up-after-a-sql-injection-attack-part-2/#comments</comments>
		<pubDate>Sun, 27 Dec 2009 04:59:07 +0000</pubDate>
		<dc:creator>Jeff Knapp</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[malware]]></category>
		<category><![CDATA[sql injection]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[t-sql]]></category>

		<guid isPermaLink="false">http://www.jephens.com/?p=268</guid>
		<description><![CDATA[Got a call today off our previous article in this series from Branden of Hot Media Group, Inc., aChicago-based web application development, networking, and graphic design firm who found himself with a database full of malware infections, but the characteristics of his attack didn't match what we had written about, so he called us up. [...]]]></description>
			<content:encoded><![CDATA[<p>Got a call today off our <a href="/2008/07/27/how-to-clean-up-after-a-sql-injection-attack">previous article in this series</a> from Branden of<a href="http://www.hotmediagroup.com/" target="_blank"> Hot Media Group, Inc</a>., aChicago-based web application development, networking, and graphic design firm who found himself with a database full of malware infections, but the characteristics of his attack didn't match what we had written about, so he called us up. We reviewed his symptoms and were able to tweak the code we provided previously to work with this new set of issues.</p>
<p>We weren't able to see how the site was attacked, nor did we worry about how the site would be steeled against future occurrence (<a href="http://msmvps.com/blogs/harrywaldron/archive/2008/05/31/microsoft-best-practices-for-preventing-sql-injection-attacks.aspx" target="_blank">always use stored procedures and/or parametrized queries, kids</a>!) -- this was purely a cleanup job.</p>
<p>This is the code we had:</p>
<pre class="code prettyprint" style="height: 20em;">DECLARE @T VARCHAR(255),@C VARCHAR(255)
DECLARE Table_Cursor CURSOR FOR
SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND (b.xtype=35 OR b.xtype=231 OR b.xtype=167)
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT ('UPDATE ['+@T+'] SET ['+@C+']=REPLACE(['+@C+'],''<script src="hxxp://evilsite.evl/b.js"><!--mce:0--></script>'', '''')') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor DECLARE Table_Cursor CURSOR FOR SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND b.xtype=99 OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN PRINT ('UPDATE ['+@T+'] SET ['+@C+']=cast(replace(cast(['+@C+'] as nvarchar(4000)),''<script src="hxxp://evilsite.evl/b.js"><!--mce:1--></script>'','''') as ntext)')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor</pre>
<p>And that worked fine, but it had some shortcomings -- mostly it only stripped out a single bit of invasive code, and our new friend had quite a bit of code to deal with, so instead of the almost quaint looking malware code:</p>
<pre class="code prettyprint" style="height: 3em;">&lt;script src="hxxp://evilsite.evl/b.js"&gt;&lt;/script&gt;</pre>
<p>We had this jumble of code in every ntext field in his database:</p>
<pre class="code prettyprint" style="height: 20em;">&lt;script type='text/javascript' src='http://google-anallytics.bad/urchin.js'&gt;&lt;/script&gt;
&lt;div style='display:none;'&gt;&lt;a href='http://tests4all.bad/1/'&gt;journals on losing post-pregnancy weight&lt;/a&gt;
&lt;a href='http://tests4all.bad/2/'&gt;personal trainer certification atlanta&lt;/a&gt;
&lt;a href='http://tests4all.bad/3/'&gt;quit smoking water vapor rings&lt;/a&gt;
&lt;a href='http://tests4all.bad/4/'&gt;eyes in the darkness&lt;/a&gt;
&lt;a href='http://tests4all.bad/5/'&gt;cheated map on dota 6.54b&lt;/a&gt;
&lt;a href='http://tests4all.bad/6/'&gt;occupations for bored teen boys&lt;/a&gt;
&lt;a href='http://tests4all.bad/7/'&gt;cgw southeast partners ilp&lt;/a&gt;
&lt;a href='http://tests4all.bad/8/'&gt;does iq tests accurately measure intelligence&lt;/a&gt;
&lt;a href='http://tests4all.bad/9/'&gt;free total psychic reading&lt;/a&gt;
&lt;a href='http://tests4all.bad/10/'&gt;minnesota past life regression&lt;/a&gt;
&lt;a href='http://tests4all.bad/11/'&gt;date of abraham lincolns death&lt;/a&gt;</pre>
<p>After trying to figure out the best way to escape all the single quotes, Branden -- an accomplished ColdFusion developer -- suggests "why don't we just drop everything to the right of the &lt;script&gt; tag?"<br />
<span id="more-268"></span><br />
Sounded like a great idea and worked very well. Since his infection had only affected NTEXT fields, we focused on cleaning them up, as well as making the script as easy to manage as possible. So I rewrote it to make it more friendly to the end-user,</p>
<pre class="code prettyprint" style="height: 25em;">DECLARE @T VARCHAR(255),@C VARCHAR(255), @sql varchar(2000)
DECLARE @ObjectionableText varchar(1000)
Set @ObjectionableText = '&lt;script type=''''text/javascript'''' src=''''http://google-anally' -- make sure your single quotes are escaped with another single quote
DECLARE Table_Cursor CURSOR FOR
SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND b.xtype=99
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0)
BEGIN
set @sql = ('UPDATE ['+@T+'] SET ['+@C+']= left(cast(' +@C+ ' as varchar(8000)), charindex('''+@ObjectionableText+''', cast(' +@C+ ' as varchar(8000)))-1) where '+@C+ ' like <a href="mailto:''%'+@ObjectionableText+'%'''">''%'+@ObjectionableText+'%'''</a>)
print @sql
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor</pre>
<p>So, let's take this apart real quick...</p>
<p>We declare some variables:</p>
<pre class="code prettyprint">DECLARE @T VARCHAR(255),@C VARCHAR(255), @sql varchar(2000)
DECLARE @ObjectionableText varchar(1000)</pre>
<p>Now, this next line is the <strong>important</strong> one -- this is where we tell the script where we want to kill from. In our example above, we could have used <strong>&lt;script</strong> as a starting tag, but the client was afraid some of the data might have legitimate &lt;script&gt; tags in the data, so we needed to get a little more specific; this string appeared in the data: "<strong>&lt;script type='text/javascript' src='http://google-anally...</strong>" so we decided to use that. However, you might notice that there were SINGLE QUOTES in the string. Since SQL Server uses a single quote as a string delimiter, we need to make sure we use FOUR single quotes in the next line everytime there's a single quote:</p>
<pre class="code prettyprint">Set @ObjectionableText = '&lt;script type=''''text/javascript'''' src=''''http://google-anally' -- make sure your single quotes are escaped with another single quote</pre>
<p>We use <strong>FOUR</strong> single quotes because this script will generate a binch of UPDATE statements for you, and the UPDATE statements need to have THEIR single-quotes escaped, so we need to tell our variable to output <strong>TWO</strong> single quotes, which means using <strong>FOUR</strong> single quotes in the variable. (Our escape uses 2 quotes and the escape later uses 2 quotes, so that equals 4.)</p>
<p>(Don't follow? Doesn't matter. Trust me. In your ObjectionableText, use FOUR single quotes where you see ONE.)</p>
<p>Now, like the old code, we set the cursor up as before; and since we only need NTEXT fields, we're only looking for columns where xtype = 99:</p>
<pre class="code prettyprint">DECLARE Table_Cursor CURSOR FOR
SELECT a.name,b.name FROM sysobjects a,syscolumns b WHERE a.id=b.id AND a.xtype='u' AND b.xtype=99
OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
WHILE(@@FETCH_STATUS=0)
BEGIN</pre>
<p>But now, we have to change the SQL statement we want to use to (a) keep 8k worth of ntext -- if you think you have more than 8K, change the number accordingly in SQL2005+, SQL2000 has an varchar limit of 8K for a varchar field... so we UPDATE the field to a new value, computed by doing a simple <a href="http://msdn.microsoft.com/en-us/library/ms177601.aspx" target="_blank">LEFT</a> and using the <a href="http://msdn.microsoft.com/en-us/library/ms186323.aspx" target="_blank">CHARINDEX</a> of the text we shoved in the @ObjectionableText variable (minus 1) to come up with it. To make sure we don't pass an invalid value to CHARINDEX we need to make sure the rows we're working on actually have the polluted text -- and that's where the <a href="http://msdn.microsoft.com/en-us/library/ms179859.aspx" target="_blank">LIKE</a> at the end comes in.</p>
<pre class="code prettyprint">set @sql = ('UPDATE ['+@T+'] SET ['+@C+']= left(cast(' +@C+ ' as varchar(8000)), charindex('''+@ObjectionableText+''', cast(' +@C+ ' as varchar(8000)))-1) where '+@C+ ' like<a href="mailto:''%'+@ObjectionableText+'%'''">''%'+@ObjectionableText+'%'''</a>)</pre>
<p>NOTE: Bear in mind we're doing a TABLE SCAN on this table since we're doing a mid-string lookup, so performance may be bad. It beats going thru everything by hand, but if you have a large table (10,000+ rows) it might take some time.</p>
<p>Now, I print the SQL statement. I could execute the statement (EXEC @sql) instead, but since I don't want you cutting-and-pasting this code without knowing what it has the potential to do, I will go for the more benign PRINT and let you either change it to EXEC or cut and paste the resulting SQL statements into a new Query Analyzer/Management Studio window..</p>
<pre class="code prettyprint">print @sql</pre>
<p>And then we loop thru the rest of the cursor and cleanup after ourselves:</p>
<pre class="code prettyprint">FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor</pre>
<p>That's it. Copy and paste the above code into Query Analyzer or SQL Server Management Studio and run it; you'll get a list of SQL statements back which look like this:</p>
<pre class="code prettyprint" style="height: 6em;">UPDATE [Banners] SET [AdCode]= left(cast(AdCode as varchar(8000)), charindex('&lt;script type=''text/javascript'' src=''http://google-anally', cast(AdCode as varchar(8000)))-1) where AdCode like '%&lt;script type=''text/javascript'' src=''http://google-anally%'
UPDATE [Banners] SET [AdCodeNetscape]= left(cast(AdCodeNetscape as varchar(8000)), charindex('&lt;script type=''text/javascript'' src=''http://google-anally', cast(AdCodeNetscape as varchar(8000)))-1) where AdCodeNetscape like '%&lt;script type=''text/javascript'' src=''http://google-anally%'</pre>
<p>Paste them into a new QA/SSMS window and run them, and your data should then be clean.</p>
<p><strong>REMINDER! In this case, we assume the malicious code was merely appended to the end of the NTEXT fields, not that fields were truncated and appended to like in the last article. If that's the case, data loss may still be possible in that the injection attack might have caused data fields to be truncated.</strong></p>
<p>Thanks to Branden for trusting us with his data, and if you're in the market for</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jephens.com/2009/12/27/cleaning-up-after-a-sql-injection-attack-part-2/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

