he‎ > ‎security‎ > ‎

Html-Sql-Injection Detection

A very simple prototype of html injection detection in MS SQLServer, please notice, that real detection is much more complex...


If Exists(Select Top 1 object_id From tempdb.sys.tables Where name = '##InjWatch')
    Delete From ##injWatch
Else
    Create Table ##InjWatch(ctext nvarchar(max), tab varchar(768), col varchar(768));
GO

Set TRANSACTION ISOLATION LEVEL read uncommitted;

Declare
CheckHtmlInjectCursor Cursor FAST_FORWARD READ_ONLY For
  Select 'CAST([' + c.name + '] AS NVARCHAR(MAX))' As c_cast,
    c.name As c_name, '' + s.name + '.[' +T.name + ']' As sT_name
  From sys.tables T
  Inner Join sys.columns c
    On  c.object_id = T.object_id
    And c.max_length > 16 And c.system_type_id In (
      Select system_type_id From sys.types Where name In (        -- TODO: check 'user defined' string types
       
'varchar', 'nvarchar', 'char', 'nchar', 'text', 'ntext')) -- TODO: check binary types and xml => ;(
  Inner Join sys.schemas s
    On s.schema_id = T.schema_id

Declare @c_cast varchar(1024), @c_name varchar(768), @sT_name varchar(768)
Open CheckHtmlInjectCursor
Fetch Next From CheckHtmlInjectCursor Into @c_cast, @c_name, @sT_name

While
(@@FETCH_STATUS = 0)
Begin
  Declare @execSQL nvarchar(max)
  Set @execSQL = 'INSERT INTO ##InjWatch(ctext, tab, col) ' +
    'SELECT ' + @c_cast + ' AS ctext, ''' + @sT_name + ''' AS tab, ''' + @c_name + ''' AS col ' +
    'FROM ' + @sT_name +
    ' WHERE (' + @c_cast + ' LIKE ''%<%'' AND ' + @c_cast + ' LIKE ''%>%'') ' +
    ' OR ' + @c_cast + ' LIKE ''%script:%'' OR ' + @c_cast + ' LIKE ''%://%''' +
    ' OR ' + @c_cast + ' LIKE ''%href%'' OR ' + @c_cast + ' LIKE ''%return %''' +
    ' OR ' + @c_cast + ' LIKE ''%mailto:%'''
  Execute sp_executesql @execSQL;
  Fetch Next From CheckHtmlInjectCursor Into @c_cast, @c_name, @sT_name
End
Close CheckHtmlInjectCursor
Deallocate CheckHtmlInjectCursor

Select Distinct * From ##InjWatch
GO
Heinrich Elsigan.
ċ
DetectHtmlInject.sql
(2k)
Heinrich Elsigan,
16.12.2011, 09:19
ċ
SimpleHtmlInjectionDetectionOnMS-SQL.sql
(2k)
Heinrich Elsigan,
16.05.2012, 05:23