项目中防御xss攻击
###1.什么是XSS攻击
XSS攻击全称是跨站脚本攻击,是经常出现在web应用中的安全漏洞,它允许恶意web用户将代码植入到页面中,比如:sql脚本,srcipt脚本,或者html代码。
黑客界共识是:跨站脚本攻击是新型的缓冲区溢出攻击。
例如:在页面输入一个转账的sql或者js脚本,然后发给后台,后台接收浏览器参数,没有任何校验,接着执行了该脚本,造成数据被篡改。
###2.如何防御XSS攻击
我的项目是springboot项目,要防御XSS攻击只需要增加一个filter,然后在filter中包装http请求。
Talk is cheap,show me the code!
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by shaomaolin on 2018/9/6. */ @WebFilter(urlPatterns = "/*", filterName = "XssFilter") public class XssFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse servletResponse = (HttpServletResponse)response; servletResponse.setHeader("Set-Cookie", "name=value; HttpOnly"); chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), servletResponse); } @Override public void destroy() { } } import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.JavaScriptUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * Created by shaomaolin on 2018/9/6. */ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{ public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } 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 (StringUtils.isBlank(value)) return null; return cleanXSS(value); } private String cleanXSS(String value) { if (StringUtils.isNotBlank(value)) { value = HtmlUtils.htmlEscape(value); value = JavaScriptUtils.javaScriptEscape(value); value = StringEscapeUtils.escapeSql(value); } return value; } }
相关推荐
sswqycbailong 2020-07-28
csxiaoqiang 2020-07-26
码农成长记 2020-07-19
layloge 2020-07-05
layloge 2020-06-26
liangjielaoshi 2020-06-25
csxiaoqiang 2020-06-16
某先生 2020-06-13
ItBJLan 2020-06-11
layloge 2020-06-07
csxiaoqiang 2020-06-03
sswqycbailong 2020-06-01
layloge 2020-05-30
码农成长记 2020-05-28
qidu 2020-05-26
zhuangnet 2020-05-20
zhuangnet 2020-05-19
xiaoemo0 2020-05-16
码农成长记 2020-05-10