微軟的“不禁止即允許(Not forbidden is allow)”的做法使得操作系統(tǒng)像是服務(wù)器所穿的鏤空禮物一樣,美觀但卻有很多“漏洞”。好了,現(xiàn)在此小黑已經(jīng)擁有了服務(wù)器的管理員權(quán)限,很顯然元芳怎么看已經(jīng)不重要了。
3.如何防止SQL注入的發(fā)生
滴答的雨已經(jīng)在博文詳細(xì)闡述了SQL Server數(shù)據(jù)庫(kù)如何進(jìn)行防注入的操作,這里不再贅述。這一篇我主要說(shuō)一下對(duì)于一個(gè)使用拼接SQL進(jìn)行查詢操作的Web應(yīng)用,怎么進(jìn)行防注入操作。
先說(shuō)一些前提,為什么我們要使用拼接SQL的方式進(jìn)行查詢?偷懶唄。這在開發(fā)過(guò)程中,看似省去了編寫參數(shù)化部分的代碼量,節(jié)省了時(shí)間和精力。但這樣做的結(jié)果就是應(yīng)用的安全性大打折扣,而且拼SQL方式創(chuàng)建的應(yīng)用,后期的維護(hù)難度也很大。SQL參數(shù)化查詢是最簡(jiǎn)單有效的避免SQL注入的解決方案,目前主流的ORM框架(MyBatis.NET/NHibernate/EntityFramework)都內(nèi)置支持并且推薦使用這種方式進(jìn)行持久層封裝。
然而有數(shù)據(jù)庫(kù)不支持參數(shù)化查詢?cè)趺崔k?是的,你沒(méi)有看錯(cuò),確實(shí)有這樣的數(shù)據(jù)庫(kù)存在。吐個(gè)槽先,個(gè)人認(rèn)為,一切不支持參數(shù)化查詢的數(shù)據(jù)庫(kù)都是在“耍流氓”,這種天然的缺陷會(huì)讓小黑們肆無(wú)忌憚地去“非禮”服務(wù)器,至少是數(shù)據(jù)庫(kù)本身。在這樣的情況下,我覺(jué)得其他功能做得再好也只能算是花拳繡腿,連最基本的數(shù)據(jù)都保護(hù)不了,那不等同于將勞動(dòng)成果拱手讓人。按照存在即合理的邏輯,我們暫且認(rèn)為它是合理的。
來(lái)說(shuō)說(shuō)我目前的做法,基于上述數(shù)據(jù)庫(kù)創(chuàng)建的Web應(yīng)用,拼接SQL操作已經(jīng)滲透到站點(diǎn)的每個(gè)頁(yè)面、每個(gè)用戶控件,所以我采用的方式是請(qǐng)求過(guò)濾。
下面是防SQL注入的操作類:
1: /// summary>
2: ///SqlInject 的摘要說(shuō)明
3: /// /summary>
4: public class SqlInject : System.Web.UI.Page
5: {
6: //檢測(cè)到注入后的處理方式: 0:僅警告;1:警告+記錄;2:警告+自定義錯(cuò)誤頁(yè)面;3:警告+記錄+自定義錯(cuò)誤頁(yè)面
7: private const int _type = 0;
8: private const string errRedirectPage = "/err.aspx";
9:
10: //如果記錄注入信息,那么請(qǐng)?jiān)O(shè)置:errMDBpath:數(shù)據(jù)庫(kù)路徑
11: private const string errMDBpath = "/SqlInject.mdb";
12:
13:
14: //過(guò)濾特征字符
15: //過(guò)濾特征字符
16: private static string StrKeyWord = ConfigurationManager.AppSettings["SqlKeyWord"]; //@"select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec|master|net local group administrators|net user|or|and";
17: private static string StrRegex = ConfigurationManager.AppSettings["SqlRegex"]; //@";|/|(|)|[|]|{|}|%|@|*|'|!"; // 原始過(guò)濾條件:【-|;|,|/|(|)|[|]|{|}|%|@|*|'|!】
18:
19: private HttpRequest request;
20: public SqlInject(System.Web.HttpRequest _request)
21: {
22: this.request = _request;
23: }
24: ///summary>
25: ///檢測(cè)SQL注入及記錄、顯示出錯(cuò)信息
26: ////summary>
27: public void CheckSqlInject()
28: {
29: bool isInject = false;
30: if (CheckRequestQuery() || CheckRequestForm())
31: {
32: isInject = true;
33: }
34: else
35: {
36: return;
37: }
38:
39: switch (_type)
40: {
41: case 0:
42: ShowErr();
43: break;
44: case 1:
45: ShowErr();
46: SaveToMdb();
47: break;
48: case 2:
49: ShowErr();
50: string temp;
51: System.Web.HttpContext.Current.Response.Write("script>setTimeout(\"" + "location.href='" + errRedirectPage + "'" + "\",5000)/script>");
52: break;
53: case 3:
54: ShowErr();
55: SaveToMdb();
56: System.Web.HttpContext.Current.Response.Write("script>setTimeout(\"" + "location.href='" + errRedirectPage + "'" + "\",5000)/script>");
57: break;
58: default:
59: break;
60: }
61: System.Web.HttpContext.Current.Response.End();
62:
63: }
64: private void SaveToMdb()
65: {
66: OleDbConnection conn = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + Server.MapPath(errMDBpath));
67: conn.Open();
68: OleDbCommand cmd = conn.CreateCommand();
69:
70: cmd.CommandText = "insert into [Record] (sIP,sDate,sPath) values ('" +
71: request.ServerVariables["REMOTE_ADDR"].ToString() + "','" +
72: DateTime.Now + "','" + request.ServerVariables["URL"].ToLower() + RelaceSingleQuotes(request.QueryString.ToString()) + "')";
73: int code = cmd.ExecuteNonQuery();
74: if (code == 1)
75: System.Web.HttpContext.Current.Response.Write("br>****以上信息已記錄至日志數(shù)據(jù)庫(kù)****");
76: else
77: System.Web.HttpContext.Current.Response.Write("br>日志數(shù)據(jù)庫(kù)出錯(cuò)");
78: conn.Close();
79:
80: }
81: private string RelaceSingleQuotes(string _url)
82: {
83: string URL = _url.Replace("'", "單引號(hào)");
84: return URL;
85: }
86: private void ShowErr()
87: {
88: //string msg = @"font color=red>請(qǐng)不要嘗試未授權(quán)之入侵檢測(cè)!/font>" + @"br>br>";
89: //msg += @"操作IP:" + request.ServerVariables["REMOTE_ADDR"] + @"br>";
90: //msg += @"操作時(shí)間:" + DateTime.Now + @"br>";
91: //msg += @"頁(yè)面:" + request.ServerVariables["URL"].ToLower() + request.QueryString.ToString() + @"br>";
92: //msg += @"a href='#' onclick='javascript:window.close()'>關(guān)閉/a>";
93: //System.Web.HttpContext.Current.Response.Clear();
94: //System.Web.HttpContext.Current.Response.Write(msg);
95: System.Web.HttpContext.Current.Response.Write("script>alert('請(qǐng)不要嘗試未授權(quán)之入侵檢測(cè)!');javascript:history.go(-1);/script>");
96: }
97: ///summary>
98: /// 特征字符
99: ////summary>
100: public static string KeyWord
101: {
102: get
103: {
104: return StrKeyWord;
105: }
106: }
107: ///summary>
108: /// 特征符號(hào)
109: ////summary>
110: public static string RegexString
111: {
112: get
113: {
114: return StrRegex;
115: }
116: }
117:
118: ///summary>
119: ///檢查字符串中是否包含Sql注入關(guān)鍵字
120: /// param name="_key">被檢查的字符串/param>
121: /// returns>如果包含注入true;否則返回false/returns>
122: ////summary>
123: private static bool CheckKeyWord(string _key)
124: {
125: string[] pattenString = StrKeyWord.Split('|');
126: string[] pattenRegex = StrRegex.Split('|');
127: foreach (string sqlParam in pattenString)
128: {
129: if (_key.Contains(sqlParam + " ") || _key.Contains(" " + sqlParam))
130: {
131: return true;
132: }
133: }
134: foreach (string sqlParam in pattenRegex)
135: {
136: if (_key.Contains(sqlParam))
137: {
138: return true;
139: }
140: }
141: return false;
142:
143: }
144: ///summary>
145: ///檢查URL中是否包含Sql注入
146: /// param name="_request">當(dāng)前HttpRequest對(duì)象/param>
147: /// returns>如果包含注入true;否則返回false/returns>
148: ////summary>
149: public bool CheckRequestQuery()
150: {
151: if (request.QueryString.Count > 0)
152: {
153: foreach (string sqlParam in this.request.QueryString)
154: {
155: if (sqlParam == "__VIEWSTATE") continue;
156: if (sqlParam == "__EVENTVALIDATION") continue;
157: if (CheckKeyWord(request.QueryString[sqlParam].ToLower()))
158: {
159: return true;
160: }
161: }
162: }
163: return false;
164: }
165: ///summary>
166: ///檢查提交的表單中是否包含Sql注入
167: /// param name="_request">當(dāng)前HttpRequest對(duì)象/param>
168: /// returns>如果包含注入true;否則返回false/returns>
169: ////summary>
170: public bool CheckRequestForm()
171: {
172: if (request.Form.Count > 0)
173: {
174: foreach (string sqlParam in this.request.Form)
175: {
176: if (sqlParam == "__VIEWSTATE") continue;
177: if (sqlParam == "__EVENTVALIDATION") continue;
178: if (CheckKeyWord(request.Form[sqlParam]))
179: {
180: return true;
181: }
182: }
183: }
184: return false;
185: }
186: }
過(guò)濾類是在某前輩的作品基礎(chǔ)上改的,很抱歉我已經(jīng)找不到最原始的出處了。需要在Web.Config中添加防SQL注入的特征字符集:
標(biāo)簽:貸款群呼 河源 宜春 濟(jì)寧 黃山 中衛(wèi) 新余 金昌
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《T-SQL篇如何防止SQL注入的解決方法》,本文關(guān)鍵詞 T-SQL,篇,如何,防止,SQL,注入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。