當然不能用 HtmlEncode 和 HtmlDecode 方法,因為這樣連基本的html代碼會被禁止掉。
我在網上搜索,也沒有找到好的解決辦法,倒是收集了一些腳本攻擊的實例:
1. <script>標記中包含的代碼
2. <a href=javascript:...中的代碼
3. 其它基本控件的 on...事件中的代碼
4. iframe 和 frameset 中載入其它頁面造成的攻擊
有了這些資料后,事情就簡單多了,寫一個簡單的方法,用正則表達式把以上符合幾點的代碼替換掉:
public string wipeScript(string html)
{
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //過濾<script></script>標記
html = regex2.Replace(html, ""); //過濾href=javascript: (<A>) 屬性
html = regex3.Replace(html, " _disibledevent="); //過濾其它控件的on...事件
html = regex4.Replace(html, ""); //過濾iframe
html = regex5.Replace(html, ""); //過濾frameset
return html;
}
此方法輸入可能包含腳本的html代碼,返回則就是干凈的代碼了。
我做過一些簡單的測試,可以滿中要求,只是還存在幾個疑問:
以上考濾的情況是否比較完善, 還存在其它的腳本攻擊手段嗎?
是否會有其它更好的解決辦法?
作者Blog:http://blog.csdn.net/yolle/
