XSS 攻击

1.为什么会产生XSS攻击
用户提交用户信息时提交 <script>xxx</script>
例子1 username 输入<script>alert("123")</script>


例子2 username 输入<script>alert("location.href='http.www.xxx.com'")</script>
2. 怎么解决XSS攻击?
将脚本转义然后html进行展示

举例:

package com.sunlala.controller;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.support.HttpRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Optional;

/**
 * Author:SunLala
 * Date: 2022/1/15
 * 功能描述:()
 */
public class XssHttpServletReqquest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    public XssHttpServletReqquest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }

    @Override
    public String getParameter(String name) {
        String parameter = request.getParameter(name);
        System.out.println("用户输入vaule"+parameter);
        if(Optional.ofNullable(parameter).isPresent()){
            parameter.replace("<","&lt");
            parameter.replace(">","&gt");
            parameter = StringEscapeUtils.escapeHtml4(parameter);
            System.out.println("过滤后的value"+parameter);
        }
        return parameter;
    }
}

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.sunlala.controller;

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;

public class XssFilter implements Filter {
    public XssFilter() {
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        XssHttpServletReqquest xssHttpServletReqquest = new XssHttpServletReqquest(request);
        filterChain.doFilter(xssHttpServletReqquest, servletResponse);
    }

    public void destroy() {
    }
}

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
    <filter>
        <filter-name>XssFilter</filter-name>
        <filter-class>com.sunlala.controller.XssFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>XssFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
上一篇:虚拟机centos7安装VMwareTools详细教程


下一篇:6.vmware tools的安装