[ Java ] XSS 2
포스트
취소

[ Java ] XSS 2

취약한 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package kr.co.openeg.lab.test.controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class XSSController {

	@RequestMapping(value="/test/xss_test.do", method = RequestMethod.POST)
	@ResponseBody
	public String testXss(HttpServletRequest request) {
		StringBuffer buffer=new StringBuffer();
		String input=request.getParameter("data");
		buffer.append(input);
        return buffer.toString();
	}
}	 



취약점 분석


1
buffer.append(input);

해당 코드에서 XSS 취약점이 발생한다.

Spring Framework에서는 HtmlUtils 클래스를 통해 XSS(Cross-Site Scripting) 취약점을 방지하기 위한 HTML 이스케이프 처리를 수행할 수 있다.



안전한 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package kr.co.openeg.lab.test.controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

@Controller
public class XSSController {

    @RequestMapping(value = "/test/xss_test.do", method = RequestMethod.POST)
    @ResponseBody
    public String testXss(HttpServletRequest request) {
        String input = request.getParameter("data");
        String escapedInput = HtmlUtils.htmlEscape(input);
        return escapedInput;
    }
}