Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,8 @@
**Vulnerability:** The `CoverLetterGenerator` used a standard Jinja2 environment (intended for HTML/XML or plain text) to render LaTeX templates. This allowed malicious user input (or AI hallucinations) containing LaTeX control characters (e.g., `\input{...}`) to be injected directly into the LaTeX source, leading to potential Local File Inclusion (LFI) or other exploits.
**Learning:** Jinja2's default `autoescape` is context-aware based on file extensions, but usually only for HTML/XML. It does NOT automatically escape LaTeX special characters. Relying on manual filters (like `| latex_escape`) in templates is error-prone and brittle, as developers might forget to apply them to every variable.
**Prevention:** Always use a dedicated Jinja2 environment for LaTeX generation that enforces auto-escaping via a `finalize` hook (e.g., `tex_env.finalize = latex_escape`). This ensures *all* variable output is sanitized by default, providing defense-in-depth even if the template author forgets explicit filters.

## 2025-02-23 - [Critical] pdflatex RCE and DoS in PDF Compilation
**Vulnerability:** Several places in the codebase (e.g. `cli/pdf/converter.py` and `cli/generators/cover_letter_generator.py`) called `pdflatex` or `pandoc` without the `-no-shell-escape` flag or timeouts, allowing for RCE and DoS.
**Learning:** Even fallback or auxiliary PDF compilation tasks need strict sandboxing. The `subprocess.communicate()` function will block indefinitely if a timeout is not specified, enabling DoS attacks via infinite compilation loops in maliciously crafted documents. Additionally, LaTeX allows shell execution by default which allows malicious users to execute arbitrary commands.
**Prevention:** Enforce `-no-shell-escape` and a timeout (e.g., 30s) on all `pdflatex` and `pandoc` calls. Handle `subprocess.TimeoutExpired` properly by killing the process and calling `communicate` again.
29 changes: 25 additions & 4 deletions cli/generators/cover_letter_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,14 +769,21 @@ def _compile_pdf(self, output_path: Path, tex_content: str) -> bool:

pdf_created = False
try:
# πŸ›‘οΈ Sentinel: Enforce -no-shell-escape and timeout to prevent RCE and DoS
# 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()
return False

if process.returncode == 0 or output_path.exists():
pdf_created = True
except (subprocess.CalledProcessError, FileNotFoundError):
Expand All @@ -786,12 +793,26 @@ def _compile_pdf(self, output_path: Path, tex_content: str) -> bool:
else:
# Fallback to pandoc
try:
# πŸ›‘οΈ Sentinel: Enforce -no-shell-escape and timeout to prevent RCE and DoS
process = subprocess.Popen(
["pandoc", str(tex_path), "-o", str(output_path), "--pdf-engine=xelatex"],
[
"pandoc",
str(tex_path),
"-o",
str(output_path),
"--pdf-engine=xelatex",
"--pdf-engine-opt=-no-shell-escape",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
try:
stdout, stderr = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
process.kill()
stdout, stderr = process.communicate()
return False

if process.returncode == 0 or output_path.exists():
pdf_created = True
except (subprocess.CalledProcessError, FileNotFoundError):
Expand Down
27 changes: 23 additions & 4 deletions cli/pdf/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,19 @@ def _compile_pdflatex(
True if PDF was created successfully
"""
try:
# πŸ›‘οΈ Sentinel: Enforce -no-shell-escape and timeout to prevent RCE and DoS
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:
process.kill()
stdout, stderr = process.communicate()
return False

if process.returncode == 0 or output_path.exists():
return True
Expand Down Expand Up @@ -120,13 +126,26 @@ def _compile_pandoc(
True if PDF was created successfully
"""
try:
# πŸ›‘οΈ Sentinel: Enforce -no-shell-escape and timeout to prevent RCE and DoS
process = subprocess.Popen(
["pandoc", str(tex_path), "-o", str(output_path), "--pdf-engine=xelatex"],
[
"pandoc",
str(tex_path),
"-o",
str(output_path),
"--pdf-engine=xelatex",
"--pdf-engine-opt=-no-shell-escape",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=working_dir,
)
stdout, stderr = process.communicate()
try:
stdout, stderr = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
process.kill()
stdout, stderr = process.communicate()
return False

if process.returncode == 0 or output_path.exists():
return True
Expand Down
75 changes: 75 additions & 0 deletions tests/test_pdf_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@
from unittest.mock import MagicMock, patch

from cli.generators.template import TemplateGenerator
from cli.pdf.converter import PDFConverter
from cli.generators.cover_letter_generator import CoverLetterGenerator


class MockConfig:
def __init__(self):
self.ai_provider = "anthropic"
self.anthropic_api_key = "mock"
self.output_dir = "output"
self.ai_model = "claude-3-haiku"

def get(self, *args, **kwargs):
return {}


class TestPDFSecurity(unittest.TestCase):
Expand Down Expand Up @@ -55,6 +68,68 @@ def test_pdflatex_arguments(self, mock_popen):
self.assertIn("-interaction=nonstopmode", command)
self.assertIn("pdflatex", command)

@patch("cli.pdf.converter.subprocess.Popen")
def test_converter_pdflatex_timeout(self, mock_popen):
process_mock = MagicMock()
process_mock.communicate.side_effect = [
subprocess.TimeoutExpired(cmd="pdflatex", timeout=30),
(b"", b""),
]
mock_popen.return_value = process_mock

converter = PDFConverter()
result = converter._compile_pdflatex(Path("output.tex"), Path("output.pdf"), Path("."))

self.assertFalse(result)
process_mock.kill.assert_called_once()
process_mock.communicate.assert_any_call(timeout=30)

@patch("cli.pdf.converter.subprocess.Popen")
def test_converter_pdflatex_arguments(self, mock_popen):
process_mock = MagicMock()
process_mock.communicate.return_value = (b"", b"")
process_mock.returncode = 0
mock_popen.return_value = process_mock

converter = PDFConverter()
converter._compile_pdflatex(Path("output.tex"), Path("output.pdf"), Path("."))

args, _ = mock_popen.call_args
command = args[0]
self.assertIn("-no-shell-escape", command)

@patch("subprocess.Popen")
def test_cover_letter_pdflatex_timeout(self, mock_popen):
process_mock = MagicMock()
process_mock.communicate.side_effect = [
subprocess.TimeoutExpired(cmd="pdflatex", timeout=30),
(b"", b""),
]
mock_popen.return_value = process_mock

# Use MockConfig with required properties
generator = CoverLetterGenerator(config=MockConfig())
result = generator._compile_pdf(Path("output.pdf"), "content")

self.assertFalse(result)
process_mock.kill.assert_called_once()
process_mock.communicate.assert_any_call(timeout=30)

@patch("subprocess.Popen")
def test_cover_letter_pdflatex_arguments(self, mock_popen):
process_mock = MagicMock()
process_mock.communicate.return_value = (b"", b"")
process_mock.returncode = 0
mock_popen.return_value = process_mock

generator = CoverLetterGenerator(config=MockConfig())
with patch.object(Path, "exists", return_value=True):
generator._compile_pdf(Path("output.pdf"), "content")

args, _ = mock_popen.call_args
command = args[0]
self.assertIn("-no-shell-escape", command)


if __name__ == "__main__":
unittest.main()
Loading