危险字符过滤的类

本文介绍了一个使用C#实现的代码过滤器,通过代理模式拦截并过滤特定类型的字符串返回值,包括对HTML、JavaScript等的过滤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

None.gifusing System;
None.gif
using System.IO;
None.gif
using System.Text;
None.gif
using System.Text.RegularExpressions;
None.gif
using System.Runtime.Remoting;
None.gif
using System.Runtime.Remoting.Proxies;
None.gif
using System.Runtime.Remoting.Messaging;
None.gif
using System.Reflection;
None.gif
None.gif
namespace FilterRealProxy
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**//// <summary>
InBlock.gif 
///  FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。
ExpandedSubBlockEnd.gif 
/// </summary>

InBlock.gif public class FilterRealProxy:RealProxy
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
private MarshalByRefObject target;
InBlock.gif  
public FilterRealProxy(MarshalByRefObject target):base(target.GetType())
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
this.target=target;    
ExpandedSubBlockEnd.gif  }

InBlock.gif  
public override IMessage Invoke(IMessage msg)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   IMethodCallMessage callMsg
=msg as IMethodCallMessage;
InBlock.gif   IMethodReturnMessage returnMsg 
= RemotingServices.ExecuteMessage(target,callMsg);
InBlock.gif   
//检查返回值是否为String,如果不是String,就没必要进行过滤
InBlock.gif
   if(this.IsMatchType(returnMsg.ReturnValue))
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
string returnValue=this.Filter(returnMsg.ReturnValue.ToString(),returnMsg.MethodName);            
InBlock.gif    
return new ReturnMessage(returnValue,null,0,null,callMsg);
ExpandedSubBlockEnd.gif   }

InBlock.gif   
return returnMsg;
ExpandedSubBlockEnd.gif     }

InBlock.gif  
protected string Filter(string ReturnValue,string MethodName)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   MethodInfo methodInfo
=target.GetType().GetMethod(MethodName);
InBlock.gif   
object[] attributes=methodInfo.GetCustomAttributes(typeof(StringFilter),true);
InBlock.gif   
foreach (object attrib in attributes)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
return FilterHandler.Process(((StringFilter)attrib).FilterType,ReturnValue);
ExpandedSubBlockEnd.gif   }

InBlock.gif   
return ReturnValue;
ExpandedSubBlockEnd.gif  }

InBlock.gif  
protected bool IsMatchType(object obj)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
return obj is System.String;
ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**////<summary>
InBlock.gif 
///  StringFilter类:自定义属性类, 定义目标元素的过滤类型 
ExpandedSubBlockEnd.gif 
///</summary>

InBlock.gif public class StringFilter:Attribute
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
protected FilterType _filterType;
InBlock.gif
InBlock.gif  
public StringFilter(FilterType filterType)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
this._filterType=filterType;
ExpandedSubBlockEnd.gif  }

InBlock.gif  
public FilterType FilterType
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
get
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
return _filterType;
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**//// <summary>
InBlock.gif 
/// 枚举类:用于指定过滤类型,例如:对script过滤还是对html进行过滤?
ExpandedSubBlockEnd.gif 
/// </summary>

InBlock.gif [Flags()]
InBlock.gif 
public enum FilterType
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  Script 
= 1,
InBlock.gif  Html 
=2,
InBlock.gif  Object
=3,
InBlock.gif  AHrefScript
=4,
InBlock.gif  Iframe
=5,
InBlock.gif  Frameset
=6,
InBlock.gif  Src
=7,
InBlock.gif  BadWords
=8,
InBlock.gif  
//Include=9,
InBlock.gif
  All=16
ExpandedSubBlockEnd.gif }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**////<summary>
InBlock.gif 
/// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。
ExpandedSubBlockEnd.gif 
///</summary>

InBlock.gif 
InBlock.gif 
public class FilterHandler
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
private FilterHandler()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
ExpandedSubBlockEnd.gif  }

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

InBlock.gif   
return filterContent;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public static string FilterScript(string content)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
string commentPattern = @"(?'comment'<!--.*?--[ \n\r]*>)" ;
InBlock.gif   
string embeddedScriptComments = @"(\/\*.*?\*\/|\/\/.*?[\n\r])" ;
InBlock.gif   
string scriptPattern = String.Format(@"(?'script'<[ \n\r]*script[^>]*>(.*?{0}?)*<[ \n\r]*/script[^>]*>)", embeddedScriptComments ) ;
InBlock.gif   
// 包含注释和Script语句
InBlock.gif
   string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, scriptPattern) ;
InBlock.gif
InBlock.gif   
return StripScriptAttributesFromTags(Regex.Replace(content,pattern,string.Empty,RegexOptions.IgnoreCase));
ExpandedSubBlockEnd.gif  }

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

InBlock.gif
InBlock.gif  
private static string StripAttributesHandler( Match m )
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
if( m.Groups["attribute"].Success  )
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
return m.Value.Replace( m.Groups["attribute"].Value, "") ;
ExpandedSubBlockEnd.gif   }

InBlock.gif   
else
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    
return m.Value ;
ExpandedSubBlockEnd.gif   }

ExpandedSubBlockEnd.gif  }

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

InBlock.gif
InBlock.gif  
public static string FilterSrc(string content)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
string newstr=FilterScript(content);
InBlock.gif   
string regexstr=@" src *= *['""]?[^\.]+\.(js|vbs|asp|aspx|php|jsp)['""]";
InBlock.gif   
return Regex.Replace(newstr,regexstr,@"",RegexOptions.IgnoreCase);
ExpandedSubBlockEnd.gif  }

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

InBlock.gif  
public static string FilterHtml(string content)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
string newstr=FilterScript(content);
InBlock.gif   
string regexstr=@"<[^>]*>";
InBlock.gif   
return Regex.Replace(newstr,regexstr,string.Empty,RegexOptions.IgnoreCase);
ExpandedSubBlockEnd.gif  }

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

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

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

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

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

InBlock.gif    sb.Remove(
0,sb.Length);
ExpandedSubBlockEnd.gif   }

InBlock.gif   
return chkStr;
ExpandedSubBlockEnd.gif  }

InBlock.gif
InBlock.gif  
public static string FilterAll(string content)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   content 
= FilterHtml(content);
InBlock.gif   content 
= FilterScript(content);
InBlock.gif   content 
= FilterAHrefScript(content);
InBlock.gif   content 
= FilterObject(content);
InBlock.gif   content 
= FilterIframe(content);
InBlock.gif   content 
= FilterFrameset(content);
InBlock.gif   content 
= FilterSrc(content);
InBlock.gif   content 
= FilterBadWords(content);
InBlock.gif   
//content = FilterInclude(content);
InBlock.gif
   return content;
ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif }

ExpandedBlockEnd.gif}

None.gif
None.gif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值