XSS 공격에 대한 방어로 다음과 같은 필터를 적용하자.
xss 공격에 대한 설명은 아래 를 클릭하면 자세하게 나와 있다.
class CrossScriptingFilter
package config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class CrossScriptingFilter implements Filter { private FilterConfig filterConfig; private Logger logger =LogManager.getLogger(CrossScriptingFilter.class); public void init(FilterConfig filterConfig) throws ServletException { //logger.debug(" xss 필터 {} ", "init" ); this.filterConfig = filterConfig; } public void destroy() { //logger.debug(" xss 필터 {} ", "destroy" ); this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //logger.debug(" xss 필터 {} ", "doFilter" ); chain.doFilter(new RequestWrapper((HttpServletRequest) request), response); } }
class RequestWrapper
package config; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public final class RequestWrapper extends HttpServletRequestWrapper { public RequestWrapper(HttpServletRequest servletRequest) { super(servletRequest); } public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values==null) { return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { encodedValues[i] = cleanXSS(values[i]); } return encodedValues; } public String getParameter(String parameter) { String value = super.getParameter(parameter); if (value == null) { return null; } return cleanXSS(value); } public String getHeader(String name) { String value = super.getHeader(name); if (value == null) return null; return cleanXSS(value); } private String cleanXSS(String value) { //You'll need to remove the spaces from the html entities below value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); value = value.replaceAll("'", "& #39;"); value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("script", ""); return value; } }
web.xml
<filter> <filter-name>XSS</filter-name> <filter-class>config.CrossScriptingFilter</filter-class> </filter> <filter-mapping> <filter-name>XSS</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
제작 : macaronics.net
소스 : https://github.com/braverokmc79/jsp_sin
댓글 ( 4)
댓글 남기기