Back to skill

Security audit

Pdf2md Universal

Security checks for vulnerabilities and agentic risk

Overview

The skill does what it claims, but its automatic OCR path can run a local Python adapter and may send rendered PDF pages to an external vision service without clear consent or scoping.

Review before installing. Use --ocr none for sensitive PDFs unless you explicitly trust the OCR path, and only set BAILIAN_ADAPTER or --bailian-adapter to adapter code you have inspected and trust. Be aware that scanned PDFs may be rendered to images for OCR and that the documented summary mode does not actually reduce converted content.

Vulnerability Patterns
  • Tool Hijacking and SpoofingModifies or replaces tools so legitimate-looking calls execute attacker logic
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
Findings (3)

T07 · Tool Hijacking and Spoofing

Warning
Location
scripts/pdf2md.py:48
Finding

Automatic Import and Execution of Untrusted Python OCR Adapters

Content
View full analysis

Vulnerability Details

File Location: scripts/pdf2md.py:48-58, 102-119
Vulnerability Type: Untrusted local module loading and arbitrary code execution
Risk Level: Medium

Vulnerable Code

python
def find_bailian_adapter():
    """定位百炼 CLI adapter。

    优先级:
    1. 环境变量 BAILIAN_ADAPTER 指定的路径
    2. 命令行 --bailian-adapter 参数(在 main 中处理)
    3. 默认路径(若存在)
    """
    env_path = os.environ.get("BAILIAN_ADAPTER")
    if env_path and os.path.exists(env_path):
        return env_path
    candidates = [
        os.path.expanduser("~/bailian_cli_adapter.py"),
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "bailian_cli_adapter.py"),
    ]
    for c in candidates:
        if os.path.exists(c):
            return c
    return None
python
adapter = find_bailian_adapter()
if not adapter:
    return None
sys.path.insert(0, os.path.dirname(adapter))
try:
    from bailian_cli_adapter import vision_describe
except ImportError:
    try:
        mod_name = os.path.splitext(os.path.basename(adapter))[0]
        mod = __import__(mod_name)
        vision_describe = mod.vision_describe
    except Exception:
        return None

Technical Analysis

The OCR implementation discovers Python adapter files through an environment variable, a command-line override, the user's home directory, or the Skill directory. It then adds the adapter directory to sys.path and imports a module from that directory.

Python executes module-level statements during import. Consequently, loading an adapter is equivalent to executing the adapter as arbitrary Python code. The implementation performs no integrity, ownership, permission, signature, trusted-directory, or canonical-path validation before importing it.

The fixed import of bailian_cli_adapter after modifying sys.path also creates module-resolution ambiguity. A malicious file with that name in the selected ...[truncated 1489 chars]

Remediation
View remediation

Remediation Suggestions

  • Remove implicit adapter discovery from the user's home directory.
  • Require an explicit adapter configuration and clearly warn that adapters are executable code.
  • Resolve the adapter with os.path.realpath() and ensure it remains within an approved directory.
  • Verify file ownership and reject group-writable or world-writable adapter files and parent directories.
  • Authenticate adapters using an allowlisted cryptographic hash or signed package.
  • Avoid inserting arbitrary directories at the beginning of the global sys.path.
  • Prefer a narrowly defined adapter protocol executed in an isolated subprocess instead of importing arbitrary Python into the main process.
  • Run adapters with reduced privileges, filesystem restrictions, network restrictions, resource limits, and a sanitized environment.
  • Require explicit user consent before sending rendered document pages to any remote OCR provider.

T08 · Insecure Dependencies

Note
Location
README.md:19
Finding

Unpinned Third-Party Dependency Installation

Content
View full analysis

Vulnerability Details

File Location: README.md:19
Vulnerability Type: Unpinned and non-reproducible dependency installation
Risk Level: Low

Vulnerable Code

bash
pip install pdfplumber pypdfium2 pillow

Technical Analysis

