示意代码如下:
/// <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
图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(); }现在我们通过参数化存储过程进行数据库查询,这里我们把之前添加的正则表达式校验注释掉。
图7 存储过程查询结果