危险字符过滤的类
2010-01-21 20:35 观海看云 阅读(100) 评论(0) 收藏 举报
using System;
 using System.IO;
using System.IO;
 using System.Text;
using System.Text;
 using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
 using System.Runtime.Remoting;
using System.Runtime.Remoting;
 using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Proxies;
 using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Messaging;
 using System.Reflection;
using System.Reflection;

 namespace FilterRealProxy
namespace FilterRealProxy
 {
{
 /// <summary>
 /// <summary>
 ///  FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。
 ///  FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。
 /// </summary>
 /// </summary>
 public class FilterRealProxy:RealProxy
 public class FilterRealProxy:RealProxy
 {
 {
 private MarshalByRefObject target;
  private MarshalByRefObject target;
 public FilterRealProxy(MarshalByRefObject target):base(target.GetType())
  public FilterRealProxy(MarshalByRefObject target):base(target.GetType())
 {
  {
 this.target=target;
   this.target=target;    
 }
  }
 public override IMessage Invoke(IMessage msg)
  public override IMessage Invoke(IMessage msg)
 {
  {
 IMethodCallMessage callMsg=msg as IMethodCallMessage;
   IMethodCallMessage callMsg=msg as IMethodCallMessage;
 IMethodReturnMessage returnMsg = RemotingServices.ExecuteMessage(target,callMsg);
   IMethodReturnMessage returnMsg = RemotingServices.ExecuteMessage(target,callMsg);
 //检查返回值是否为String,如果不是String,就没必要进行过滤
   //检查返回值是否为String,如果不是String,就没必要进行过滤
 if(this.IsMatchType(returnMsg.ReturnValue))
   if(this.IsMatchType(returnMsg.ReturnValue))
 {
   {
 string returnValue=this.Filter(returnMsg.ReturnValue.ToString(),returnMsg.MethodName);
    string returnValue=this.Filter(returnMsg.ReturnValue.ToString(),returnMsg.MethodName);            
 return new ReturnMessage(returnValue,null,0,null,callMsg);
    return new ReturnMessage(returnValue,null,0,null,callMsg);
 }
   }
 return returnMsg;
   return returnMsg;
 }
     }
 protected string Filter(string ReturnValue,string MethodName)
  protected string Filter(string ReturnValue,string MethodName)
 {
  {
 MethodInfo methodInfo=target.GetType().GetMethod(MethodName);
   MethodInfo methodInfo=target.GetType().GetMethod(MethodName);
 object[] attributes=methodInfo.GetCustomAttributes(typeof(StringFilter),true);
   object[] attributes=methodInfo.GetCustomAttributes(typeof(StringFilter),true);
 foreach (object attrib in attributes)
   foreach (object attrib in attributes)
 {
   {
 return FilterHandler.Process(((StringFilter)attrib).FilterType,ReturnValue);
    return FilterHandler.Process(((StringFilter)attrib).FilterType,ReturnValue);
 }
   }
 return ReturnValue;
   return ReturnValue;
 }
  }
 protected bool IsMatchType(object obj)
  protected bool IsMatchType(object obj)
 {
  {
 return obj is System.String;
   return obj is System.String;
 }
  }
 }
 }

 ///<summary>
 ///<summary>
 ///  StringFilter类:自定义属性类, 定义目标元素的过滤类型
 ///  StringFilter类:自定义属性类, 定义目标元素的过滤类型 
 ///</summary>
 ///</summary>
 public class StringFilter:Attribute
 public class StringFilter:Attribute
 {
 {
 protected FilterType _filterType;
  protected FilterType _filterType;

 public StringFilter(FilterType filterType)
  public StringFilter(FilterType filterType)
 {
  {
 this._filterType=filterType;
   this._filterType=filterType;
 }
  }
 public FilterType FilterType
  public FilterType FilterType
 {
  {
 get
   get
 {
   {
 return _filterType;
    return _filterType;
 }
   }
 }
  }
 }
 }

 /// <summary>
 /// <summary>
 /// 枚举类:用于指定过滤类型,例如:对script过滤还是对html进行过滤?
 /// 枚举类:用于指定过滤类型,例如:对script过滤还是对html进行过滤?
 /// </summary>
 /// </summary>
 [Flags()]
 [Flags()]
 public enum FilterType
 public enum FilterType
 {
 {
 Script = 1,
  Script = 1,
 Html =2,
  Html =2,
 Object=3,
  Object=3,
 AHrefScript=4,
  AHrefScript=4,
 Iframe=5,
  Iframe=5,
 Frameset=6,
  Frameset=6,
 Src=7,
  Src=7,
 BadWords=8,
  BadWords=8,
 //Include=9,
  //Include=9,
 All=16
  All=16
 }
 }

 ///<summary>
 ///<summary>
 /// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。
 /// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。
 ///</summary>
 ///</summary>
 
 
 public class FilterHandler
 public class FilterHandler
 {
 {
 private FilterHandler()
  private FilterHandler()
 {
  {
 }
  }
 public static string Process(FilterType filterType,string filterContent)
  public static string Process(FilterType filterType,string filterContent)
 {
  {
 switch(filterType)
   switch(filterType)
 {
   {
 case FilterType.Script:
    case FilterType.Script:
 filterContent=FilterScript(filterContent);
     filterContent=FilterScript(filterContent);
 break;
     break;
 case FilterType.Html:
    case FilterType.Html:
 filterContent=FilterHtml(filterContent);
     filterContent=FilterHtml(filterContent);
 break;
     break;
 case FilterType.Object:
    case FilterType.Object:
 filterContent=FilterObject(filterContent);
     filterContent=FilterObject(filterContent);
 break;
     break;
 case FilterType.AHrefScript:
    case FilterType.AHrefScript:
 filterContent=FilterAHrefScript(filterContent);
     filterContent=FilterAHrefScript(filterContent);
 break;
     break;
 case FilterType.Iframe:
    case FilterType.Iframe:
 filterContent=FilterIframe(filterContent);
     filterContent=FilterIframe(filterContent);
 break;
     break;
 case FilterType.Frameset:
    case FilterType.Frameset:
 filterContent=FilterFrameset(filterContent);
     filterContent=FilterFrameset(filterContent);
 break;
     break;
 case FilterType.Src:
    case FilterType.Src:
 filterContent=FilterSrc(filterContent);
     filterContent=FilterSrc(filterContent);
 break;
     break;
 //case FilterType.Include:
    //case FilterType.Include:
 // filterContent=FilterInclude(filterContent);
    // filterContent=FilterInclude(filterContent);
 // break;
    // break;
 case FilterType.BadWords:
    case FilterType.BadWords:
 filterContent=FilterBadWords(filterContent);
     filterContent=FilterBadWords(filterContent);
 break;
     break;
 case FilterType.All:
    case FilterType.All:
 filterContent=FilterAll(filterContent);
     filterContent=FilterAll(filterContent);
 break;
     break;
 default:
    default:
 //do nothing
     //do nothing
 break;
     break;
 }
   }
 return filterContent;
   return filterContent;
 }
  }

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

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

 private static string StripScriptAttributesFromTags( string content )
  private static string StripScriptAttributesFromTags( string content )
 {
  {
 string eventAttribs = @"on(blur|c(hange|lick)|dblclick|focus|keypress|(key|mouse)(down|up)|(un)?load
   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))" ;
                    |mouse(move|o(ut|ver))|reset|s(elect|ubmit))" ;
 
    
 string pattern = String.Format(@"(?inx)
   string pattern = String.Format(@"(?inx)
 \<(\w+)\s+
        \<(\w+)\s+
 (
            (
 (?'attribute'
                (?'attribute'
 (?'attributeName'{0})\s*=\s*
                (?'attributeName'{0})\s*=\s*
 (?'delim'['""]?)
                (?'delim'['""]?)
 (?'attributeValue'[^'"">]+)
                (?'attributeValue'[^'"">]+)
 (\3)
                (\3)
 )
            )
 |
            |
 (?'attribute'
            (?'attribute'
 (?'attributeName'href)\s*=\s*
                (?'attributeName'href)\s*=\s*
 (?'delim'['""]?)
                (?'delim'['""]?)
 (?'attributeValue'javascript[^'"">]+)
                (?'attributeValue'javascript[^'"">]+)
 (\3)
                (\3)
 )
            )
 |
            |
 [^>]
            [^>]
 )*
        )*
 \>", eventAttribs ) ;
    \>", eventAttribs ) ;
 Regex re = new Regex( pattern ) ;
   Regex re = new Regex( pattern ) ;
 // 使用MatchEvaluator的委托
   // 使用MatchEvaluator的委托
 return re.Replace( content, new MatchEvaluator( StripAttributesHandler ) ) ;
   return re.Replace( content, new MatchEvaluator( StripAttributesHandler ) ) ;
 }
  }

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

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

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

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

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

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

 //移除非法或不友好字符
  //移除非法或不友好字符
 private static string FilterBadWords(string chkStr)
  private static string FilterBadWords(string chkStr)
 {
  {
 //这里的非法和不友好字符由你任意加,用“|”分隔,支持正则表达式,由于本Blog禁止贴非法和不友好字符,所以这里无法加上。
    //这里的非法和不友好字符由你任意加,用“|”分隔,支持正则表达式,由于本Blog禁止贴非法和不友好字符,所以这里无法加上。
 string BadWords=@"
string BadWords=@" ";
";
 if (chkStr == "")
   if (chkStr == "")
 {
   {
 return "";
    return "";
 }
   }

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

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

 using System.IO;
using System.IO; using System.Text;
using System.Text; using System.Text.RegularExpressions;
using System.Text.RegularExpressions; using System.Runtime.Remoting;
using System.Runtime.Remoting; using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Messaging; using System.Reflection;
using System.Reflection;
 namespace FilterRealProxy
namespace FilterRealProxy {
{ /// <summary>
 /// <summary> ///  FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。
 ///  FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。 /// </summary>
 /// </summary> public class FilterRealProxy:RealProxy
 public class FilterRealProxy:RealProxy {
 { private MarshalByRefObject target;
  private MarshalByRefObject target; public FilterRealProxy(MarshalByRefObject target):base(target.GetType())
  public FilterRealProxy(MarshalByRefObject target):base(target.GetType()) {
  { this.target=target;
   this.target=target;     }
  } public override IMessage Invoke(IMessage msg)
  public override IMessage Invoke(IMessage msg) {
  { IMethodCallMessage callMsg=msg as IMethodCallMessage;
   IMethodCallMessage callMsg=msg as IMethodCallMessage; IMethodReturnMessage returnMsg = RemotingServices.ExecuteMessage(target,callMsg);
   IMethodReturnMessage returnMsg = RemotingServices.ExecuteMessage(target,callMsg); //检查返回值是否为String,如果不是String,就没必要进行过滤
   //检查返回值是否为String,如果不是String,就没必要进行过滤 if(this.IsMatchType(returnMsg.ReturnValue))
   if(this.IsMatchType(returnMsg.ReturnValue)) {
   { string returnValue=this.Filter(returnMsg.ReturnValue.ToString(),returnMsg.MethodName);
    string returnValue=this.Filter(returnMsg.ReturnValue.ToString(),returnMsg.MethodName);             return new ReturnMessage(returnValue,null,0,null,callMsg);
    return new ReturnMessage(returnValue,null,0,null,callMsg); }
   } return returnMsg;
   return returnMsg; }
     } protected string Filter(string ReturnValue,string MethodName)
  protected string Filter(string ReturnValue,string MethodName) {
  { MethodInfo methodInfo=target.GetType().GetMethod(MethodName);
   MethodInfo methodInfo=target.GetType().GetMethod(MethodName); object[] attributes=methodInfo.GetCustomAttributes(typeof(StringFilter),true);
   object[] attributes=methodInfo.GetCustomAttributes(typeof(StringFilter),true); foreach (object attrib in attributes)
   foreach (object attrib in attributes) {
   { return FilterHandler.Process(((StringFilter)attrib).FilterType,ReturnValue);
    return FilterHandler.Process(((StringFilter)attrib).FilterType,ReturnValue); }
   } return ReturnValue;
   return ReturnValue; }
  } protected bool IsMatchType(object obj)
  protected bool IsMatchType(object obj) {
  { return obj is System.String;
   return obj is System.String; }
  } }
 }
 ///<summary>
 ///<summary> ///  StringFilter类:自定义属性类, 定义目标元素的过滤类型
 ///  StringFilter类:自定义属性类, 定义目标元素的过滤类型  ///</summary>
 ///</summary> public class StringFilter:Attribute
 public class StringFilter:Attribute {
 { protected FilterType _filterType;
  protected FilterType _filterType;
 public StringFilter(FilterType filterType)
  public StringFilter(FilterType filterType) {
  { this._filterType=filterType;
   this._filterType=filterType; }
  } public FilterType FilterType
  public FilterType FilterType {
  { get
   get {
   { return _filterType;
    return _filterType; }
   } }
  } }
 }
 /// <summary>
 /// <summary> /// 枚举类:用于指定过滤类型,例如:对script过滤还是对html进行过滤?
 /// 枚举类:用于指定过滤类型,例如:对script过滤还是对html进行过滤? /// </summary>
 /// </summary> [Flags()]
 [Flags()] public enum FilterType
 public enum FilterType {
 { Script = 1,
  Script = 1, Html =2,
  Html =2, Object=3,
  Object=3, AHrefScript=4,
  AHrefScript=4, Iframe=5,
  Iframe=5, Frameset=6,
  Frameset=6, Src=7,
  Src=7, BadWords=8,
  BadWords=8, //Include=9,
  //Include=9, All=16
  All=16 }
 }
 ///<summary>
 ///<summary> /// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。
 /// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。 ///</summary>
 ///</summary> 
  public class FilterHandler
 public class FilterHandler {
 { private FilterHandler()
  private FilterHandler() {
  { }
  } public static string Process(FilterType filterType,string filterContent)
  public static string Process(FilterType filterType,string filterContent) {
  { switch(filterType)
   switch(filterType) {
   { case FilterType.Script:
    case FilterType.Script: filterContent=FilterScript(filterContent);
     filterContent=FilterScript(filterContent); break;
     break; case FilterType.Html:
    case FilterType.Html: filterContent=FilterHtml(filterContent);
     filterContent=FilterHtml(filterContent); break;
     break; case FilterType.Object:
    case FilterType.Object: filterContent=FilterObject(filterContent);
     filterContent=FilterObject(filterContent); break;
     break; case FilterType.AHrefScript:
    case FilterType.AHrefScript: filterContent=FilterAHrefScript(filterContent);
     filterContent=FilterAHrefScript(filterContent); break;
     break; case FilterType.Iframe:
    case FilterType.Iframe: filterContent=FilterIframe(filterContent);
     filterContent=FilterIframe(filterContent); break;
     break; case FilterType.Frameset:
    case FilterType.Frameset: filterContent=FilterFrameset(filterContent);
     filterContent=FilterFrameset(filterContent); break;
     break; case FilterType.Src:
    case FilterType.Src: filterContent=FilterSrc(filterContent);
     filterContent=FilterSrc(filterContent); break;
     break; //case FilterType.Include:
    //case FilterType.Include: // filterContent=FilterInclude(filterContent);
    // filterContent=FilterInclude(filterContent); // break;
    // break; case FilterType.BadWords:
    case FilterType.BadWords: filterContent=FilterBadWords(filterContent);
     filterContent=FilterBadWords(filterContent); break;
     break; case FilterType.All:
    case FilterType.All: filterContent=FilterAll(filterContent);
     filterContent=FilterAll(filterContent); break;
     break; default:
    default: //do nothing
     //do nothing break;
     break; }
   } return filterContent;
   return filterContent; }
  }
 public static string FilterScript(string content)
  public static string FilterScript(string content) {
  { string commentPattern = @"(?'comment'<!--.*?--[ \n\r]*>)" ;
   string commentPattern = @"(?'comment'<!--.*?--[ \n\r]*>)" ; string embeddedScriptComments = @"(\/\*.*?\*\/|\/\/.*?[\n\r])" ;
   string embeddedScriptComments = @"(\/\*.*?\*\/|\/\/.*?[\n\r])" ; string scriptPattern = String.Format(@"(?'script'<[ \n\r]*script[^>]*>(.*?{0}?)*<[ \n\r]*/script[^>]*>)", embeddedScriptComments ) ;
   string scriptPattern = String.Format(@"(?'script'<[ \n\r]*script[^>]*>(.*?{0}?)*<[ \n\r]*/script[^>]*>)", embeddedScriptComments ) ; // 包含注释和Script语句
   // 包含注释和Script语句 string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, scriptPattern) ;
   string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, scriptPattern) ;
 return StripScriptAttributesFromTags(Regex.Replace(content,pattern,string.Empty,RegexOptions.IgnoreCase));
   return StripScriptAttributesFromTags(Regex.Replace(content,pattern,string.Empty,RegexOptions.IgnoreCase)); }
  }
 private static string StripScriptAttributesFromTags( string content )
  private static string StripScriptAttributesFromTags( string content ) {
  { string eventAttribs = @"on(blur|c(hange|lick)|dblclick|focus|keypress|(key|mouse)(down|up)|(un)?load
   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))" ;
                    |mouse(move|o(ut|ver))|reset|s(elect|ubmit))" ; 
     string pattern = String.Format(@"(?inx)
   string pattern = String.Format(@"(?inx) \<(\w+)\s+
        \<(\w+)\s+ (
            ( (?'attribute'
                (?'attribute' (?'attributeName'{0})\s*=\s*
                (?'attributeName'{0})\s*=\s* (?'delim'['""]?)
                (?'delim'['""]?) (?'attributeValue'[^'"">]+)
                (?'attributeValue'[^'"">]+) (\3)
                (\3) )
            ) |
            | (?'attribute'
            (?'attribute' (?'attributeName'href)\s*=\s*
                (?'attributeName'href)\s*=\s* (?'delim'['""]?)
                (?'delim'['""]?) (?'attributeValue'javascript[^'"">]+)
                (?'attributeValue'javascript[^'"">]+) (\3)
                (\3) )
            ) |
            | [^>]
            [^>] )*
        )* \>", eventAttribs ) ;
    \>", eventAttribs ) ; Regex re = new Regex( pattern ) ;
   Regex re = new Regex( pattern ) ; // 使用MatchEvaluator的委托
   // 使用MatchEvaluator的委托 return re.Replace( content, new MatchEvaluator( StripAttributesHandler ) ) ;
   return re.Replace( content, new MatchEvaluator( StripAttributesHandler ) ) ; }
  }
 private static string StripAttributesHandler( Match m )
  private static string StripAttributesHandler( Match m ) {
  { if( m.Groups["attribute"].Success  )
   if( m.Groups["attribute"].Success  ) {
   { return m.Value.Replace( m.Groups["attribute"].Value, "") ;
    return m.Value.Replace( m.Groups["attribute"].Value, "") ; }
   } else
   else {
   { return m.Value ;
    return m.Value ; }
   } }
  }
 public static string FilterAHrefScript(string content)
  public static string FilterAHrefScript(string content) {
  { string newstr=FilterScript(content);
   string newstr=FilterScript(content); string regexstr=@" href[ ^=]*= *[\s\S]*script *:";
   string regexstr=@" href[ ^=]*= *[\s\S]*script *:"; return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  }
 public static string FilterSrc(string content)
  public static string FilterSrc(string content) {
  { string newstr=FilterScript(content);
   string newstr=FilterScript(content); string regexstr=@" src *= *['""]?[^\.]+\.(js|vbs|asp|aspx|php|jsp)['""]";
   string regexstr=@" src *= *['""]?[^\.]+\.(js|vbs|asp|aspx|php|jsp)['""]"; return Regex.Replace(newstr,regexstr,@"",RegexOptions.IgnoreCase);
   return Regex.Replace(newstr,regexstr,@"",RegexOptions.IgnoreCase); }
  } /*
/* public static string FilterInclude(string content)
  public static string FilterInclude(string content) {
  { string newstr=FilterScript(content);
   string newstr=FilterScript(content); string regexstr=@"<[\s\S]*include *(file|virtual) *= *[\s\S]*\.(js|vbs|asp|aspx|php|jsp)[^>]*>";
   string regexstr=@"<[\s\S]*include *(file|virtual) *= *[\s\S]*\.(js|vbs|asp|aspx|php|jsp)[^>]*>"; return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  } */
*/ public static string FilterHtml(string content)
  public static string FilterHtml(string content) {
  { string newstr=FilterScript(content);
   string newstr=FilterScript(content); string regexstr=@"<[^>]*>";
   string regexstr=@"<[^>]*>"; return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  }
 public static string FilterObject(string content)
  public static string FilterObject(string content) {
  { string regexstr=@"(?i)<Object([^>])*>(\w|\W)*</Object([^>])*>";
   string regexstr=@"(?i)<Object([^>])*>(\w|\W)*</Object([^>])*>"; return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  }
 public static string FilterIframe(string content)
  public static string FilterIframe(string content) {
  { string regexstr=@"(?i)<Iframe([^>])*>(\w|\W)*</Iframe([^>])*>";
   string regexstr=@"(?i)<Iframe([^>])*>(\w|\W)*</Iframe([^>])*>"; return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  }
 public static string FilterFrameset(string content)
  public static string FilterFrameset(string content) {
  { string regexstr=@"(?i)<Frameset([^>])*>(\w|\W)*</Frameset([^>])*>";
   string regexstr=@"(?i)<Frameset([^>])*>(\w|\W)*</Frameset([^>])*>"; return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase);
   return Regex.Replace(content,regexstr,string.Empty,RegexOptions.IgnoreCase); }
  }
 //移除非法或不友好字符
  //移除非法或不友好字符 private static string FilterBadWords(string chkStr)
  private static string FilterBadWords(string chkStr) {
  { //这里的非法和不友好字符由你任意加,用“|”分隔,支持正则表达式,由于本Blog禁止贴非法和不友好字符,所以这里无法加上。
    //这里的非法和不友好字符由你任意加,用“|”分隔,支持正则表达式,由于本Blog禁止贴非法和不友好字符,所以这里无法加上。 string BadWords=@"
string BadWords=@" ";
"; if (chkStr == "")
   if (chkStr == "") {
   { return "";
    return ""; }
   }
 string[] bwords = BadWords.Split('#');
   string[] bwords = BadWords.Split('#'); int i,j;
   int i,j; string str;
   string str; StringBuilder sb = new StringBuilder();
   StringBuilder sb = new StringBuilder(); for(i = 0; i< bwords.Length; i++)
   for(i = 0; i< bwords.Length; i++) {
   { str=bwords[i].ToString().Trim();
    str=bwords[i].ToString().Trim(); string regStr,toStr;
    string regStr,toStr; regStr=str;
    regStr=str; Regex r=new Regex(regStr,RegexOptions.IgnoreCase | RegexOptions.Singleline| RegexOptions.Multiline);
    Regex r=new Regex(regStr,RegexOptions.IgnoreCase | RegexOptions.Singleline| RegexOptions.Multiline); Match m=r.Match(chkStr);
    Match m=r.Match(chkStr); if(m.Success)
    if(m.Success) {
    { j=m.Value.Length;
     j=m.Value.Length; sb.Insert(0,"*",j);
     sb.Insert(0,"*",j); toStr=sb.ToString();
     toStr=sb.ToString(); chkStr=Regex.Replace(chkStr,regStr,toStr,RegexOptions.IgnoreCase | RegexOptions.Singleline| RegexOptions.Multiline);
     chkStr=Regex.Replace(chkStr,regStr,toStr,RegexOptions.IgnoreCase | RegexOptions.Singleline| RegexOptions.Multiline);   }
    } sb.Remove(0,sb.Length);
    sb.Remove(0,sb.Length); }
   } return chkStr;
   return chkStr; }
  }
 public static string FilterAll(string content)
  public static string FilterAll(string content) {
  { content = FilterHtml(content);
   content = FilterHtml(content); content = FilterScript(content);
   content = FilterScript(content); content = FilterAHrefScript(content);
   content = FilterAHrefScript(content); content = FilterObject(content);
   content = FilterObject(content); content = FilterIframe(content);
   content = FilterIframe(content); content = FilterFrameset(content);
   content = FilterFrameset(content); content = FilterSrc(content);
   content = FilterSrc(content); content = FilterBadWords(content);
   content = FilterBadWords(content); //content = FilterInclude(content);
   //content = FilterInclude(content); return content;
   return content; }
  } }
 } }
}
    作者:观海看云(个人开发历程知识库 - 博客园)
出处:http://www.cnblogs.com/zhangtao/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/zhangtao/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 
                    
                     
                    
                 
                    
                
 
  
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号