【问题标题】:Sanitizing PDF user input in Python在 Python 中清理 PDF 用户输入
【发布时间】:2019-07-01 04:00:34
【问题描述】:

我的应用程序允许用户上传 PDF 文件。这些文件应该看起来相对相似并且是相同格式的变体。我了解 PDF 有时可能包含恶意内容——例如在 Adob​​e Reader 或类似软件中打开时将执行的 Javascript。

我在网上看到了一些软件包,例如 PDFiD,它可以帮助您查看可能有问题的 PDF。这似乎允许您查看所有基础内容类型。我目前的思考过程是了解我的文档应该包含哪些内容类型,然后如果文件有异常内容,则阻止它们上传。

有没有一种简单的方法可以使用 Python 自动清理恶意内容的 PDF,删除其中可能包含的所有可执行代码?我知道有一种 PDF/A 格式允许这样的事情,但是有没有像 PyPDF2 这样具有清理功能的包?

【问题讨论】:

  • Didier Stevens 在 python 中有一些很棒的 PDF 取证工具。您可以编写一些内容来删除最常见的恶意内容。我说“大多数”是因为除了嵌入的 JavaScript 或 ActionScript 之外,PDF 中可能还有很多恶意内容。
  • 还有一种消毒剂叫做origapy。然而,它基于 ruby​​ 库,并且自 2010 年以来(从网站上)似乎没有处于积极开发中......

标签: python pdf sanitization


【解决方案1】:

我相信这就是答案:

from pdfid import PDFiD
new_file = PDFiD('path/to/file', disarm=True)

会取PDF的元素

<Keywords>
    <Keyword Count="56" HexcodeCount="0" Name="obj"/>
    <Keyword Count="56" HexcodeCount="0" Name="endobj"/>
    <Keyword Count="32" HexcodeCount="0" Name="stream"/>
    <Keyword Count="32" HexcodeCount="0" Name="endstream"/>
    <Keyword Count="1" HexcodeCount="0" Name="xref"/>
    <Keyword Count="1" HexcodeCount="0" Name="trailer"/>
    <Keyword Count="1" HexcodeCount="0" Name="startxref"/>
    <Keyword Count="8" HexcodeCount="0" Name="/Page"/>
    <Keyword Count="0" HexcodeCount="0" Name="/Encrypt"/>
    <Keyword Count="0" HexcodeCount="0" Name="/ObjStm"/>
    <Keyword Count="0" HexcodeCount="0" Name="/JS"/>
    <Keyword Count="0" HexcodeCount="0" Name="/JavaScript"/>
    <Keyword Count="0" HexcodeCount="0" Name="/AA"/>
    <Keyword Count="0" HexcodeCount="0" Name="/OpenAction"/>
    <Keyword Count="0" HexcodeCount="0" Name="/AcroForm"/>
    <Keyword Count="0" HexcodeCount="0" Name="/JBIG2Decode"/>
    <Keyword Count="0" HexcodeCount="0" Name="/RichMedia"/>
    <Keyword Count="0" HexcodeCount="0" Name="/Launch"/>
    <Keyword Count="0" HexcodeCount="0" Name="/EmbeddedFile"/>
    <Keyword Count="0" HexcodeCount="0" Name="/XFA"/>
    <Keyword Count="0" HexcodeCount="0" Name="/Colors &gt; 2^24"/>
</Keywords>

如果可疑,则将所有内容设为 count=0

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    • 2015-11-10
    • 1970-01-01
    相关资源
    最近更新 更多