過濾危險字符的類(asp.net2.0)

^_^,是我從1.1複製到2.0的!
FilterRealProxy.cs文件

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Reflection;

 

/// <summary>
/// FilterRealProxy 的摘要說明一個真實代理, 攔截它所代理對象中方法的返回值,並對需要過濾的返回值進行過濾。
///

/// </summary>
public class FilterRealProxy:RealProxy
{
    private MarshalByRefObject target;
 public FilterRealProxy()
 {
  //
  // TODO: 在此處添加構造函數邏輯
  //
 }

    public FilterRealProxy(MarshalByRefObject target)
        : base(target.GetType())
    {
        this.target = target;
    }

    public override IMessage Invoke(IMessage msg)
    {
        IMethodCallMessage callMsg = msg as IMethodCallMessage;
        IMethodReturnMessage returnMsg = RemotingServices.ExecuteMessage(target, callMsg);
        //檢查返回值是否爲String,如果不是String,就沒必要進行過濾
        if (this.IsMatchType(returnMsg.ReturnValue))
        {
            string returnValue = this.Filter(returnMsg.ReturnValue.ToString(), returnMsg.MethodName);
            return new ReturnMessage(returnValue, null, 0, null, callMsg);
        }
        return returnMsg;
    }

    protected string Filter(string ReturnValue, string MethodName)
    {
        MethodInfo methodInfo = target.GetType().GetMethod(MethodName);
        object[] attributes = methodInfo.GetCustomAttributes(typeof(StringFilter), true);
        foreach (object attrib in attributes)
        {
            return FilterHandler.Process(((StringFilter)attrib).FilterType, ReturnValue);
        }
        return ReturnValue;
    }
    protected bool IsMatchType(object obj)
    {
        return obj is System.String;
    }

StringFilter.cs文件

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Reflection;

/// <summary>
/// StringFilter 的摘要說明:自定義屬性類, 定義目標元素的過濾類型
/// </summary>
public class StringFilter:Attribute
{
    protected FilterType _filterType;
 public StringFilter()
 {
  //
  // TODO: 在此處添加構造函數邏輯
  //
 }
    public StringFilter(FilterType filterType)
    {
        this._filterType = filterType;
    }
    public FilterType FilterType
    {
        get
        {
            return _filterType;
        }
    }
}

FilterType.cs 文件

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Reflection;

/// <summary>
/// FilterType 的摘要說明:枚舉類:用於指定過濾類型,例如:對script過濾還是對html進行過濾?
/// </summary>
[Flags()]
public enum FilterType
{
    Script = 1,
    Html = 2,
    Object = 3,
    AHrefScript = 4,
    Iframe = 5,
    Frameset = 6,
    Src = 7,
    BadWords = 8,
    //Include=9,
    All = 16
}

FilterHandler.cs文件

using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
using System.Reflection;

///<summary>
/// 過濾處理類:根據過濾類型,調用相應的過濾處理方法。
///</summary>

public class FilterHandler
{
    private FilterHandler()
    {
    }
    public static string Process(FilterType filterType, string filterContent)
    {
        switch (filterType)
        {
            case FilterType.Script:
                filterContent = FilterScript(filterContent);
                break;
            case FilterType.Html:
                filterContent = FilterHtml(filterContent);
                break;
            case FilterType.Object:
                filterContent = FilterObject(filterContent);
                break;
            case FilterType.AHrefScript:
                filterContent = FilterAHrefScript(filterContent);
                break;
            case FilterType.Iframe:
                filterContent = FilterIframe(filterContent);
                break;
            case FilterType.Frameset:
                filterContent = FilterFrameset(filterContent);
                break;
            case FilterType.Src:
                filterContent = FilterSrc(filterContent);
                break;
            //case FilterType.Include:
            // filterContent=FilterInclude(filterContent);
            // break;
            case FilterType.BadWords:
                filterContent = FilterBadWords(filterContent);
                break;
            case FilterType.All:
                filterContent = FilterAll(filterContent);
                break;
            default:
                //do nothing
                break;
        }
        return filterContent;
    }

    public static string FilterScript(string content)
    {
        string commentPattern = @"(?'comment'<!--.*?--[ /n/r]*>)";
        string embeddedScriptComments = @"(///*.*?/*//|////.*?[/n/r])";
        string scriptPattern = String.Format(@"(?'script'<[ /n/r]*script[^>]*>(.*?{0}?)*<[ /n/r]*/script[^>]*>)", embeddedScriptComments);
        // 包含註釋和Script語句
        string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, scriptPattern);

        return StripScriptAttributesFromTags(Regex.Replace(content, pattern, string.Empty, RegexOptions.IgnoreCase));
    }

    private static string StripScriptAttributesFromTags(string content)
    {
        string eventAttribs = @"on(blur|c(hange|lick)|dblclick|focus|keypress|(key|mouse)(down|up)|(un)?load
                    |mouse(move|o(ut|ver))|reset|s(elect|ubmit))";

