Skip to content

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

Open
anchapin wants to merge 1 commit intomainfrom
sentinel-fix-pdf-rce-15424413755351556693
Open

πŸ›‘οΈ Sentinel: [CRITICAL] Fix RCE vulnerability in PDF compilation#291
anchapin wants to merge 1 commit intomainfrom
sentinel-fix-pdf-rce-15424413755351556693

Conversation

@anchapin
Copy link
Copy Markdown
Owner

@anchapin anchapin commented May 7, 2026

🚨 Severity: CRITICAL
πŸ’‘ Vulnerability: The application used subprocess.Popen to compile LaTeX files using pdflatex and pandoc without the -no-shell-escape flag and without process timeouts.
🎯 Impact: This allowed malicious .tex content (e.g., injected via unsanitized user input or AI hallucinations) to execute arbitrary shell commands via the \write18 feature or similar LaTeX exploits. Furthermore, the lack of timeouts could lead to Denial of Service (DoS) via infinite compilation loops.
πŸ”§ Fix: Added -no-shell-escape flags to all pdflatex and pandoc calls. Implemented timeout=30 handling via subprocess.communicate() with proper process cleanup (process.kill()) for timeout exceptions.
βœ… Verification: Ensure tests pass locally (e.g., test_pdf_security.py).


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

Summary by Sourcery

Harden PDF compilation against remote code execution and denial-of-service by constraining LaTeX tool invocations and documenting the incident.

Bug Fixes:

  • Disable LaTeX shell execution by adding no-shell-escape options to all pdflatex and pandoc-based PDF compilation paths.
  • Prevent unbounded PDF compilation by adding 30-second timeouts with process cleanup for external LaTeX and pandoc processes.

Documentation:

  • Document the critical RCE and DoS vulnerability in PDF compilation and the mitigations applied in the Sentinel security log.

Added `-no-shell-escape` flags to `pdflatex` and `pandoc` compilation commands in `cli/pdf/converter.py` and `cli/generators/cover_letter_generator.py` to prevent arbitrary command execution via maliciously crafted or hallucinated LaTeX content. Also implemented bounded subprocess execution using `timeout=30` and proper process termination `kill()` to prevent potential DoS attacks.

Co-authored-by: anchapin <[email protected]>
@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 May 7, 2026

Reviewer's Guide

Adds hardened PDF compilation by disabling LaTeX shell escapes and enforcing time-bounded subprocess execution for both pdflatex and pandoc, plus documents the incident in Sentinel notes.

Sequence diagram for hardened LaTeX PDF compilation with timeout and fallback

sequenceDiagram
    participant Caller
    participant CoverLetterGenerator
    participant Subprocess
    participant Pdflatex
    participant Pandoc

    Caller->>CoverLetterGenerator: _compile_pdf(output_path, tex_content)
    CoverLetterGenerator->>CoverLetterGenerator: write tex_content to tex_path

    Note over CoverLetterGenerator: Primary compilation via pdflatex
    CoverLetterGenerator->>Subprocess: Popen(pdflatex -interaction=nonstopmode -no-shell-escape)
    Subprocess->>Pdflatex: execute tex_path

    alt completes within 30s
        CoverLetterGenerator->>Subprocess: communicate(timeout=30)
        Subprocess-->>CoverLetterGenerator: stdout, stderr
        alt returncode == 0 or pdf exists
            CoverLetterGenerator-->>Caller: pdf_created = True
        else returncode != 0 and no pdf
            CoverLetterGenerator->>CoverLetterGenerator: pdf_created remains False
        end
    else times out after 30s
        CoverLetterGenerator->>Subprocess: process.kill()
        CoverLetterGenerator->>Subprocess: communicate()
        CoverLetterGenerator->>CoverLetterGenerator: raise RuntimeError
        CoverLetterGenerator->>CoverLetterGenerator: enter exception handler
    end

    alt pdf_created is False and pdf does not exist
        Note over CoverLetterGenerator: Fallback compilation via pandoc
        CoverLetterGenerator->>Subprocess: Popen(pandoc --pdf-engine=xelatex --pdf-engine-opt=-no-shell-escape)
        Subprocess->>Pandoc: execute tex_path

        alt completes within 30s
            CoverLetterGenerator->>Subprocess: communicate(timeout=30)
            Subprocess-->>CoverLetterGenerator: stdout, stderr
            alt returncode == 0 or pdf exists
                CoverLetterGenerator-->>Caller: pdf_created = True
            else returncode != 0 and no pdf
                CoverLetterGenerator->>CoverLetterGenerator: pdf_created remains False
            end
        else times out after 30s
            CoverLetterGenerator->>Subprocess: process.kill()
            CoverLetterGenerator->>Subprocess: communicate()
            CoverLetterGenerator->>CoverLetterGenerator: raise RuntimeError
            CoverLetterGenerator->>CoverLetterGenerator: exception handler ignores
        end
    else pdf already created
        CoverLetterGenerator-->>Caller: pdf_created = True
    end
Loading

File-Level Changes

