Doc-Sherlock is a security tool designed to identify hidden text in PDF documents that could be used for prompt injection attacks against LLM systems. This tool helps security teams detect common techniques used to hide malicious content from human reviewers while remaining accessible to LLM parsers.
Attackers can exploit LLM systems by hiding text in PDFs that is:
- Invisible to human reviewers
- Parsed and processed by LLM systems
- Designed to inject malicious prompts or instructions
These attacks can lead to prompt injection, data leakage, or manipulation of LLM outputs.
The related technique is the l from OWASP top 10 for LLMs, which states that "LLMs can be tricked into executing malicious code or commands by embedding them in seemingly innocuous text."
Doc-Sherlock implements multiple detection strategies to identify hidden content:
- Identifies text with colors too similar to the background (e.g., white text on white background)
- Calculates contrast ratios using WCAG standards
- Flags text that falls below configurable thresholds
- Identifies text with abnormally small font sizes
- Configurable minimum size thresholds (default: 4pt)
- Detects text that would be illegible to humans
- Identifies text positioned outside normal page boundaries
- Detects content placed beyond page margins or viewport
- Flags text that would be invisible when viewing the document normally
- Identifies text with low opacity/transparency settings
- Detects nearly invisible text (e.g., 1-10% opacity)
- Analyzes PDF content streams for transparency operators
- Identifies content in hidden PDF layers (Optional Content Groups)
- Detects layers with suspicious names or hidden by default
- Analyzes PDF structure for layer manipulation
- Identifies text hidden behind images, shapes, or other elements
- Detects z-ordering manipulation to obscure content
- Compares visual rendering with extracted text
- Identifies suspicious content in PDF metadata fields
- Detects potential prompt injection attempts in document properties
- Flags unusually large metadata strings
- Compares visual rendering with extracted text content
- Uses OCR to identify differences between what's visible and what's present
- Detects sophisticated hiding techniques
- Identifies unusual encoding patterns in PDF content
- Detects obfuscated text and operators
- Flags embedded files and suspicious structures
pip install doc-sherlock
git clone https://github.com/example/doc-sherlock.git cd doc-sherlock pip install -e .
For Ubuntu/Debian systems, you can automatically install both Doc-Sherlock and its system dependencies using the following script:
#!/bin/bash # Install Tesseract OCR system dependency sudo apt-get update && sudo apt-get install -y tesseract-ocr # Install Doc-Sherlock pip install doc-sherlock # Or if installing from source # cd path/to/doc-sherlock # pip install -e .
Doc-Sherlock requires:
- Python 3.8+
- Tesseract OCR (for rendering discrepancy detection)
To use the REST API server, you need the fastapi and uvicorn packages. These are included in the dev extra requirements:
pip install -e .[dev]
This will install all development dependencies, including FastAPI and Uvicorn, which are required to run the REST API server.
After installing the dev dependencies, you can start the REST API server with:
doc-sherlock rest_service
# or, if not installed as a script:
python -m doc_sherlock.cli rest_serviceThis will start a FastAPI server (default: http://127.0.0.1:8000) with a /analyze POST endpoint. You can send a PDF file to this endpoint and receive the findings as a JSON response.
Example using curl:
curl -F "file=@path/to/document.pdf" http://127.0.0.1:8000/analyzeTesseract OCR is required for the rendering discrepancy detection feature, which compares visual content with extracted text. Without it, some detection methods will be disabled or will report warnings.
Ubuntu/Debian:
sudo apt-get update sudo apt-get install -y tesseract-ocr
Fedora/RHEL/CentOS:
sudo dnf install tesseract
macOS:
brew install tesseract
Windows: Download and install from: https://github.com/UB-Mannheim/tesseract/wiki
Verify Installation:
tesseract --version
After installing Tesseract OCR, you should see the rendering discrepancy detection working properly. When analyzing a test PDF like tests/data/tiny_font.pdf, you should see findings like:
[HIGH] Page contains more text in PDF than visible through OCR (Page 1)
If you don't see this finding or see warnings about Tesseract not being installed, check your installation.
# Basic usage: Analyze a single PDF file doc-sherlock analyze path/to/your/document.pdf # Customize detection thresholds doc-sherlock analyze --min-contrast 4.5 --min-font-size 4 --min-opacity 0.3 document.pdf # Output detailed report in JSON format doc-sherlock analyze --output-format json --output report.json document.pdf # Analyze a directory of PDFs recursively doc-sherlock analyze --recursive path/to/pdf/directory/ # Enable verbose output doc-sherlock analyze --verbose document.pdf # Show warnings (warnings are hidden by default to reduce noise) doc-sherlock analyze --show-warnings document.pdf # Combine options doc-sherlock analyze --show-warnings --verbose --min-font-size 3 document.pdf
from doc_sherlock import PDFAnalyzer # Create an analyzer with custom configuration config = { "min_contrast_ratio": 4.5, # WCAG AA standard "min_font_size": 4.0, # Minimum font size in points "min_opacity": 0.3, # Minimum opacity (0.0-1.0) } analyzer = PDFAnalyzer("path/to/document.pdf", config) # Run all detectors results = analyzer.run_all_detectors() # Print a summary of findings print(results.summary()) # Access individual findings for finding in results.findings: print(f"{finding.finding_type.value}: {finding.description} (Severity: {finding.severity.value})") if finding.text_content: print(f"Text: {finding.text_content}") # Run specific detectors contrast_results = analyzer.detect_low_contrast() font_results = analyzer.detect_tiny_font() # Export results to JSON results.save_json("report.json") # Analyze a directory of PDFs dir_results = PDFAnalyzer.analyze_directory("/path/to/pdfs/", recursive=True, config=config)
# Clone the repository git clone https://github.com/example/doc-sherlock.git cd doc-sherlock # Create and activate a virtual environment python -m venv venv # On Linux/Mac source venv/bin/activate # On Windows # venv\Scripts\activate # Install basic package with dependencies pip install -e . # Install development dependencies pip install -e ".[dev]" # Install test dependencies pip install -e ".[test]" # Install all dependencies (dev and test) pip install -e ".[dev,test]"
pypdf: PDF parsing and manipulationpdfminer.six: Text extraction with formatting detailspikepdf: Low-level PDF structure analysispdfplumber: Text extraction with position informationpillow: Image processingpytesseract: OCR capabilities (requires Tesseract to be installed)colorama: Terminal color outputclick: Command-line interface
pytest: Testing frameworkpytest-cov: Test coverage reportingblack: Code formattingisort: Import sortingflake8: Linting
fpdf: PDF generation for testsreportlab: PDF generation with advanced features for tests
After installing Doc-Sherlock with pip install -e ., you can use the command-line tool as follows:
# Analyze a PDF file doc-sherlock analyze path/to/your/document.pdf # Analyze a test PDF doc-sherlock analyze tests/data/tiny_font.pdf # Show warnings during analysis (warnings are hidden by default) doc-sherlock analyze --show-warnings path/to/your/document.pdf # Get help on available commands doc-sherlock --help
Note: The command is
doc-sherlock(notdock-sherlock)
Doc-Sherlock includes a comprehensive test suite with test PDFs that simulate various hiding techniques:
# Run all tests python -m pytest # Run with coverage report python -m pytest --cov=doc_sherlock # Run specific test categories python -m pytest tests/test_contrast_detector.py
The test suite generates test PDFs using ReportLab and validates that each detector correctly identifies the corresponding hiding technique.
- Doc-Sherlock is designed as a detection tool, not a guarantee of security
- False positives and false negatives are possible
- Always combine with other security measures when processing PDFs in LLM pipelines
- Consider using PDF sanitization tools alongside Doc-Sherlock
For more information on practical attacks, you can visit the following link:
https://kai-greshake.de/posts/inject-my-pdf/
Contributions are welcome! Please feel free to submit a Pull Request.
AGPL 3.0 License. See LICENSE.txt for details.