        string pattern = String.Format(@"(?inx)
        /<(/w+)/s+
            (
                (?'attribute'
                (?'attributeName'{0})/s*=/s*
                (?'delim'['""]?)
                (?'attributeValue'[^'"">]+)
                (/3)
            )
            |
            (?'attribute'
                (?'attributeName'href)/s*=/s*
                (?'delim'['""]?)
                (?'attributeValue'javascript[^'"">]+)
                (/3)
            )
            |
            [^>]
        )*
    />", eventAttribs);
        Regex re = new Regex(pattern);
        // 使用MatchEvaluator的委託
        return re.Replace(content, new MatchEvaluator(StripAttributesHandler));
    }

    private static string StripAttributesHandler(Match m)
    {
        if (m.Groups["attribute"].Success)
        {
            return m.Value.Replace(m.Groups["attribute"].Value, "");
        }
        else
        {
            return m.Value;
        }
    }

    public static string FilterAHrefScript(string content)
    {
        string newstr = FilterScript(content);
        string regexstr = @" href[ ^=]*= *[/s/S]*script *:";
        return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    public static string FilterSrc(string content)
    {
        string newstr = FilterScript(content);
        string regexstr = @" src *= *['""]?[^/.]+/.(js|vbs|asp|aspx|php|jsp)['""]";
        return Regex.Replace(newstr, regexstr, @"", RegexOptions.IgnoreCase);
    }
    /**/
    /*
public static string FilterInclude(string content)
{
string newstr=FilterScript(content);
string regexstr=@"<[/s/S]*include *(file|virtual) *= *[/s/S]*/.(js|vbs|asp|aspx|php|jsp)[^>]*>";
return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase);
}
*/
    public static string FilterHtml(string content)
    {
        string newstr = FilterScript(content);
        string regexstr = @"<[^>]*>";
        return Regex.Replace(newstr, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    public static string FilterObject(string content)
    {
        string regexstr = @"(?i)<Object([^>])*>(/w|/W)*</Object([^>])*>";
        return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    public static string FilterIframe(string content)
    {
        string regexstr = @"(?i)<Iframe([^>])*>(/w|/W)*</Iframe([^>])*>";
        return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    public static string FilterFrameset(string content)
    {
        string regexstr = @"(?i)<Frameset([^>])*>(/w|/W)*</Frameset([^>])*>";
        return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
    }

    //移除非法或不友好字符
    private static string FilterBadWords(string chkStr)
    {
        //這裏的非法和不友好字符由你任意加,用“|”分隔,支持正則表達式,由於本Blog禁止貼非法和不友好字符,所以這裏無法加上。
        string BadWords = @"";
        if (chkStr == "")
        {
            return "";
        }

        string[] bwords = BadWords.Split('#');
        int i, j;
        string str;
        StringBuilder sb = new StringBuilder();
        for (i = 0; i < bwords.Length; i++)
        {
            str = bwords[i].ToString().Trim();
            string regStr, toStr;
            regStr = str;
            Regex r = new Regex(regStr, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
            Match m = r.Match(chkStr);
            if (m.Success)
            {
                j = m.Value.Length;
                sb.Insert(0, "*", j);
                toStr = sb.ToString();
                chkStr = Regex.Replace(chkStr, regStr, toStr, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
            }
            sb.Remove(0, sb.Length);
        }
        return chkStr;
    }

    public static string FilterAll(string content)
    {
        content = FilterHtml(content);
        content = FilterScript(content);
        content = FilterAHrefScript(content);
        content = FilterObject(content);
        content = FilterIframe(content);
        content = FilterFrameset(content);
        content = FilterSrc(content);
        content = FilterBadWords(content);
        //content = FilterInclude(content);
        return content;
    }
}

     花了不少時間找,花了不少時間複製。編譯通過後,在頁面中添加了個文本框輸入幾個html字符測試一下,彈出這麼錯誤:
應用程序中的服務器錯誤。

從客戶端(TextBox1="<html>women</html>")中檢測到有潛在危險的 Request.Form 值。

說明: 請求驗證過程檢測到有潛在危險的客戶端輸入值,對請求的處理已經中止。該值可能指示危及應用程序安全的嘗試,如跨站點的腳本攻擊。通過在 Page 指令或 配置節中設置 validateRequest=false 可以禁用請求驗證。但是,在這種情況下,強烈建議應用程序顯式檢查所有輸入。

異常詳細信息: System.Web.HttpRequestValidationException: 從客戶端(TextBox1="<html>women</html>")中檢測到有潛在危險的 Request.Form 值。

      悲呼哉!我僅想生成xml文件的時候不允許輸入html標記而已!忘了.net文本框本身就可以驗證一下了……

      不過這也是個好東西(雖然看不(大)懂)……這次也要用,配置成validateRequest=false 我也要用!呵呵……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章