filter防止xxs攻击

filter防止xxs攻击

什么是XSS攻击?

XSS攻击使用Javascript脚本注入进行攻击

例如在表单中注入:

注意:谷歌浏览器 已经防止了XSS攻击,为了演示效果,最好使用火狐浏览器

fromToXss.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


"Content-Type" content="text/html; charset=UTF-8">
Insert title here


    
"XssDemo" method="post"> "text" name="userName"> "submit">

XssDemo

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/XssDemo")
public class XssDemo extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        req.setAttribute("userName", userName);
        req.getRequestDispatcher("showUserName.jsp").forward(req, resp);
    }
    

}

代码: showUserName.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


"Content-Type" content="text/html; charset=UTF-8">
Insert title here


userName:${userName}


解决方案:

使用Fileter过滤器过滤器注入标签

XSSFilter

public class XssFiter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        XssAndSqlHttpServletRequestWrapper xssRequestWrapper = new XssAndSqlHttpServletRequestWrapper(req);
        chain.doFilter(xssRequestWrapper, response);
    }

    public void destroy() {

    }

}

 

XssAndSqlHttpServletRequestWrapper

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 防止XSS攻击
 */
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
    HttpServletRequest request;
    public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }
    @Override
    public String getParameter(String name) {
        String value = request.getParameter(name);
        System.out.println("name:" + name + "," + value);
        if (!StringUtils.isEmpty(value)) {
            // 转换Html
            value = StringEscapeUtils.escapeHtml4(value);
        }
        return value;
    }
}

 

posted @ 2019-02-20 09:07 动手的程序员 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(filter防止xxs攻击)