SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE (job_id = 1) 假设现在要求我们获取Department表中的所有数据,而且必须保留WHERE语句,那我们只要确保WHERE恒真就OK了,SQL示意代码如下:
SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE (job_id = 1) OR 1 = 1
上面我们使得WHERE恒真,所以该查询中WHERE已经不起作用了,其查询结果等同于以下SQL语句。
SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs
SQL查询代码实现如下:
string sql1 = string.Format( "SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE job_id='{0}'", jobId); 现在我们要通过页面请求的方式,让数据库执行我们的SQL语句,我们要在URL中嵌入恶意表达式1=1(或2=2等等),如下URL所示:
/// <summary> /// A helper method to attempt to discover [known] SqlInjection attacks. /// </summary> /// <param name="whereClause">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 name="whereClause">string of the whereClause to check</param> /// <param name="orderBy">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 name="sender">The source of the event.</param> /// <param name="e">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"); } } } }
-- ============================================= -- 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(); } 现在我们通过参数化存储过程进行数据库查询,这里我们把之前添加的正则表达式校验注释掉。
string sql1 = string.Format("SELECT job_id, job_desc, min_lvl, max_lvl FROM jobs WHERE job_id = @jobId"); using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN1"].ToString())) using (var com = new SqlCommand(sql1, con)) { // Pass jobId to sql statement. com.Parameters.Add("@jobId", SqlDbType.Int).Value = jobId; com.Connection.Open(); gdvData.DataSource = com.ExecuteReader(); gdvData.DataBind(); } sqlinjection10
LINQ to SQL 前面使用了存储过程和参数化查询,这两种方法都是非常常用的,而针对于.NET Framework的ORM框架也有很多,如:NHibernate,Castle和Entity Framework,这里我们使用比较简单LINQ to SQL。
sqlinjection17
图 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了。