Skip to content

πŸ›‘οΈ Sentinel: [CRITICAL] Fix RCE in PDF compilation#210

Open
anchapin wants to merge 2 commits intomainfrom
sentinel/pdf-compilation-no-shell-escape-6615092504026383693
Open

πŸ›‘οΈ Sentinel: [CRITICAL] Fix RCE in PDF compilation#210
anchapin wants to merge 2 commits intomainfrom
sentinel/pdf-compilation-no-shell-escape-6615092504026383693

Conversation

@anchapin
Copy link
Copy Markdown
Owner

@anchapin anchapin commented Mar 25, 2026

🚨 Severity: CRITICAL
πŸ’‘ Vulnerability: The CoverLetterGenerator and PDFConverter classes were using pdflatex and pandoc to compile LaTeX source into PDFs. However, they lacked the -no-shell-escape flag and a subprocess timeout. This allows an attacker (or hallucinating AI) to inject LaTeX code capable of executing arbitrary shell commands via \write18 or perform Local File Inclusion (LFI). Additionally, an untrusted compilation could cause infinite loops resulting in Denial of Service (DoS).
🎯 Impact: A user generating a cover letter from an AI output or converting a manipulated .tex file could experience a full Remote Code Execution (RCE) on their machine, or a complete process hang.
πŸ”§ Fix: Added the -no-shell-escape flag to both pdflatex directly and pandoc (via --pdf-engine-opt=-no-shell-escape). Also added a 30-second timeout to process.communicate(timeout=30), gracefully catching the exception to kill the process to prevent zombie processes.
βœ… Verification: Ran pytest tests/test_pdf_security.py and pytest tests/test_cover_letter_security.py to ensure the vulnerability is mitigated. Also executed the full pytest suite ensuring 681 tests pass cleanly.


PR created automatically by Jules for task 6615092504026383693 started by @anchapin

Summary by Sourcery

Harden LaTeX-based PDF generation against remote code execution and hangs in both cover letter generation and generic PDF conversion flows.

Bug Fixes:

  • Prevent LaTeX and pandoc PDF compilation from executing arbitrary shell commands by disabling shell escape in pdflatex and the pandoc PDF engine.
  • Mitigate potential denial-of-service from untrusted LaTeX input by enforcing a timeout on external PDF compilation processes and aborting on long-running jobs.

Co-authored-by: anchapin <6326294+anchapin@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

πŸ‘‹ Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a πŸ‘€ emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Mar 25, 2026

Reviewer's Guide

Hardened LaTeX→PDF compilation in both the cover letter generator and generic PDF converter by disabling shell escapes and adding timeouts to external pdflatex/pandoc calls to prevent RCE and DoS.

Sequence diagram for secured LaTeX to PDF compilation with timeout

