图1 jobs表
接着让我们实现Web程序,它根据工作Id(job_id)来查询相应的招聘信息,示意代码如下:
/// /// Handles the Load event of the Page control.///
/// The source of the event.
/// The instance containing the event data.protected void Page_Load(object sender, EventArgs e)
{ if (!IsPostBack)
{ // Gets departmentId from http request. string queryString = Request.QueryString["departmentID"]; if (!string.IsNullOrEmpty(queryString))
{ // Gets data from database. gdvData.DataSource = GetData(queryString.Trim()); // Binds data to gridview. gdvData.DataBind();
}
}
}
现在我们已经完成了Web程序,接下来让我们查询相应招聘信息吧。
图3 job表查询结果
现在我们把job表中的所有数据都查询出来了,仅仅通过一个简单的恒真表达式就可以进行了一次简单的***。
虽然我们把job表的数据都查询出来了,但数据并没有太大的价值,由于我们把该表临时命名为job表,所以接着我们要找出该表真正表名。
首先我们假设表名就是job,然后输入以下URL:
http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or
1=(select count(*) from job)--
等效SQL语句如下:
SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs
WHERE job_id='1'or 1=(select count(*) from job) --'
图4 job表查询结果
当我们输入了以上URL后,结果服务器返回我们错误信息,这证明了我们的假设是错误的,那我们该感觉到挫败吗?不,其实这里返回了很多信息,首先它证明了该表名不是job,而且它还告诉我们后台数据库是SQL
Server,不是MySQL或Oracle,这也设计一个漏洞把错误信息直接返回给了用户。
接下假定表名是jobs,然后输入以下URL:
http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or1=(select
count(*) from jobs) --
等效SQL语句如下:
SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs
WHERE job_id='1'or 1=(select count(*) from jobs) --'
通过正则表达校验用户输入
首先我们可以通过正则表达式校验用户输入数据中是包含:对单引号和双"-"进行转换等字符。
然后继续校验输入数据中是否包含SQL语句的保留字,如:WHERE,EXEC,DROP等。
现在让我们编写正则表达式来校验用户的输入吧,正则表达式定义如下:
private static readonly Regex RegSystemThreats = new Regex(@"\s?or\s*|\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|" + @"\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?", RegexOptions.Compiled | RegexOptions.IgnoreCase); 上面我们定义了一个正则表达式对象RegSystemThreats,并且给它传递了校验用户输入的正则表达式。
由于我们已经完成了对用户输入校验的正则表达式了,接下来就是通过该正则表达式来校验用户输入是否合法了,由于.NET已经帮我们实现了判断字符串是否匹配正则表达式的方法——IsMatch(),所以我们这里只需给传递要匹配的字符串就OK了。
示意代码如下:
/// /// A helper method to attempt to discover [known] SqlInjection attacks.
///
/// string of the whereClause to check
/// true if found, false if not found public static bool DetectSqlInjection(string whereClause)
{ return RegSystemThreats.IsMatch(whereClause);
}///
/// A helper method to attempt to discover [known] SqlInjection attacks.
///
/// string of the whereClause to check
/// string of the orderBy clause to check
/// true if found, false if not found public static bool DetectSqlInjection(string whereClause, string orderBy)
{ return RegSystemThreats.IsMatch(whereClause) || RegSystemThreats.IsMatch(orderBy);
}
现在我们完成了校验用的正则表达式,接下来让我们需要在页面中添加校验功能。
/// /// Handles the Load event of the Page control.///
/// The source of the event.
/// The instance containing the event data.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。
http://localhost:3452/ExcelUsingXSLT/Default.aspx?jobid=1'or'1'='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();
}
现在我们通过参数化存储过程进行数据库查询,这里我们把之前添加的正则表达式校验注释掉。
图 12 添加jobs.dbml文件
var dc = new pubsDataContext();int result;// Validates jobId is int or not.if (int.TryParse(jobId, out result)) {
gdvData.DataSource = dc.jobs.Where(p => p.job_id == result);
gdvData.DataBind();
}
相比存储过程和参数化查询,LINQ to SQL我们只需添加jobs.dbml,然后使用LINQ对表进行查询就OK了。