利用SQL注入漏洞登录后台 (5)

示意代码如下:

/// <summary> /// A helper method to attempt to discover [known] SqlInjection attacks. /// </summary> /// <param>string of the whereClause to check</param> /// <returns>true if found, false if not found </returns> public static bool DetectSqlInjection(string whereClause) { return RegSystemThreats.IsMatch(whereClause); } /// <summary> /// A helper method to attempt to discover [known] SqlInjection attacks. /// </summary> /// <param>string of the whereClause to check</param> /// <param>string of the orderBy clause to check</param> /// <returns>true if found, false if not found </returns> public static bool DetectSqlInjection(string whereClause, string orderBy) { return RegSystemThreats.IsMatch(whereClause) || RegSystemThreats.IsMatch(orderBy); }

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

/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param>The source of the event.</param> /// <param>The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Gets departmentId from http request. string queryString = Request.QueryString["jobId"]; if (!string.IsNullOrEmpty(queryString)) { if (!DetectSqlInjection(queryString) && !DetectSqlInjection(queryString, queryString)) { // Gets data from database. gdvData.DataSource = GetData(queryString.Trim()); // Binds data to gridview. gdvData.DataBind(); } else { throw new Exception("Please enter correct field"); } } } }

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

:3452/ExcelUsingXSLT/Default.aspx?jobid=1\'or\'1\'=http://www.likecs.com/\'1

sqlinjection9

图6 添加校验查询结果

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

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

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

-- ============================================= -- Author: JKhuang -- Create date: 12/31/2011 -- Description: Get data from jobs table by specified jobId. -- ============================================= ALTER PROCEDURE [dbo].[GetJobs] -- ensure that the id type is int @jobId INT AS BEGIN -- SET NOCOUNT ON; SELECT job_id, job_desc, min_lvl, max_lvl FROM dbo.jobs WHERE job_id = @jobId GRANT EXECUTE ON GetJobs TO pubs END

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

using (var com = new SqlCommand("GetJobs", con)) { // Uses store procedure. com.CommandType = CommandType.StoredProcedure; // Pass jobId to store procedure. com.Parameters.Add("@jobId", SqlDbType.Int).Value = jobId; com.Connection.Open(); gdvData.DataSource = com.ExecuteScalar(); gdvData.DataBind(); }

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

sqlinjection10

图7 存储过程查询结果

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzzsxw.html