现在的位置: 首页 > 综合 > 正文

SQL注入原理(转)

2016年08月23日 ⁄ 综合 ⁄ 共 24510字 ⁄ 字号 评论关闭

1.1.1 摘要

日前,国内最大的程序员社区CSDN网站的用户数据库被黑客公开发布,600万用户的登录名及密码被公开泄露,随后又有多家网站的用户密码被流传于网络,连日来引发众多网民对自己账号、密码等互联网信息被盗取的普遍担忧。

网络安全成为了现在互联网的焦点,这也恰恰触动了每一位用户的神经,由于设计的漏洞导致了不可收拾的恶果,验证了一句话“出来混的,迟早是要还的”,所以我想通过专题博文介绍一些常用的攻击技术和防范策略。

SQL Injection也许很多人都知道或者使用过,如果没有了解或完全没有听过也没有关系,因为接下来我们将介绍SQL
Injection。

1.1.2 正文

SQL Injection:就是通过把SQL命令插入到Web表单递交或输入域名或页面请求的查询字符串,最终达到欺骗服务器执行恶意的SQL命令。

具体来说,它是利用现有应用程序,将(恶意)的SQL命令注入到后台数据库引擎执行的能力,它可以通过在Web表单中输入(恶意)SQL语句得到一个存在安全漏洞的网站上的数据库,而不是按照设计者意图去执行SQL语句。

首先让我们了解什么时候可能发生SQL Injection。

假设我们在浏览器中输入URL www.sample.com,由于它只是对页面的简单请求无需对数据库动进行动态请求,所以它不存在SQL Injection,当我们输入www.sample.com?testid=23时,我们在URL中传递变量testid,并且提供值为23,由于它是对数据库进行动态查询的请求(其中?testid=23表示数据库查询变量),所以我们可以该URL中嵌入恶意SQL语句。

现在我们知道SQL Injection适用场合,接下来我们将通过具体的例子来说明SQL Injection的应用,这里我们以pubs数据库作为例子。

我们通过Web页面查询job表中的招聘信息,job表的设计如下:

sqlinjection5

图1 jobs表

接着让我们实现Web程序,它根据工作Id(job_id)来查询相应的招聘信息,示意代码如下:

<span style="word-break: break-all; line-height: normal !important; color: gray;">/// <summary>
///</span><span style="word-break: break-all; line-height: normal !important; color: green;">Handles the Load event of the Page control.</span><span style="word-break: break-all; line-height: normal !important; color: gray;">/// </summary>
/// <param name="sender"></span><span style="word-break: break-all; line-height: normal !important; color: green;">The source of the event.</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param>
/// <param name="e"></span><span style="word-break: break-all; line-height: normal !important; color: green;">The</span><span style="word-break: break-all; line-height: normal !important; color: gray;"><see cref="System.EventArgs"/></span><span style="word-break: break-all; line-height: normal !important; color: green;">instance containing the event data.</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param></span><span style="word-break: break-all; line-height: normal !important; color: blue;">protected void</span>Page_Load(<span style="word-break: break-all; line-height: normal !important; color: blue;">object</span>sender,<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">EventArgs</span>e)
{<span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(!IsPostBack)
    {<span style="word-break: break-all; line-height: normal !important; color: green;">// Gets departmentId from http request.</span><span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>queryString = Request.QueryString[<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"departmentID"</span>];<span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(!<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>.IsNullOrEmpty(queryString))
        {<span style="word-break: break-all; line-height: normal !important; color: green;">// Gets data from database.</span>gdvData.DataSource = GetData(queryString.Trim());<span style="word-break: break-all; line-height: normal !important; color: green;">// Binds data to gridview.</span>gdvData.DataBind();
        }
    }
}

现在我们已经完成了Web程序,接下来让我们查询相应招聘信息吧。

sqlinjection6

图2 job表查询结果

如图所示,我们要查询数据库中工作Id值为1的工作信息,而且在页面显示了该工作的Id,Description,Min
Lvl和Max Lvl等信息。

