1. 程式人生 > >web安全與防禦

web安全與防禦

一、釣魚網站之XSS攻擊原理分析

將表單提交的指令碼:<script>for(var i=0;i<3;i++){alert("彈死你"+i);}</script> 中的特殊字元進行轉義,禁止指令碼執行。


pom.xml引入common-lang包

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

/**
 * xss過濾器
 * Created by yz on 2018/4/9.
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    /**
* 將request中的value值重寫一下,將一些指令碼引數 非法引數轉換成html元素執行 * @param name * @return */ @Override public String getParameter(String name) { String value = this.request.getParameter(name); if(!StringUtils.isEmpty(value)){ System.out.println("轉換前 value:"+value); value = StringEscapeUtils.escapeHtml
(value); System.out.println("轉換後 value:"+value); } return value; } }
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by yz on 2018/4/9.
 */
@Component
public class XssFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化方法...");
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("正常攔截請求...");
        HttpServletRequest req = (HttpServletRequest) request;
        XssHttpServletRequestWrapper xssWrapper = new XssHttpServletRequestWrapper(req);
        filterChain.doFilter(xssWrapper,response);
    }

    /**
     * 只執行一次
     */
    @Override
    public void destroy() {
        System.out.println("銷燬請求...");
    }
}
/**
 * Created by yz on 2018/4/9.
 */
@Controller
public class IndexController {

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request){
        String name = request.getParameter("name");
        System.out.println(name);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name",name);
        modelAndView.setViewName("index");
        return modelAndView;
    }
}

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by yz on 2018/4/9.
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

index.jsp

<%@ page contentType="text/html; charset=UTF-8" language="java"%>
<html>
<body>
<h2>Hello World!</h2>
<form name="form" method="post" action="<%=request.getContextPath() %>/index">
    <input type="text" name="name">
    <input type="submit" name="submit" value="提交">
</form>
name:${name}

<h3>我是A頁面</h3>
<img alt="" src="/log.png">
</body>
</html>



二、web安全之圖片防盜鏈


三、表單操作資料庫SQL注入