sequenceDiagram
    actor User
    participant CoverLetterGenerator
    participant PDFConverter
    participant Subprocess as subprocess_Popen

    User->>CoverLetterGenerator: generate_cover_letter()
    CoverLetterGenerator->>CoverLetterGenerator: _compile_pdf(output_path, tex_content)
    CoverLetterGenerator->>Subprocess: Popen(["pdflatex", "-interaction=nonstopmode", "-no-shell-escape", tex_path.name])
    Note over Subprocess: Start pdflatex process in tex_path.parent
    CoverLetterGenerator->>Subprocess: communicate(timeout=30)
    alt pdflatex completes in time
        Subprocess-->>CoverLetterGenerator: stdout, stderr
        alt returncode == 0 or PDF exists
            CoverLetterGenerator-->>User: pdf_created = True
        else pdflatex fails
            CoverLetterGenerator->>Subprocess: Popen(["pandoc", tex_path, "-o", output_path, "--pdf-engine=xelatex", "--pdf-engine-opt=-no-shell-escape"])
            Note over Subprocess: Start pandoc process
            CoverLetterGenerator->>Subprocess: communicate(timeout=30)
            alt pandoc completes in time
                Subprocess-->>CoverLetterGenerator: stdout, stderr
                alt returncode == 0 or PDF exists
                    CoverLetterGenerator-->>User: pdf_created = True
                else pandoc fails
                    CoverLetterGenerator-->>User: pdf_created = False
                end
            else pandoc times out
                CoverLetterGenerator->>Subprocess: kill()
                Subprocess-->>CoverLetterGenerator: communicate()
                CoverLetterGenerator-->>User: pdf_created = False
            end
        end
    else pdflatex times out
        CoverLetterGenerator->>Subprocess: kill()
        Subprocess-->>CoverLetterGenerator: communicate()
        Note over CoverLetterGenerator: Abort pdflatex path
        CoverLetterGenerator->>Subprocess: Popen(["pandoc", tex_path, "-o", output_path, "--pdf-engine=xelatex", "--pdf-engine-opt=-no-shell-escape"])
        CoverLetterGenerator->>Subprocess: communicate(timeout=30)
        alt pandoc completes in time
            Subprocess-->>CoverLetterGenerator: stdout, stderr
            alt returncode == 0 or PDF exists
                CoverLetterGenerator-->>User: pdf_created = True
            else pandoc fails
                CoverLetterGenerator-->>User: pdf_created = False
            end
        else pandoc times out
            CoverLetterGenerator->>Subprocess: kill()
            Subprocess-->>CoverLetterGenerator: communicate()
            CoverLetterGenerator-->>User: pdf_created = False
        end
    end

    User->>PDFConverter: convert_to_pdf(tex_path, output_path)
    PDFConverter->>PDFConverter: _compile_pdflatex(tex_path, working_dir, output_path)
    PDFConverter->>Subprocess: Popen(["pdflatex", "-interaction=nonstopmode", "-no-shell-escape", tex_path.name])
    PDFConverter->>Subprocess: communicate(timeout=30)
    alt pdflatex completes and succeeds
        Subprocess-->>PDFConverter: stdout, stderr
        PDFConverter-->>User: True
    else pdflatex fails or times out
        opt timeout path
            PDFConverter->>Subprocess: kill()
            Subprocess-->>PDFConverter: communicate()
        end
        PDFConverter->>PDFConverter: _compile_pandoc(tex_path, working_dir, output_path)
        PDFConverter->>Subprocess: Popen(["pandoc", tex_path, "-o", output_path, "--pdf-engine=xelatex", "--pdf-engine-opt=-no-shell-escape"])
        PDFConverter->>Subprocess: communicate(timeout=30)
        alt pandoc completes and succeeds
            Subprocess-->>PDFConverter: stdout, stderr
            PDFConverter-->>User: True
        else pandoc fails or times out
            opt timeout path
                PDFConverter->>Subprocess: kill()
                Subprocess-->>PDFConverter: communicate()
            end
            PDFConverter-->>User: False
        end
    end
Loading

Updated class diagram for secure PDF compilation helpers

classDiagram
    class CoverLetterGenerator {
        +_compile_pdf(output_path Path, tex_content str) bool
    }

    class PDFConverter {
        +_compile_pdflatex(tex_path Path, working_dir Path, output_path Path) bool
        +_compile_pandoc(tex_path Path, working_dir Path, output_path Path) bool
    }

    class SubprocessWrapper {
        +run_pdflatex(tex_path Path, working_dir Path, output_path Path) bool
        +run_pandoc(tex_path Path, working_dir Path, output_path Path) bool
        -NO_SHELL_ESCAPE_FLAG str
        -TIMEOUT_SECONDS int
    }

    CoverLetterGenerator ..> SubprocessWrapper : uses
    PDFConverter ..> SubprocessWrapper : uses

    class ExternalTool {
        <<interface>>
        +name str
    }

    class Pdflatex {
        +name str
        +flags str[]
    }

    class Pandoc {
        +name str
        +flags str[]
    }

    SubprocessWrapper ..> ExternalTool : invokes
    Pdflatex ..|> ExternalTool
    Pandoc ..|> ExternalTool
Loading

File-Level Changes

Change Details Files
Harden pdflatex invocation in cover letter PDF compilation to prevent RCE and hangs.
  • Add -no-shell-escape flag to pdflatex invocation used for cover letter compilation
  • Wrap process.communicate with a 30-second timeout and handle subprocess.TimeoutExpired by killing the process and returning False
  • Preserve existing success criteria based on process return code or output file existence
