- 浏览: 35087 次
- 性别:
- 来自: 唐山
文章分类
最新评论
通过HttpModule、httpHandlers防止SQL注入式攻击
1、通过HttpModule防止SQL注入式攻击,适用于.net1.1程序
(1)新建类文件SqlHttpModule.cs,具体代码类似如下:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; namespace HttpModule.Class { /// <summary> /// SqlInPost 的摘要说明 /// </summary> public class SqlHttpModule : System.Web.IHttpModule { public SqlHttpModule() { } public void Dispose() { } public void Init(HttpApplication context) { context.AcquireRequestState += new EventHandler(context_AcquireRequestState); } private void context_AcquireRequestState(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; try { string getkeys = string.Empty; string keyvalue = string.Empty; string strErrorAlertScript = "<script type=\"text/javascript\">alert('字符串格式非法,请重新输入!');history.go(-1);</script>"; string requestUrl = context.Request.Path.ToString(); #region URL提交数据 if (context.Request.QueryString != null) { for (int i = 0; i < context.Request.QueryString.Count; i++) { getkeys = context.Request.QueryString.Keys[i]; keyvalue = context.Server.UrlDecode(context.Request.QueryString[getkeys]).Replace("'", ""); if (!IsSafeString(keyvalue)) { context.Response.Write(strErrorAlertScript); context.Response.End(); break; } } } #endregion #region 表单提交数据 if (context.Request.Form != null) { for (int i = 0; i < context.Request.Form.Count; i++) { getkeys = context.Request.Form.Keys[i].ToUpper(); if (getkeys == "__VIEWSTATE" || getkeys == "__EVENTARGUMENT" || getkeys == "__EVENTTARGET" || getkeys == "__CLIENTPOSTDATA__") continue; keyvalue = context.Server.HtmlDecode(context.Request.Form[i]).Replace("'", ""); if (!IsSafeString(keyvalue)) { context.Response.Write(strErrorAlertScript); context.Response.End(); break; } } } #endregion } catch (Exception ex) { } } //判断是否为安全字符串 public bool IsSafeString(string strText) { bool bResult = true; //strText = Regex.Replace(strText, "[\\s]{1,}", ""); //two or more spaces strText = Regex.Replace(strText, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br> string FilterSql = System.Configuration.ConfigurationSettings.AppSettings["SqlHttpModule_KeyWord"];//将关键词组配置在webconfig中 if(FilterSql==null || FilterSql=="") { string[] UnSafeArray = new string[23]; UnSafeArray[0] = "'"; UnSafeArray[1] = "xp_cmdshell "; UnSafeArray[2] = "declare"; UnSafeArray[3] = "netlocalgroupadministrators "; UnSafeArray[4] = "delete "; UnSafeArray[5] = "truncate "; UnSafeArray[6] = "netuser "; UnSafeArray[7] = "/add "; UnSafeArray[8] = "drop "; UnSafeArray[9] = "update "; UnSafeArray[10] = "select "; UnSafeArray[11] = "union "; UnSafeArray[12] = "exec "; UnSafeArray[13] = "create "; UnSafeArray[14] = "insertinto "; UnSafeArray[15] = "sp_ "; UnSafeArray[16] = "exec "; UnSafeArray[17] = "create "; UnSafeArray[18] = "insert "; UnSafeArray[19] = "masterdbo "; UnSafeArray[20] = "sp_ "; UnSafeArray[21] = ";-- "; UnSafeArray[22] = "1= "; foreach (string strValue in UnSafeArray) { if (strText.ToLower().IndexOf(strValue) > -1) { bResult = false; break; } } } else { string sqlStr = FilterSql; string[] sqlStrs = sqlStr.Split('|'); foreach (string ss in sqlStrs) { if (strText.ToLower().IndexOf(ss) >= 0) { bResult = false; break; } } } return bResult; } } }
(2)在web.config文件中做以下配置
</system.web>
<httpModules>
<add name="SqlHttpModule" type="HttpModule.Class.SqlHttpModule, HttpModule" />
</httpModules>
</system.web>
2、通过httpHandlers防止SQL注入式攻击,适用于.net2.0及以上程序
(1)新建类文件SqlhttpHandlers.cs,具体代码类似如下:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; using System.Collections.Specialized; namespace httpHandlers { /// <summary> /// SqlInPost 的摘要说明 /// </summary> public class SqlhttpHandlers : IHttpHandlerFactory { public SqlhttpHandlers() { // // TODO: 在此处添加构造函数逻辑 // } public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { //得到编译实例(通过反射) PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true); IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated); //过滤字符串 if (requestType == "POST") { Page page = handler as Page; if (page != null) page.PreLoad += new EventHandler(FormFilterStrFactoryHandler_PreLoad); } if (requestType == "GET") { Page page = handler as Page; if (page != null) page.PreLoad += new EventHandler(RequestFilterStrFactoryRHandler_PreLoad); } //返回 return handler; } public virtual void ReleaseHandler(IHttpHandler handler) { } /// <summary> /// 过滤TextBox、Input和Textarea中非法字符 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void FormFilterStrFactoryHandler_PreLoad(object sender, EventArgs e) { try { bool isSafe = true; Page page = sender as Page; NameValueCollection postData = page.Request.Form; foreach (string postKey in postData) { Control ctl = page.FindControl(postKey); if (ctl as TextBox != null) { ((TextBox)ctl).Text = ((TextBox)ctl).Text.Replace("'", "'"); string strValue = ((TextBox)ctl).Text.Trim(); if (!IsSafeString(strValue)) { isSafe = false; break; } continue; } if (ctl as HtmlInputControl != null) { ((HtmlInputControl)ctl).Value = ((HtmlInputControl)ctl).Value.Replace("'", "'"); string strValue = ((HtmlInputControl)ctl).Value.Trim(); if (!IsSafeString(strValue)) { isSafe = false; break; } continue; } if (ctl as HtmlTextArea != null) { ((HtmlTextArea)ctl).Value = ((HtmlTextArea)ctl).Value.Replace("'", "'"); string strValue = ((HtmlTextArea)ctl).Value.Trim(); if (!IsSafeString(strValue)) { isSafe = false; break; } continue; } } if (!isSafe) { page.Response.Write("<b><font color='red' font-size=12pt>字符串格式非法!</font></b>"); page.Response.End(); } } catch(Exception ex) { string a = ex.Message; } } /// <summary> /// 过滤QueryString 中的非法字符串 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RequestFilterStrFactoryRHandler_PreLoad(object sender, EventArgs e) { try { Page page = sender as Page; NameValueCollection QueryNV = page.Request.QueryString; bool isSafe = true; for (int i = 0; i < QueryNV.Count; i++) { if (!IsSafeString(QueryNV.Get(i))) { isSafe = false; break; } } if (!isSafe) { page.Response.Write("<b><font color='red' font-size=12pt>字符串格式非法!</font></b>"); page.Response.End(); } } catch { } } //判断是否为安全字符串 public bool IsSafeString(string strText) { bool bResult = true; strText = Regex.Replace(strText, "[\\s]{1,}", ""); //two or more spaces strText = Regex.Replace(strText, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br> string[] UnSafeArray = new string[23]; UnSafeArray[0] = "'"; UnSafeArray[1] = "xp_cmdshell"; UnSafeArray[2] = "declare"; UnSafeArray[3] = "netlocalgroupadministrators"; UnSafeArray[4] = "delete"; UnSafeArray[5] = "truncate"; UnSafeArray[6] = "netuser"; UnSafeArray[7] = "/add"; UnSafeArray[8] = "drop"; UnSafeArray[9] = "update"; UnSafeArray[10] = "select"; UnSafeArray[11] = "union"; UnSafeArray[12] = "exec"; UnSafeArray[13] = "create"; UnSafeArray[14] = "insertinto"; UnSafeArray[15] = "sp_"; UnSafeArray[16] = "exec"; UnSafeArray[17] = "create"; UnSafeArray[18] = "insertinto"; UnSafeArray[19] = "masterdbo"; UnSafeArray[20] = "sp_"; UnSafeArray[21] = ";--"; UnSafeArray[22] = "1="; foreach (string strValue in UnSafeArray) { if (strText.ToLower().IndexOf(strValue) > -1) { bResult = false; break; } } return bResult; } } }
(2)在web.config文件中做以下配置
</system.web>
<httpHandlers>
<add verb="*" path="*.aspx" type="httpHandlers.SqlhttpHandlers, httpHandlers"/>
</httpHandlers>
</system.web>
相关推荐
ASP.NET 防止 SQL 注入攻击的方法有很多,这些方法包括参数法防注入、传统的笨一点的办法、HttpModule 实现防sql注入、SqlFilter 防止 SQL 注入、validation 防止 SQL 注入等。只有通过使用这些方法,才能有效地防止...
在防止SQL注入的安全策略中,HttpModule扮演着关键角色,因为它可以在请求到达实际的页面处理程序之前进行干预,从而对用户输入进行检查和过滤。 在标题所提及的"asp.net利用HttpModule实现防sql注入"中,我们首先...
SQL注入是一种常见的网络安全威胁,攻击者通过输入恶意的SQL代码到表单字段或其他用户输入点,试图欺骗数据库系统执行非授权的操作,如获取敏感信息、修改或删除数据。这种攻击方式可能导致数据泄露、系统瘫痪,甚至...
在.NET框架中,HttpModule是一...然而,值得注意的是,单一的IP限制并不总是足够安全,因为攻击者可能通过代理或动态IP地址绕过限制。因此,结合其他安全措施,如验证码、用户身份验证等,可以进一步提高系统的安全性。
通过深入理解HttpModule和HttpHandler的工作原理,我们可以更好地优化应用程序性能,实现复杂的业务需求。博客上的学习资料会进一步详细解释这些概念,并提供实践示例,帮助你轻松掌握这两个核心组件。
这个【HttpModule伪静态实例】是一个用于演示如何通过HttpModule实现URL伪静态的技术方案,这对于提升网站SEO(搜索引擎优化)和用户体验具有重要意义。 首先,我们来看看什么是URL伪静态。静态URL通常是指以`....
例如,使用参数化查询防止SQL注入攻击,检查文件是否存在和是否可读,以及处理可能出现的异常情况。 总结来说,通过ASP.NET结合SQL语句,我们可以高效地对Excel文件进行数据操作,这在数据导入导出、临时数据存储等...
c#httpModule中重写url
CookieEncryption_Solution HTTPmodule操作cookie的方法demo
在实际项目中,HttpModule可以与其他组件如HttpHandlers、Controllers等协同工作,以实现复杂的业务逻辑。例如,你可能有一个`Default.aspx`页面,当用户访问该页面时,HttpModule可以在请求到达页面之前先进行处理...
`RegisterHttpModule`方法是用于动态注册HttpModule的一种技术,这使得我们能够在不修改Web.config配置文件的情况下,实现HttpModule的添加和管理。 HttpModule本身是一种特殊的类,它继承自`System.Web....
***中通过HttpModule计算页面执行时间的知识点涵盖以下几个方面: 1. 页面执行时间的测量意义 页面执行时间是指从用户发起请求到服务器完全处理完毕并返回响应的这段时间。它是衡量Web应用性能的重要指标,对优化...
c#基于HttpModule的用户身份验证 c#基于HttpModule的用户身份验证 c#基于HttpModule的用户身份验证 c#基于HttpModule的用户身份验证c#
每个HttpModule都实现了IHttpModule接口,并且通过在`web.config`文件中注册,可以将它们添加到ASP.NET的请求处理管道中。 **ASP.NET请求流程**是这样的:客户端发起HTTP请求,服务器接收到请求后,IIS(Internet ...
***是一种流行的服务器端Web应用开发框架,通过HTTP模块(HttpModule)可以进行各种请求处理和响应修改,例如,当项目中需要在很多页面上使用一个共同的参数(比如cid)时,我们可以使用HttpModule在URL地址上自动...
在ASP.NET中,HttpModule通过实现IHttpModule接口来创建自定义模块。IHttpModule接口有两个关键方法:`Init(HttpApplication context)` 和 `Dispose()`。`Init`方法是模块初始化的地方,可以在这里注册事件处理程序...
知识点:利用HTTPModule统计页面访问量 在深入探讨如何利用HTTPModule来统计页面访问量之前,我们首先需要理解几个核心概念。HTTPModule是ASP.NET框架的一部分,它允许开发者在请求处理过程中插入自定义代码,从而...
在IT行业中,防盗链系统是一种常见的安全措施,用于防止他人盗用网站的资源,比如图片、视频或音频等。在本案例中,我们将探讨如何使用C#编程语言和httpHandlers来构建一个这样的系统。C#是微软开发的一种面向对象的...