The installation instructions request the latest versions of three packages and their transitive dependencies without version constraints or integrity hashes. The effective dependency set can therefore change between installations even when the project source remains unchanged.

Python package installation may execute package build or installation logic. If a future dependency or transitive dependency release is compromised, vulnerable, or unexpectedly incompatible, users following this instruction can install affected code without any project-level integrity check.

No direct evidence that the named packages are currently malicious was found. The weakness is the absence of reproducible version and artifact verification.

Attack Path

  1. A named dependency or one of its transitive dependencies publishes a compromised or vulnerable release.
  2. A user follows the documented installation command after that release becomes the version selected by pip.
  3. pip downloads the mutable dependency set from the configured package index.
  4. Package build, installation, or runtime code executes in the user's Python environment.
  5. The compromised component obtains the privileges available to that installation or runtime process.

This path requires a compromised dependency release, package-index compromise, unsafe index configuration, or a vulnerable version selected by the resolver.

Impact Assessment

Impact depends on the compromised component and how the installation is performed. Potential consequences include:

  • Arbitrary code execution during installation or import.
  • Access to files and environment variables available to the Python process.
  • Compromise of co ...[truncated 255 chars]
Remediation
View remediation

Remediation Suggestions

  • Add a dependency lock file containing exact, tested versions.
  • Generate and verify package hashes for all direct and transitive dependencies.
  • Install with a command such as pip install --require-hashes -r requirements.txt.
  • Document the trusted package index and avoid adding untrusted extra indexes.
  • Use an isolated virtual environment rather than system-wide installation.
  • Add automated dependency vulnerability and update monitoring.
  • Review and deliberately update the lock file instead of resolving mutable latest versions during every installation.

T09 · Insecure Skill Coding Practices

Note
Location
scripts/pdf2md.py:275
Finding

Race-Prone Temporary File Creation Using tempfile.mktemp

Content
View full analysis

Vulnerability Details

File Location: scripts/pdf2md.py:275-277
Vulnerability Type: Insecure temporary file creation and local race condition
Risk Level: Low

Vulnerable Code

python
if find_pdftotext():
    txt_path = tempfile.mktemp(suffix=".txt")
    if not run_pdftotext(pdf, txt_path):
        txt_path = None

The resulting path is later supplied to pdftotext:

python
r = subprocess.run([exe, "-layout", pdf, out_txt], capture_output=True)

Technical Analysis

tempfile.mktemp() generates a candidate pathname but does not atomically create or reserve the file. A time-of-check-to-time-of-use window therefore exists between generating the path and the external pdftotext process opening it.

A local attacker who can observe or predict the pathname may create a file or symbolic link at that location first. The behavior then depends on how pdftotext handles the pre-existing path, but it may write extracted content to an attacker-selected target or otherwise interfere with conversion.

Attack Path

  1. The victim starts conversion of a PDF.
  2. tempfile.mktemp() generates a path in the shared temporary directory without creating it.
  3. Before pdftotext opens the path, a local attacker creates a file or symbolic link at that path.
  4. pdftotext processes the attacker-prepared path as its output destination.
  5. Depending on platform and utility behavior, extracted text may be redirected, conversion may be disrupted, or a victim-writable target may be overwritten.

Exploitation requires local access, the ability to interact with the temporary directory, and successful timing or prediction of the generated name.

Impact Assessment

Potential impact includes:

  • Disclosure of extracted PDF text to another local user.
  • Overwriting or corrupting files writable by the victim account.
  • Denial of service or manipulation of conversion results.

The process doe ...[truncated 148 chars]

Remediation
View remediation

Remediation Suggestions

  • Replace tempfile.mktemp() with an API that creates the file atomically, such as tempfile.mkstemp().
  • Prefer a private tempfile.TemporaryDirectory() and create all intermediate files inside it.
  • Ensure temporary files and directories use restrictive permissions.
  • Close the descriptor returned by mkstemp() only when required for compatibility, while retaining exclusive ownership of the created path.
  • Delete temporary resources in a finally block so exceptions do not leave sensitive extracted text behind.
  • Where supported, avoid pathname-based intermediate files by using pipes or securely opened descriptors.
