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;

namespace FilterRealProxy


{

/**//// <summary>
/// FilterRealProxy类:一个真实代理, 拦截它所代理对象中方法的返回值,并对需要过滤的返回值进行过滤。
/// </summary>
public class FilterRealProxy:RealProxy

{
private MarshalByRefObject target;
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;
}
}


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

{
protected FilterType _filterType;

public StringFilter(FilterType filterType)

{
this._filterType=filterType;
}
public FilterType FilterType

{
get

{
return _filterType;
}
}
}


/**//// <summary>
/// 枚举类:用于指定过滤类型,例如:对s cript过滤还是对HTML进行过滤?
/// </summary>
[Flags()]
public enum FilterType

{
s cript = 1,
HTML =2,
Object=3,
AHrefs cript=4,
Iframe=5,
Frameset=6,
Src=../../7,
Badwords=8,
//Include=9,
All=16
}


/**////<summary>
/// 过滤处理类:根据过滤类型,调用相应的过滤处理方法。
///</summary>
public class FilterHandler

{
private FilterHandler()

{
}
public static string Process(FilterType filterType,string filterContent)

{
switch(filterType)

{
case FilterType.s cript:
filterContent=Filters cript(filterContent);
break;
case FilterType.HTML:
filterContent=FilterHTML(filterContent);
break;
case FilterType.Object:
filterContent=FilterObject(filterContent);
break;
case FilterType.AHrefs cript:
filterContent=FilterAHrefs cript(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 Filters cript(string content)

{
string commentPattern = @"(?'comment'<!--.*?--[ \n\r]*>)" ;
string embeddeds criptComments = @"(\/\*.*?\*\/|\/\/.*?[\n\r])" ;
string s criptPattern = String.Format(@"(?'s cript'<[ \n\r]*s cript[^>]*>(.*?{0}?)*<[ \n\r]*/s cript[^>]*>)", embeddeds criptComments ) ;
// 包含注释和s cript语句
string pattern = String.Format(@"(?s)({0}|{1})", commentPattern, s criptPattern) ;

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

private static string Strips criptAttributesFromTags( 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'javas cript[^'"">]+)
(\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 FilterAHrefs cript(string content)

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

public static string FilterSrc(string content)

{
string newstr=Filters cript(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=Filters cript(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=Filters cript(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 = Filters cript(content);
content = FilterAHrefs cript(content);
content = FilterObject(content);
content = FilterIframe(content);
content = FilterFrameset(content);
content = FilterSrc(content);
content = FilterBadwords(content);
//content = FilterInclude(content);
return content;
}
}
}


危险字符过滤的类(完美版)[2]
//没有太多时间完善它了,那位大侠有空完善它一下,完善之后给我一份?
(阿山NET a3news(AT)hotmail.com http://www.vcsharp.com/) /?"

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
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;
using FilterRealProxy;

namespace FilterForm


{

/**//// <summary>
/// FilterFormTest 的摘要说明。
/// </summary>
public class FilterFormTest : System.Windows.Forms.Form

{
private System.Windows.Forms.Button btnFilter;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.TextBox MyTextBox;
private System.Windows.Forms.Button btnOpenFile;
private System.Windows.Forms.ListBox listBox1;

/**//// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public FilterFormTest()

{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();

//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}


/**//// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )

{
if( disposing )

{
if(components != null)

{
components.Dispose();
}
}
base.Dispose( disposing );
}


Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码

/**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()

{
this.MyTextBox = new System.Windows.Forms.TextBox();
this.btnFilter = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.btnOpenFile = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// MyTextBox
//
this.MyTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.MyTextBox.Location = new System.Drawing.Point(8, 8);
this.MyTextBox.Multiline = true;
this.MyTextBox.Name = "MyTextBox";
this.MyTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.MyTextBox.Size = new System.Drawing.Size(432, 360);
this.MyTextBox.TabIndex = 0;
this.MyTextBox.Text = "";
//
// btnFilter
//
this.btnFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnFilter.Location = new System.Drawing.Point(448, 232);
this.btnFilter.Name = "btnFilter";
this.btnFilter.Size = new System.Drawing.Size(88, 23);
this.btnFilter.TabIndex = 1;
this.btnFilter.Text = "去除危险字符";
this.btnFilter.Click += new System.EventHandler(this.btnFilter_Click);
//
// btnOpenFile
//
this.btnOpenFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnOpenFile.Location = new System.Drawing.Point(456, 48);
this.btnOpenFile.Name = "btnOpenFile";
this.btnOpenFile.TabIndex = 2;
this.btnOpenFile.Text = "打开文件";
this.btnOpenFile.Click += new System.EventHandler(this.btnOpenFile_Click);
//
// listBox1
//
this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.listBox1.ItemHeight = 12;

this.listBox1.Items.AddRange(new object[]
{
"s cript脚本",
"HTML代码",
"Object物件",
"链接脚本",
"Iframe内框架",
"Frameset框架",
"Src插入性脚本",
"非法字符",
"Include包含文件",
"以上所有"});
this.listBox1.Location = new System.Drawing.Point(448, 88);
this.listBox1.MultiColumn = true;
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(96, 124);
this.listBox1.TabIndex = 3;
//
// FilterFormTest
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(544, 381);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.btnOpenFile);
this.Controls.Add(this.btnFilter);
this.Controls.Add(this.MyTextBox);
this.Name = "FilterFormTest";
this.Text = "FilterFormTest";
this.ResumeLayout(false);

}
#endregion


/**//// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()

{
Application.Run(new FilterFormTest());
}

/**////<summary>
/// 实体类:该实体类必须从MarshalByRefObject继承,所以被过滤的实体类不能再从其他类继承或实现接口,这是使用透明代理的局限性。
///</summary>
public class Entry : MarshalByRefObject

{
public Entry()

{
}
public static Entry CreateInstance()

{
Entry entry=new Entry();
RealProxy realProxy = new FilterRealProxy.FilterRealProxy(entry);
object transparentProxy = realProxy.GetTransparentProxy();
return (Entry)transparentProxy;
}

private string _body;
public virtual string Body

{
[StringFilter((FilterType)16)]

get
{return _body;}

set
{_body = value;}
}
}

private void btnFilter_Click(object sender, System.EventArgs e)

{
Entry en=Entry.CreateInstance();
en.Body = MyTextBox.Text;
MyTextBox.Text=en.Body;
}

private void btnOpenFile_Click(object sender, System.EventArgs e)

{
OpenFileDialog dlgFile=new OpenFileDialog();
dlgFile.Filter="HTML(*.htm)|*.htm|Text(*.txt)|*.txt|All Files(*.*)|*.*";
if(dlgFile.ShowDialog() == DialogResult.OK)

{
System.IO.StreamReader sr=new System.IO.StreamReader(dlgFile.FileName,System.Text.Encoding.Default);//得到一个含有s cript脚本的字符串
MyTextBox.Text = sr.ReadToEnd();
sr.Close();
}
}

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{
}
}
}


posted on
2007-02-12 14:05
mbskys
阅读(
113)
评论()
收藏
举报