现在要求我们实现根据工作Id查询相应工作信息的功能,想必大家很快可以给出解决方案,SQL示意代码如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>jobs<span style="word-break: break-all; line-height: normal !important; color: blue;">WHERE</span><span style="word-break: break-all; line-height: normal !important; color: gray;">(</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">=</span>1<span style="word-break: break-all; line-height: normal !important; color: gray;">)</span>

假设现在要求我们获取Department表中的所有数据,而且必须保留WHERE语句,那我们只要确保WHERE恒真就OK了,SQL示意代码如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT     job_id</span><span style="word-break: break-all; line-height: normal !important; color: gray;">, job_desc, min_lvl, max_lvl</span><span style="word-break: break-all; line-height: normal !important; color: blue;">FROM         jobs
WHERE</span><span style="word-break: break-all; line-height: normal !important; color: gray;">(job_id = 1) OR 1 = 1</span>

上面我们使得WHERE恒真,所以该查询中WHERE已经不起作用了,其查询结果等同于以下SQL语句。

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT     job_id</span><span style="word-break: break-all; line-height: normal !important; color: gray;">, job_desc, min_lvl, max_lvl</span><span style="word-break: break-all; line-height: normal !important; color: blue;">FROM         jobs</span>

SQL查询代码实现如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>sql1 =<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>.Format(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE job_id='{0}'"</span>, jobId);

现在我们要通过页面请求的方式,让数据库执行我们的SQL语句,我们要在URL中嵌入恶意表达式1=1(或2=2等等),如下URL所示:

http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or'1'='1

等效SQL语句如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>jobs<span style="word-break: break-all; line-height: normal !important; color: blue;">WHERE</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">=</span><span style="word-break: break-all; line-height: normal !important; color: red;">'1'</span><span style="word-break: break-all; line-height: normal !important; color: gray;">OR</span><span style="word-break: break-all; line-height: normal !important; color: red;">'1'</span><span style="word-break: break-all; line-height: normal !important; color: gray;">=</span>1<span style="word-break: break-all; line-height: normal !important; color: red;">'</span>

sqlinjection7

图3 job表查询结果

现在我们把job表中的所有数据都查询出来了,仅仅通过一个简单的恒真表达式就可以进行了一次简单的攻击。

虽然我们把job表的数据都查询出来了,但数据并没有太大的价值,由于我们把该表临时命名为job表,所以接着我们要找出该表真正表名。

首先我们假设表名就是job,然后输入以下URL:

http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or
1=(select count(*) from job)--

等效SQL语句如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>jobs<span style="word-break: break-all; line-height: normal !important; color: blue;">WHERE</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">=</span><span style="word-break: break-all; line-height: normal !important; color: red;">'1'</span><span style="word-break: break-all; line-height: normal !important; color: gray;">or</span>1<span style="word-break: break-all; line-height: normal !important; color: gray;">=(</span><span style="word-break: break-all; line-height: normal !important; color: blue;">select</span><span style="word-break: break-all; line-height: normal !important; color: rgb(255, 0, 255);">count</span><span style="word-break: break-all; line-height: normal !important; color: gray;">(*)</span><span style="word-break: break-all; line-height: normal !important; color: blue;">from</span>job<span style="word-break: break-all; line-height: normal !important; color: gray;">)</span><span style="word-break: break-all; line-height: normal !important; color: green;">--'</span>

sqlinjection8

图4 job表查询结果

当我们输入了以上URL后,结果服务器返回我们错误信息,这证明了我们的假设是错误的,那我们该感觉到挫败吗?不,其实这里返回了很多信息,首先它证明了该表名不是job,而且它还告诉我们后台数据库是SQL Server,不是MySQLOracle,这也设计一个漏洞把错误信息直接返回给了用户。

接下假定表名是jobs,然后输入以下URL:

http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or1=(select
count(*) from jobs) --

等效SQL语句如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>jobs<span style="word-break: break-all; line-height: normal !important; color: blue;">WHERE</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">=</span><span style="word-break: break-all; line-height: normal !important; color: red;">'1'</span><span style="word-break: break-all; line-height: normal !important; color: gray;">or</span>1<span style="word-break: break-all; line-height: normal !important; color: gray;">=(</span><span style="word-break: break-all; line-height: normal !important; color: blue;">select</span><span style="word-break: break-all; line-height: normal !important; color: rgb(255, 0, 255);">count</span><span style="word-break: break-all; line-height: normal !important; color: gray;">(*)</span><span style="word-break: break-all; line-height: normal !important; color: blue;">from</span>jobs<span style="word-break: break-all; line-height: normal !important; color: gray;">)</span><span style="word-break: break-all; line-height: normal !important; color: green;">--'</span>

sqlinjection

图5 job表查询结果

现在证明了该表名是jobs,这可以迈向成功的一大步,由于我们知道了表名就可以对该表进行增删改操作了,而且我们还可以猜测出更多的表对它们作出修改,一旦修改成功那么这将是一场灾难。

现在大家已经对SQL Injection的攻击有了初步的了解了,接下让我们学习如何防止SQL
Injection。

总的来说有以下几点:

1.永远不要信任用户的输入,要对用户的输入进行校验,可以通过正则表达式,或限制长度,对单引号和双"-"进行转换等。

2.永远不要使用动态拼装SQL,可以使用参数化的SQL或者直接使用存储过程进行数据查询存取。

3.永远不要使用管理员权限的数据库连接,为每个应用使用单独的权限有限的数据库连接。

4.不要把机密信息明文存放,请加密或者hash掉密码和敏感的信息。

5.应用的异常信息应该给出尽可能少的提示,最好使用自定义的错误信息对原始错误信息进行包装,把异常信息存放在独立的表中。

通过正则表达校验用户输入

首先我们可以通过正则表达式校验用户输入数据中是包含:对单引号和双"-"进行转换等字符。

然后继续校验输入数据中是否包含SQL语句的保留字,如:WHERE,EXEC,DROP等。

现在让我们编写正则表达式来校验用户的输入吧,正则表达式定义如下:

<span style="word-break: break-all; line-height: normal !important; color: blue;">private static readonly</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">Regex</span>RegSystemThreats =<span style="word-break: break-all; line-height: normal !important; color: blue;">new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">Regex</span>(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">@"\s?or\s*|\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|"</span>+<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">@"\s?sysobjects\s?|\s?xp_.*?|\s?syslogins\s?|\s?sysremote\s?|\s?sysusers\s?|\s?sysxlogins\s?|\s?sysdatabases\s?|\s?aspnet_.*?|\s?exec\s?"</span>,<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">RegexOptions</span>.Compiled |<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">RegexOptions</span>.IgnoreCase);

上面我们定义了一个正则表达式对象RegSystemThreats,并且给它传递了校验用户输入的正则表达式。

由于我们已经完成了对用户输入校验的正则表达式了,接下来就是通过该正则表达式来校验用户输入是否合法了,由于.NET已经帮我们实现了判断字符串是否匹配正则表达式的方法——IsMatch(),所以我们这里只需给传递要匹配的字符串就OK了。

示意代码如下:

<span style="word-break: break-all; line-height: normal !important; color: gray;">/// <summary>
///</span><span style="word-break: break-all; line-height: normal !important; color: green;">A helper method to attempt to discover [known] SqlInjection attacks.</span><span style="word-break: break-all; line-height: normal !important; color: gray;">/// </summary>
/// <param name="whereClause"></span><span style="word-break: break-all; line-height: normal !important; color: green;">string of the whereClause to check</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param>
/// <returns></span><span style="word-break: break-all; line-height: normal !important; color: green;">true if found, false if not found</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></returns></span><span style="word-break: break-all; line-height: normal !important; color: blue;">public static bool</span>DetectSqlInjection(<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>whereClause)
{<span style="word-break: break-all; line-height: normal !important; color: blue;">return</span>RegSystemThreats.IsMatch(whereClause);
}<span style="word-break: break-all; line-height: normal !important; color: gray;">/// <summary>
///</span><span style="word-break: break-all; line-height: normal !important; color: green;">A helper method to attempt to discover [known] SqlInjection attacks.</span><span style="word-break: break-all; line-height: normal !important; color: gray;">/// </summary>
/// <param name="whereClause"></span><span style="word-break: break-all; line-height: normal !important; color: green;">string of the whereClause to check</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param>
/// <param name="orderBy"></span><span style="word-break: break-all; line-height: normal !important; color: green;">string of the orderBy clause to check</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param>
/// <returns></span><span style="word-break: break-all; line-height: normal !important; color: green;">true if found, false if not found</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></returns></span><span style="word-break: break-all; line-height: normal !important; color: blue;">public static bool</span>DetectSqlInjection(<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>whereClause,<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>orderBy)
{<span style="word-break: break-all; line-height: normal !important; color: blue;">return</span>RegSystemThreats.IsMatch(whereClause) || RegSystemThreats.IsMatch(orderBy);
}

现在我们完成了校验用的正则表达式,接下来让我们需要在页面中添加校验功能。

<span style="word-break: break-all; line-height: normal !important; color: gray;">/// <summary>
///</span><span style="word-break: break-all; line-height: normal !important; color: green;">Handles the Load event of the Page control.</span><span style="word-break: break-all; line-height: normal !important; color: gray;">/// </summary>
/// <param name="sender"></span><span style="word-break: break-all; line-height: normal !important; color: green;">The source of the event.</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param>
/// <param name="e"></span><span style="word-break: break-all; line-height: normal !important; color: green;">The</span><span style="word-break: break-all; line-height: normal !important; color: gray;"><see cref="System.EventArgs"/></span><span style="word-break: break-all; line-height: normal !important; color: green;">instance containing the event data.</span><span style="word-break: break-all; line-height: normal !important; color: gray;"></param></span><span style="word-break: break-all; line-height: normal !important; color: blue;">protected void</span>Page_Load(<span style="word-break: break-all; line-height: normal !important; color: blue;">object</span>sender,<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">EventArgs</span>e)
{<span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(!IsPostBack)
    {<span style="word-break: break-all; line-height: normal !important; color: green;">// Gets departmentId from http request.</span><span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>queryString = Request.QueryString[<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"jobId"</span>];<span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(!<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>.IsNullOrEmpty(queryString))
        {<span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(!DetectSqlInjection(queryString) && !DetectSqlInjection(queryString, queryString))
            {<span style="word-break: break-all; line-height: normal !important; color: green;">// Gets data from database.</span>gdvData.DataSource = GetData(queryString.Trim());<span style="word-break: break-all; line-height: normal !important; color: green;">// Binds data to gridview.</span>gdvData.DataBind();
            }<span style="word-break: break-all; line-height: normal !important; color: blue;">else</span>{<span style="word-break: break-all; line-height: normal !important; color: blue;">throw new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">Exception</span>(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"Please enter correct field"</span>);
            }
        }
    }
}

当我们再次执行以下URL时,被嵌入的恶意语句被校验出来了,从而在一定程度上防止了SQL Injection。

http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or'1'='1

sqlinjection9

图6 添加校验查询结果

但使用正则表达式只能防范一些常见或已知SQL Injection方式,而且每当发现有新的攻击方式时,都要对正则表达式进行修改,这可是吃力不讨好的工作。

通过参数化存储过程进行数据查询存取

首先我们定义一个存储过程根据jobId来查找jobs表中的数据。

<span style="word-break: break-all; line-height: normal !important; color: green;">-- =============================================
-- Author:        JKhuang
-- Create date: 12/31/2011
-- Description:    Get data from jobs table by specified jobId.
-- =============================================</span><span style="word-break: break-all; line-height: normal !important; color: blue;">ALTER PROCEDURE</span>[dbo]<span style="word-break: break-all; line-height: normal !important; color: gray;">.</span>[GetJobs]<span style="word-break: break-all; line-height: normal !important; color: green;">-- ensure that the id type is int</span>@jobId<span style="word-break: break-all; line-height: normal !important; color: blue;">INT
AS
BEGIN</span><span style="word-break: break-all; line-height: normal !important; color: green;">--    SET NOCOUNT ON;</span><span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>dbo<span style="word-break: break-all; line-height: normal !important; color: gray;">.</span>jobs<span style="word-break: break-all; line-height: normal !important; color: blue;">WHERE</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">=</span>@jobId<span style="word-break: break-all; line-height: normal !important; color: blue;">GRANT EXECUTE ON</span>GetJobs<span style="word-break: break-all; line-height: normal !important; color: blue;">TO</span>pubs<span style="word-break: break-all; line-height: normal !important; color: blue;">END</span>

接着修改我们的Web程序使用参数化的存储过程进行数据查询。

<span style="word-break: break-all; line-height: normal !important; color: blue;">using</span>(var com =<span style="word-break: break-all; line-height: normal !important; color: blue;">new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">SqlCommand</span>(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"GetJobs"</span>, con))
{<span style="word-break: break-all; line-height: normal !important; color: green;">// Uses store procedure.</span>com.CommandType =<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">CommandType</span>.StoredProcedure;<span style="word-break: break-all; line-height: normal !important; color: green;">// Pass jobId to store procedure.</span>com.Parameters.Add(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"@jobId"</span>,<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">SqlDbType</span>.Int).Value = jobId;
    com.Connection.Open();
    gdvData.DataSource = com.ExecuteScalar();
    gdvData.DataBind(); 
}

现在我们通过参数化存储过程进行数据库查询,这里我们把之前添加的正则表达式校验注释掉。

sqlinjection10

图7 存储过程查询结果

大家看到当我们试图在URL中嵌入恶意的SQL语句时,参数化存储过程已经帮我们校验出传递给数据库的变量不是整形,而且使用存储过程的好处是我们还可以很方便地控制用户权限,我们可以给用户分配只读或可读写权限。

但我们想想真的有必要每个数据库操作都定义成存储过程吗?而且那么多的存储过程也不利于日常的维护。

参数化SQL语句

还是回到之前动态拼接SQL基础上,我们知道一旦有恶意SQL代码传递过来,而且被拼接到SQL语句中就会被数据库执行,那么我们是否可以在拼接之前进行判断呢?——命名SQL参数。

<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>sql1 =<span style="word-break: break-all; line-height: normal !important; color: blue;">string</span>.Format(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE job_id = @jobId"</span>);<span style="word-break: break-all; line-height: normal !important; color: blue;">using</span>(var con =<span style="word-break: break-all; line-height: normal !important; color: blue;">new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">SqlConnection</span>(<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">ConfigurationManager</span>.ConnectionStrings[<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"SQLCONN1"</span>].ToString()))<span style="word-break: break-all; line-height: normal !important; color: blue;">using</span>(var com =<span style="word-break: break-all; line-height: normal !important; color: blue;">new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">SqlCommand</span>(sql1, con))
{<span style="word-break: break-all; line-height: normal !important; color: green;">// Pass jobId to sql statement.</span>com.Parameters.Add(<span style="word-break: break-all; line-height: normal !important; color: rgb(163, 21, 21);">"@jobId"</span>,<span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">SqlDbType</span>.Int).Value = jobId;
    com.Connection.Open();
    gdvData.DataSource = com.ExecuteReader();
    gdvData.DataBind(); 
}

sqlinjection10

图8 参数化SQL查询结果

这样我们就可以避免每个数据库操作(尤其一些简单数据库操作)都编写存储过程了,而且当用户具有数据库中jobs表的读权限才可以执行该SQL语句。

添加新架构

数据库架构是一个独立于数据库用户的非重复命名空间,您可以将架构视为对象的容器(类似于.NET中的命名空间)。

首先我们右击架构文件夹,然后新建架构。

clip_image002

sqlinjection12

图9 添加HumanResource架构

上面我们完成了在pubs数据库中添加HumanResource架构,接着把jobs表放到HumanResource架构中。

sqlinjection15

sqlinjection13

图 10 修改jobs表所属的架构

当我们再次执行以下SQL语句时,SQL Server提示jobs无效,这是究竟什么原因呢?之前还运行的好好的。

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>jobs

sqlinjection14

图 11 查询输出

当我们输入完整的表名“架构名.对象名”(HumanResource.jobs)时,SQL语句执行成功。

<span style="word-break: break-all; line-height: normal !important; color: blue;">SELECT</span>job_id<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>job_desc<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>min_lvl<span style="word-break: break-all; line-height: normal !important; color: gray;">,</span>max_lvl<span style="word-break: break-all; line-height: normal !important; color: blue;">FROM</span>HumanResource<span style="word-break: break-all; line-height: normal !important; color: gray;">.</span>jobs

sqlinjection16

为什么之前我们执行SQL语句时不用输入完整表名dbo.jobs也可以执行呢?

这是因为默认的架构(default schema)是dbo,当只输入表名时,Sql Server会自动加上当前登录用户的默认的架构(default schema)——dbo。

由于我们使用自定义架构,这也降低了数据库表名被猜测出来的可能性。

LINQ to SQL

前面使用了存储过程和参数化查询,这两种方法都是非常常用的,而针对于.NET Framework的ORM框架也有很多,如:NHibernate,Castle和Entity Framework,这里我们使用比较简单LINQ to SQL。

sqlinjection17

图 12 添加jobs.dbml文件

var dc =<span style="word-break: break-all; line-height: normal !important; color: blue;">new</span><span style="word-break: break-all; line-height: normal !important; color: rgb(43, 145, 175);">pubsDataContext</span>();<span style="word-break: break-all; line-height: normal !important; color: blue;">int</span>result;<span style="word-break: break-all; line-height: normal !important; color: green;">// Validates jobId is int or not.</span><span style="word-break: break-all; line-height: normal !important; color: blue;">if</span>(<span style="word-break: break-all; line-height: normal !important; color: blue;">int</span>.TryParse(jobId,<span style="word-break: break-all; line-height: normal !important; color: blue;">out</span>result))
{
    gdvData.DataSource = dc.jobs.Where(p => p.job_id == result);
    gdvData.DataBind();
}

相比存储过程和参数化查询,LINQ to SQL我们只需添加jobs.dbml,然后使用LINQ对表进行查询就OK了。

1.1.3 总结

我们在本文中介绍了SQL Injection的基本原理,通过介绍什么是SQL Injection,怎样进行SQL Injection和如何防范SQL Injection。通过一些程序源码对SQL的攻击进行了细致的分析,使我们对SQL Injection机理有了一个深入的认识,作为一名Web应用开发人员,一定不要盲目相信用户的输入,而要对用户输入的数据进行严格的校验处理,否则的话,SQL Injection将会不期而至。

抱歉!评论已关闭.