Vulnerability Patterns
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
Findings (11)

Missing User Warnings

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill offers OCR through an external service ('百炼 qwen3-vl-plus' via adapter) but does not clearly warn that document pages may be transmitted to a remote provider. Because PDFs often contain confidential financial, legal, or personal data, silent remote OCR can cause unintended data exfiltration, privacy violations, or regulatory exposure.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The trigger list is excessively broad and matches many ordinary PDF- or token-related user requests, which can cause the skill to activate outside its narrowly intended context. Over-broad activation increases the chance of the agent steering users into file conversion workflows unnecessarily, including processing sensitive documents and invoking downstream tools without sufficiently specific user intent.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 81)May include surrounding context.

python
exe = find_pdftotext()
    if not exe:
        return False
    r = subprocess.run([exe, "-layout", pdf, out_txt], capture_output=True)
    return r.returncode == 0 and os.path.exists(out_txt)

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 93)May include surrounding context.

python
total_chars = len(total.strip())
    # 页数
    pages = 1
    r = subprocess.run([find_pdftotext(), "-v"], capture_output=True)
    info = subprocess.run(
        [find_pdftotext() or "pdftotext", pdf, "-"],
        capture_output=True)

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 94)May include surrounding context.

python
# 页数
    pages = 1
    r = subprocess.run([find_pdftotext(), "-v"], capture_output=True)
    info = subprocess.run(
        [find_pdftotext() or "pdftotext", pdf, "-"],
        capture_output=True)
    # 用 pdfinfo 更可靠

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 100)May include surrounding context.

python
# 用 pdfinfo 更可靠
    pdfinfo = shutil.which("pdfinfo")
    if pdfinfo:
        r2 = subprocess.run([pdfinfo, pdf], capture_output=True, text=True)
        m = re.search(r"Pages:\s+(\d+)", r2.stdout)
        if m:
            pages = int(m.group(1))

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The OCR path renders PDF pages to images and sends them to vision_describe, which appears to use an external OCR/model service, without a prominent user-facing disclosure or explicit consent at runtime. In a document-processing skill, this can leak sensitive document contents to a third party, making the context materially more dangerous because PDFs commonly contain confidential data.

Content

No source excerpt is available for this finding.

Dynamic import via __import__()

Medium
Category
Dangerous Code Execution
Confidence
95% confidence
Finding

The code modifies sys.path based on an environment variable or CLI-supplied adapter path and then dynamically imports a module with import. That allows loading and executing attacker-controlled Python code if an untrusted path is supplied, leading to arbitrary code execution in the current process.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 125)May include surrounding context.

python
except ImportError:
        try:
            mod_name = os.path.splitext(os.path.basename(adapter))[0]
            mod = __import__(mod_name)
            vision_describe = mod.vision_describe
        except Exception:
            return None

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The CLI help text says summary=只保留前几页/高密度内容, implying a reduced-content conversion mode. However, args.mode is only passed into token_report for display and is not used to limit pages, filter content density, or otherwise alter extraction/OCR behavior anywhere in the conversion flow.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · scripts/pdf2md.py (reported line 308)May include surrounding context.

python
# OCR 不可用 → 回退 tesseract
            tess = find_tesseract()
            if tess and txt_path:
                r = subprocess.run([tess, pdf, "stdout", "-l", "chi_sim+eng"],
                                   capture_output=True)
                md_text = r.stdout.decode("utf-8", errors="ignore")
                write_plain(md_text, out_md)

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The Tesseract fallback hard-codes -l chi_sim+eng, which imposes a Chinese-plus-English language setting regardless of the document language or user preference. This is a natural-language policy issue because the skill forces a locale/language choice rather than offering a configurable or opt-in selection.

Content

No source excerpt is available for this finding.