cli/generators/cover_letter_generator.py
Harden pandoc-based PDF compilation in cover letter generation to prevent RCE and hangs.
  • Add --pdf-engine-opt=-no-shell-escape to pandoc invocation using xelatex
  • Wrap pandoc process.communicate with a 30-second timeout and handle subprocess.TimeoutExpired by killing the process and returning False
  • Keep existing success checks on process return code and output file presence
cli/generators/cover_letter_generator.py
Secure pdflatex invocation in generic PDF converter with shell escape disable and timeout.
  • Add -no-shell-escape flag to pdflatex command in _compile_pdflatex
  • Introduce communicate(timeout=30) with TimeoutExpired handling that kills the process and returns False
  • Retain existing working directory and output checks
cli/pdf/converter.py
Secure pandoc invocation in generic PDF converter with shell escape disable and timeout.
  • Add --pdf-engine-opt=-no-shell-escape to pandoc xelatex engine invocation
  • Wrap communicate with a 30-second timeout and kill/return False on TimeoutExpired
  • Maintain current success logic based on return code or output file existence
cli/pdf/converter.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The timeout handling logic around process.communicate is duplicated in four places; consider extracting a small helper (e.g., run_with_timeout(cmd, cwd, timeout=30)) to centralize the pattern of Popen + communicate + timeout/kill handling.
  • When a timeout occurs you currently kill the process and immediately return False without surfacing any context; consider at least logging or propagating the fact that the failure was due to a timeout so callers and operators can distinguish it from normal compilation errors.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The timeout handling logic around `process.communicate` is duplicated in four places; consider extracting a small helper (e.g., `run_with_timeout(cmd, cwd, timeout=30)`) to centralize the pattern of `Popen` + `communicate` + timeout/kill handling.
- When a timeout occurs you currently kill the process and immediately return `False` without surfacing any context; consider at least logging or propagating the fact that the failure was due to a timeout so callers and operators can distinguish it from normal compilation errors.

## Individual Comments

### Comment 1
<location path="cli/pdf/converter.py" line_range="87-96" />
<code_context>
         try:
             # Use Popen with explicit cleanup to avoid double-free issues
             process = subprocess.Popen(
-                ["pdflatex", "-interaction=nonstopmode", tex_path.name],
+                ["pdflatex", "-interaction=nonstopmode", "-no-shell-escape", tex_path.name],
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 cwd=tex_path.parent,
             )
-            stdout, stderr = process.communicate()
+            try:
+                stdout, stderr = process.communicate(timeout=30)
+            except subprocess.TimeoutExpired:
+                process.kill()
+                stdout, stderr = process.communicate()
</code_context>
<issue_to_address>
**issue (bug_risk):** Killing the process on timeout has a small race condition that can raise OSError if the process exits just before kill() is called.

To avoid that exception, wrap the termination calls defensively, e.g.:

```python
try:
    stdout, stderr = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
    try:
        process.terminate()
    except OSError:
        pass  # process already exited
    try:
        stdout, stderr = process.communicate(timeout=5)
    except subprocess.TimeoutExpired:
        try:
            process.kill()
        except OSError:
            pass
        stdout, stderr = process.communicate()
```

At minimum, wrap `process.kill()` in a `try/except OSError` to prevent spurious failures.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click πŸ‘ or πŸ‘Ž on each comment and I'll use the feedback to improve your reviews.

Comment on lines 87 to +96
try:
process = subprocess.Popen(
["pdflatex", "-interaction=nonstopmode", tex_path.name],
["pdflatex", "-interaction=nonstopmode", "-no-shell-escape", tex_path.name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=working_dir,
)
stdout, stderr = process.communicate()
try:
stdout, stderr = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Killing the process on timeout has a small race condition that can raise OSError if the process exits just before kill() is called.

To avoid that exception, wrap the termination calls defensively, e.g.:

try:
    stdout, stderr = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
    try:
        process.terminate()
    except OSError:
        pass  # process already exited
    try:
        stdout, stderr = process.communicate(timeout=5)
    except subprocess.TimeoutExpired:
        try:
            process.kill()
        except OSError:
            pass
        stdout, stderr = process.communicate()

At minimum, wrap process.kill() in a try/except OSError to prevent spurious failures.

Co-authored-by: anchapin <6326294+anchapin@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant