|
| 1 | +# PolyFile Development Guide |
| 2 | + |
| 3 | +## Project Overview |
| 4 | + |
| 5 | +PolyFile is a file analysis utility that identifies and maps the semantic and syntactic structure of files—including polyglots, chimeras, and "schizophrenic" files that are validly multiple types simultaneously. |
| 6 | + |
| 7 | +**Key capabilities:** |
| 8 | +- Pure-Python libmagic implementation (263+ MIME types) |
| 9 | +- Recursive embedded file detection (like binwalk) |
| 10 | +- Parsers for PDF, ZIP, JPEG, iNES, and 188 Kaitai Struct formats |
| 11 | +- Interactive HTML hex viewer with structure mapping |
| 12 | +- Drop-in replacement for Unix `file` command |
| 13 | + |
| 14 | +Part of the [ALAN Parsers Project](https://github.com/trailofbits/polyfile#the-alan-parsers-project) alongside PolyTracker. |
| 15 | + |
| 16 | +## Architecture |
| 17 | + |
| 18 | +### Core Pattern: Matchers + Parsers |
| 19 | + |
| 20 | +**Matchers** classify file types. Two types: |
| 21 | +- libmagic DSL matchers (defined in `polyfile/magic_defs/`) |
| 22 | +- Python matchers (classes extending `Matcher`) |
| 23 | + |
| 24 | +**Parsers** create AST representations of file structure. Registered via decorator: |
| 25 | +```python |
| 26 | +from polyfile import register_parser |
| 27 | + |
| 28 | +@register_parser("application/pdf") |
| 29 | +def parse_pdf(file_stream, match): |
| 30 | + # Return parsed structure |
| 31 | + ... |
| 32 | +``` |
| 33 | + |
| 34 | +### Key Modules |
| 35 | + |
| 36 | +| Module | Purpose | Size | |
| 37 | +|--------|---------|------| |
| 38 | +| `polyfile.py` | Core engine—Match, Parser, Submatch classes | 15 KB | |
| 39 | +| `magic.py` | Pure-Python libmagic DSL implementation | 117 KB | |
| 40 | +| `pdf.py` | PDF parser with embedded file detection | 48 KB | |
| 41 | +| `debugger.py` | Interactive GDB-style debugger | 42 KB | |
| 42 | +| `kaitaimatcher.py` | Kaitai Struct format bridge | — | |
| 43 | + |
| 44 | +### Directory Structure |
| 45 | + |
| 46 | +``` |
| 47 | +polyfile/ |
| 48 | +├── polyfile/ # Main package |
| 49 | +│ ├── magic_defs/ # 354 libmagic definition files |
| 50 | +│ ├── kaitai/parsers/ # 188 auto-generated Kaitai parsers (excluded from lint) |
| 51 | +│ └── templates/ # HTML output templates |
| 52 | +├── polymerge/ # Companion merge tool |
| 53 | +├── tests/ # Test suite |
| 54 | +├── docs/ # Extension guide, JSON format spec |
| 55 | +└── kaitai_struct_formats/ # Git submodule with KSY definitions |
| 56 | +``` |
| 57 | + |
| 58 | +## Development Commands |
| 59 | + |
| 60 | +### Setup |
| 61 | +```bash |
| 62 | +# Install from source (requires Java for Kaitai compiler) |
| 63 | +pip install -e .[dev] |
| 64 | + |
| 65 | +# Install from PyPI |
| 66 | +pip install polyfile |
| 67 | +``` |
| 68 | + |
| 69 | +### Linting |
| 70 | +```bash |
| 71 | +# Run flake8 (excludes auto-generated kaitai parsers) |
| 72 | +flake8 polyfile polymerge --max-complexity=10 --max-line-length=127 \ |
| 73 | + --exclude=polyfile/kaitai/parsers |
| 74 | +``` |
| 75 | + |
| 76 | +### Testing |
| 77 | +```bash |
| 78 | +# Run all tests |
| 79 | +pytest tests |
| 80 | + |
| 81 | +# Run specific test file |
| 82 | +pytest tests/test_magic.py |
| 83 | +pytest tests/test_pdf.py |
| 84 | +pytest tests/test_corkami.py # Polyglot corpus |
| 85 | +``` |
| 86 | + |
| 87 | +### Security Audit |
| 88 | +```bash |
| 89 | +pip-audit |
| 90 | +``` |
| 91 | + |
| 92 | +### Pre-Commit Checklist |
| 93 | +Run all checks before committing changes: |
| 94 | +```bash |
| 95 | +# Lint |
| 96 | +flake8 polyfile polymerge --max-complexity=10 --max-line-length=127 \ |
| 97 | + --exclude=polyfile/kaitai/parsers |
| 98 | + |
| 99 | +# Security audit (checks for vulnerable dependencies) |
| 100 | +pip-audit |
| 101 | + |
| 102 | +# Tests |
| 103 | +pytest tests |
| 104 | +``` |
| 105 | + |
| 106 | +## Code Navigation |
| 107 | + |
| 108 | +### Finding Matchers |
| 109 | +```bash |
| 110 | +# Find libmagic definitions by MIME type |
| 111 | +rg "application/pdf" polyfile/magic_defs/ |
| 112 | + |
| 113 | +# Find Python matchers |
| 114 | +ast-grep --pattern 'class $NAME(Matcher): $$$' --lang py polyfile/ |
| 115 | +``` |
| 116 | + |
| 117 | +### Finding Parsers |
| 118 | +```bash |
| 119 | +# Find registered parsers |
| 120 | +rg "@register_parser" polyfile/ |
| 121 | + |
| 122 | +# Find parser for specific MIME type |
| 123 | +rg 'register_parser.*application/zip' polyfile/ |
| 124 | +``` |
| 125 | + |
| 126 | +### Key Entry Points |
| 127 | +- CLI: `polyfile/__main__.py` |
| 128 | +- Core analysis: `polyfile/polyfile.py:PolyFile.struc()` |
| 129 | +- Magic matching: `polyfile/magic.py:MagicMatcher.match()` |
| 130 | + |
| 131 | +## Testing |
| 132 | + |
| 133 | +### Test Structure |
| 134 | +``` |
| 135 | +tests/ |
| 136 | +├── test_magic.py # libmagic implementation vs corpus |
| 137 | +├── test_pdf.py # PDF parsing |
| 138 | +├── test_corkami.py # Polyglot/chimera edge cases |
| 139 | +├── test_kaitai.py # Kaitai format tests |
| 140 | +└── unit/ |
| 141 | + ├── test_ast.py # AST utilities |
| 142 | + └── test_http.py # HTTP protocol parsing |
| 143 | +``` |
| 144 | + |
| 145 | +### Test Conventions |
| 146 | +- Uses real file corpus including libmagic's official test suite |
| 147 | +- Tests polyglot files to verify multi-type detection |
| 148 | +- Parser tests validate structure extraction |
| 149 | + |
| 150 | +## Extending PolyFile |
| 151 | + |
| 152 | +### Adding a Custom Matcher (Python) |
| 153 | +```python |
| 154 | +from polyfile import Matcher, Match |
| 155 | + |
| 156 | +class MyMatcher(Matcher): |
| 157 | + def match(self, data: bytes) -> Match | None: |
| 158 | + if data.startswith(b'MAGIC'): |
| 159 | + return Match( |
| 160 | + mime_type="application/x-myformat", |
| 161 | + name="My Format", |
| 162 | + offset=0, |
| 163 | + length=len(data) |
| 164 | + ) |
| 165 | + return None |
| 166 | +``` |
| 167 | + |
| 168 | +### Adding a Custom Parser |
| 169 | +```python |
| 170 | +from polyfile import register_parser, Parser, Submatch |
| 171 | + |
| 172 | +@register_parser("application/x-myformat") |
| 173 | +class MyParser(Parser): |
| 174 | + def parse(self, file_stream, match) -> Iterator[Submatch]: |
| 175 | + # Yield Submatch objects representing structure |
| 176 | + yield Submatch( |
| 177 | + name="header", |
| 178 | + start=0, |
| 179 | + length=8, |
| 180 | + value=file_stream.read(8) |
| 181 | + ) |
| 182 | +``` |
| 183 | + |
| 184 | +### Adding Kaitai Struct Format |
| 185 | +1. Add `.ksy` file to `kaitai_struct_formats/` |
| 186 | +2. Map MIME type in `polyfile/kaitai/parsers/__init__.py` |
| 187 | +3. Rebuild: `python compile_kaitai_parsers.py` |
| 188 | + |
| 189 | +See `docs/extending_polyfile.md` for detailed guide. |
| 190 | + |
| 191 | +## Internal API Patterns |
| 192 | + |
| 193 | +### File I/O |
| 194 | +- Use `FileStream` abstraction for seeking/reading |
| 195 | +- `PathOrStdin`/`PathOrStdout` for CLI flexibility |
| 196 | + |
| 197 | +### Match Hierarchy |
| 198 | +- `Match` → top-level file type match |
| 199 | +- `Submatch` → nested structure within a match |
| 200 | +- Build trees for embedded files (ZIP contents, PDF streams) |
| 201 | + |
| 202 | +### Error Handling |
| 203 | +- Raise `InvalidMatch` when parser cannot process data |
| 204 | +- Matchers return `None` for non-matching data |
| 205 | + |
| 206 | +### Gotchas |
| 207 | +- `polyfile/kaitai/parsers/` is auto-generated—never edit manually |
| 208 | +- Java required at install time for Kaitai compilation |
| 209 | +- libmagic DSL has quirks—see [blog post](https://blog.trailofbits.com/2022/07/01/libmagic-the-blathering/) |
0 commit comments