百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

polyfile

> 数据库
开源

一个纯粹的 Python 清洁室实现的 libmagic,其中包含了来自 Kaitai struct 的仪器化解析和交互式十六进制查看器

387 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

一个纯粹的 Python 清洁室实现的 libmagic,其中包含了来自 Kaitai struct 的仪器化解析和交互式十六进制查看器

PolyFile

A utility to identify and map the semantic and syntactic structure of files, including polyglots, chimeras, and schizophrenic files. It has a pure-Python implementation of libmagic and can act as a drop-in replacement for the file command. However, unlike file, PolyFile recurses into the files it identifies: the ZIP parser matches every decompressed member, the PDF parser matches every decoded stream, and every non-constant byte field of a parsed structure is matched again on its own. A few matchers also search for their magic anywhere in the input, so a ZIP archive that does not start at byte offset zero is still found. PolyFile does not scan every offset the way binwalk does; issue #3532 tracks that.

PolyFile can be used in conjunction with its sister tool PolyTracker for Automated Lexical Annotation and Navigation of Parsers, a backronym devised solely for the purpose of collectively referring to the tools as The ALAN Parsers Project.

Quickstart

You can install the latest stable version of PolyFile from PyPI with uv:

uv tool install polyfile

To run PolyFile once without installing it:

uvx polyfile 

To install PolyFile from source, clone the repository with its submodules and run uv in the same directory as this README:

bash
git submodule update --init --recursive
uv pip install .

Installing from source builds in an isolated environment, so it needs network access to fetch the build backend. To build offline, install setuptools>=83.0.0 yourself and run uv pip install --no-build-isolation ..

Installing from PyPI reuses the parsers that the published distribution already carries. Installing from a source checkout regenerates them, and only that path needs Java, which runs the Kaitai Struct compiler that compiles the file format definitions.

This installs the polyfile executable in your path. The companion merge tool runs as python -m polymerge.

Usage

Running polyfile on a file with no arguments will mimic the behavior of file --keep-going:

bash
$ polyfile png-polyglot.png
PNG image data, 256 x 144, 8-bit/color RGB, non-interlaced
Brainfu** Program
Malformed PDF
PDF document, version 1.3,  1 pages
ZIP end of central directory record Java JAR archive 

To generate an interactive hex viewer for the file, use the --html option:

bash
$ polyfile --html output.html png-polyglot.png
Found a file of type application/pdf at byte offset 0
Found a file of type application/x-brainfuck at byte offset 0
Found a file of type image/png at byte offset 0
Found a file of type application/zip at byte offset 0
Found a file of type application/java-archive at byte offset 0
Saved HTML output to output.html

The viewer renders any byte that no match describes in gray on a diagonal hatch, and reports how many such bytes the file has above the hex dump.

Run polyfile --help for full usage instructions.

Interactive Debugger

PolyFile has an interactive debugger both for its file matching and parsing. It can be used to debug a libmagic pattern definition, determine why a specific file fails to be classified as the expected MIME type, or step through a parser. You can run PolyFile with the debugger enabled using the -db option.

File Support

PolyFile has a cleanroom, pure Python implementation of the libmagic file classifier, and supports all 896 MIME types that it can identify.

It currently has support for parsing and semantically mapping the following formats:

  • PDF, using pdfminer.six to decode objects and streams
  • ZIP, including recursive identification of all ZIP contents
  • JPEG/JFIF, using its Kaitai Struct grammar
  • iNES
  • Any other format specified in a KSY grammar

For an example that exercises all of these file formats, run:

bash
curl -v --silent https://www.sultanik.com/files/ESultanikResume.pdf | polyfile --html ESultanikResume.html -

Prior to PolyFile version 0.3.0, it used the TrID database for file identification rather than the libmagic file definitions. This proved to be very slow (since TrID has many duplicate entries) and prone to false positives (since TrID's file definitions are much simpler than libmagic's). The original TrID matching code is still shipped with PolyFile and can be invoked programmatically, but it is not used by default.

Output Format

PolyFile has several options for outputting its results, specified by its --format option. For computer-readable output, PolyFile has an extension of the SBuD JSON format described in the documentation. Prior to version 0.5.0 this was the default output format of PolyFile. However, now the default output format is to mimic the behavior of the file command. To maintain the original behavior, use the --format sbud option.

The json and sbud formats include a b64contents key holding a base64 encoding of the entire input, so their output grows with the size of the file you analyze. Pass --no-contents to leave that key out; PolyFile then skips the encoding instead of computing it and throwing the result away. The key is omitted rather than emptied, so a consumer that needs the contents fails instead of reading the input as empty. The HTML hex viewer is built from the contents, so you cannot combine --no-contents with --format html or --html.

libmagic Implementation

PolyFile has a cleanroom implementation of libmagic (used in the file command). It can be invoked programmatically by running:

python
from polyfile.magic import MagicMatcher

with open("file_to_test", "rb") as f:
    # the default instance automatically loads all file definitions
    for match in MagicMatcher.DEFAULT_INSTANCE.match(f.read()):
        for mimetype in match.mimetypes:
            print(f"Matched MIME: {mimetype}")
        print(f"Match string: {match!s}")

To load a specific or custom file definition:

python
list_of_paths_to_definitions = ["def1", "def2"]
matcher = MagicMatcher.parse(*list_of_paths_to_definitions)
with open("file_to_test", "rb") as f:
    for match in matcher.match(f.read()):
        ...

Extending PolyFile

Instructions on extending PolyFile to support more file formats with new matchers and parsers is described [in the documentation](in the documentation).

License and Acknowledgements

This research was developed by Trail of Bits with funding from the Defense Advanced Research Projects Agency (DARPA) under the SafeDocs program as a subcontractor to Galois. It is licensed under the Apache 2.0 license. © 2019, Trail of Bits.

PolyFile generates most of its parsers from the Kaitai Struct format gallery, where each format specification carries its own license. A generated parser is a derivative work of its specification, so PolyFile builds parsers only from specifications under a permissive license. The distributed package therefore contains no copyleft code, and the specifications PolyFile cannot redistribute are excluded from the source distribution. For the details, see Licensing of generated parsers.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Pythonfile-format-detectionfile-formatslibmagicpolyglots

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库