XSS Filter实现

下面的filter主要是解决防止XSS攻击

一个是Filter负责将请求的request包装一下。

转自CSDN ,MARK下链接:

http://blog.csdn.net/yuwenruli/article/details/6870753

另外还看到一个实现:

http://www.stripesframework.org/display/stripes/XSS+filter

核心代码:

public class SafeHtmlUtil
{
	public static String sanitize(String raw)
	{
		if (raw==null || raw.length()==0)
			return raw;

		return HTMLEntityEncode(canonicalize(raw));
	}


	private static Pattern scriptPattern = new Pattern("script", REFlags.IGNORE_CASE);
	private static Replacer scriptReplacer = scriptPattern.replacer("script");

	public static String HTMLEntityEncode(String input)
	{
		String next = scriptReplacer.replace(input);

		StringBuffer sb = new StringBuffer();
		for ( int i = 0; i < next.length(); ++i )
		{
			char ch = next.charAt( i );

			if (ch=='<')
				sb.append("&lt;");
			else if (ch=='>')
				sb.append("&gt;");
			else
				sb.append(ch);
		}

		return sb.toString();
	}


	// "Simplifies input to its simplest form to make encoding tricks more difficult"
	// though it didn't do seem to do anything to hex or html encoded characters... *shrug* maybe for unicode?
	public static String canonicalize( String input )
	{
		String canonical = sun.text.Normalizer.normalize( input, Normalizer.DECOMP, 0 );
		return canonical;
	}

还在googlecode上面开到一个开源项目:OWASP

http://code.google.com/p/owasp-esapi-java/

相关推荐