Change Details Files
Harden pdflatex-based PDF compilation against RCE and hangs in the cover letter generator.
  • Add -no-shell-escape flag to pdflatex invocation to disable shell escape in LaTeX
  • Wrap process.communicate with a 30-second timeout and kill the process on timeout before raising an error
  • Treat RuntimeError from timeouts like other recoverable subprocess failures while still checking whether the PDF output exists
  • Apply the same timeout and error-handling pattern to the pdflatex fallback path
cli/generators/cover_letter_generator.py
Harden shared PDF converter’s pdflatex and pandoc flows with shell-escape disabling and bounded execution time.
  • Add -no-shell-escape flag to pdflatex invocation in the PDF converter
  • Add --pdf-engine-opt=-no-shell-escape to pandoc invocation to disable shell escapes in the LaTeX engine
  • Introduce 30-second timeouts around subprocess.communicate for both pdflatex and pandoc, with process.kill and RuntimeError on timeout
  • Include RuntimeError in handled exceptions while preserving existing behavior of accepting PDFs produced despite non-zero return codes
cli/pdf/converter.py
Document the critical RCE vulnerability and the chosen mitigations in Sentinel security notes.
  • Add a new Sentinel incident entry describing the lack of -no-shell-escape and timeouts in PDF compilation
  • Record learnings about LaTeX-capable tools and the need for explicit shell-escape disabling and timeouts
  • Document preventive guidelines for future subprocess-based document compilation
.jules/sentinel.md

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 new timeout/kill logic for pdflatex and pandoc is duplicated in multiple places; consider extracting a shared helper (e.g., run_with_timeout(cmd, cwd, timeout=30)) or at least centralizing the timeout constant to avoid divergence in future changes.
  • By catching RuntimeError together with other exceptions and then treating an existing output file as success, timeouts will be silently downgraded to success if a partial PDF exists; consider either surfacing timeout failures distinctly or validating the resulting file before treating it as successful.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new timeout/kill logic for `pdflatex` and `pandoc` is duplicated in multiple places; consider extracting a shared helper (e.g., `run_with_timeout(cmd, cwd, timeout=30)`) or at least centralizing the timeout constant to avoid divergence in future changes.
- By catching `RuntimeError` together with other exceptions and then treating an existing output file as success, timeouts will be silently downgraded to success if a partial PDF exists; consider either surfacing timeout failures distinctly or validating the resulting file before treating it as successful.

## Individual Comments

### Comment 1
<location path="cli/pdf/converter.py" line_range="103" />
<code_context>
             if process.returncode == 0 or output_path.exists():
                 pdf_created = True
-        except (subprocess.CalledProcessError, FileNotFoundError):
+        except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError):
             # Check if PDF was created anyway
             if output_path.exists():
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Timeout and other failures are fully suppressed, which makes diagnosing compilation issues difficult.

In this pandoc path, `RuntimeError` (including timeouts) and `FileNotFoundError` are now silently swallowed, and the caller only sees `False`. Please at least log the exception type and a brief message (and possibly stderr) so timeouts vs. missing binaries/misconfigurations can be distinguished in production without modifying code.

Suggested implementation:

```python
        except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError) as exc:
            # Log the failure so timeouts, missing binaries, etc. can be diagnosed
            logger.error(
                "PDF compilation failed (%s): %s",
                type(exc).__name__,
                str(exc),
                exc_info=True,
            )
            # Log stderr if it was captured
            if "stderr" in locals() and stderr:
                logger.error("PDF compilation stderr:\n%s", stderr)

            # Check if PDF was created anyway (pdflatex returns non-zero for warnings)
            if output_path.exists():
                return True

```

1. Ensure there is a module-level logger defined in `cli/pdf/converter.py`, for example:
   `logger = logging.getLogger(__name__)`.
2. If not already present, import the `logging` module at the top of the file:
   `import logging`.
</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 thread cli/pdf/converter.py
if process.returncode == 0 or output_path.exists():
return True
except (subprocess.CalledProcessError, FileNotFoundError):
except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (bug_risk): Timeout and other failures are fully suppressed, which makes diagnosing compilation issues difficult.

In this pandoc path, RuntimeError (including timeouts) and FileNotFoundError are now silently swallowed, and the caller only sees False. Please at least log the exception type and a brief message (and possibly stderr) so timeouts vs. missing binaries/misconfigurations can be distinguished in production without modifying code.

Suggested implementation:

        except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError) as exc:
            # Log the failure so timeouts, missing binaries, etc. can be diagnosed
            logger.error(
                "PDF compilation failed (%s): %s",
                type(exc).__name__,
                str(exc),
                exc_info=True,
            )
            # Log stderr if it was captured
            if "stderr" in locals() and stderr:
                logger.error("PDF compilation stderr:\n%s", stderr)

            # Check if PDF was created anyway (pdflatex returns non-zero for warnings)
            if output_path.exists():
                return True
  1. Ensure there is a module-level logger defined in cli/pdf/converter.py, for example:
    logger = logging.getLogger(__name__).
  2. If not already present, import the logging module at the top of the file:
    import logging.

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