Back to skill

Security audit

论文格式检查

Security checks for vulnerabilities and agentic risk

Overview

This skill is a Chinese thesis DOCX formatting checker with local report/output file behavior that is mostly disclosed and purpose-aligned.

Install only if you need Chinese thesis DOCX format checking, and use it on documents you trust. Review generated reports and formatted DOCX outputs before submitting academic work, avoid using the same path for input and output, and run it in a constrained environment if processing DOCX files from other people.

Vulnerability Patterns
  • 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
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (2)

T09 · Insecure Skill Coding Practices

Warning
Location
risk_report.py:511
Finding

Unbounded DOCX Archive Extraction Enables Resource-Exhaustion Attacks

Content
View full analysis

Vulnerability Details

File Location: risk_report.py:511-517
Vulnerability Type: Unrestricted archive extraction and decompression bomb exposure
Risk Level: Medium

python
tmpdir = tempfile.mkdtemp(prefix="risk_")
all_issues = []
sections_count = 0
try:
    with zipfile.ZipFile(src, "r") as z:
        z.extractall(tmpdir)
    _, body = parse_document(tmpdir)

Related unbounded ZIP-entry reads also occur at reader.py:624-632 and template_reader.py:477-485.

Technical Analysis

A DOCX file is a ZIP archive containing OOXML resources. The code extracts every archive member without first enforcing limits on:

  • The number of archive members
  • Individual or aggregate expanded sizes
  • Compression ratios
  • Available temporary-disk capacity
  • XML input size
  • Processing time

An attacker can construct a small, highly compressed DOCX whose expanded contents consume a large amount of disk space. Alternatively, oversized XML entries can exhaust memory when subsequently loaded and parsed.

The temporary directory is eventually removed in a finally block, but cleanup only occurs after extraction returns or raises an exception. It does not prevent resource exhaustion while decompression is in progress.

Attack Path

  1. An attacker creates a ZIP bomb or otherwise oversized archive with a .docx extension.
  2. The attacker supplies it as a thesis document for analysis.
  3. A user or Agent invokes the documented risk_report.py command.
  4. ZipFile.extractall() expands all entries into the system temporary directory without resource limits.
  5. Disk space, memory, or CPU is exhausted before analysis completes.
  6. The audit process, other processes sharing the host, or the host itself may become unavailable.

Impact Assessment

Exploitation does not grant elevated privileges or arbitrary code execution. The attacker obtains a denial-of-service capability within the privileges ...[truncated 397 chars]

Remediation
View remediation

Remediation Suggestions

  • Do not call extractall() on an untrusted DOCX archive.
  • Read only the OOXML entries required by the analysis, such as word/document.xml, selected header and footer files, styles, and theme data.
  • Inspect every ZipInfo before processing and reject archives that exceed defined limits for:
    • Total entry count
    • Maximum compressed and expanded size per entry
    • Maximum aggregate expanded size
    • Maximum compression ratio
  • Reject encrypted entries, unsupported compression methods, duplicate critical OOXML entries, and malformed member names.
  • Normalize and validate member paths before any extraction, ensuring that each destination remains under the temporary directory.
  • Check available disk capacity before extraction if extraction remains necessary.
  • Apply execution timeouts and memory limits when processing documents from untrusted users.
  • Handle limit violations with a controlled error and ensure temporary resources are deleted.

T09 · Insecure Skill Coding Practices

Warning
Location
reader.py:624
Finding

Untrusted OOXML Is Parsed Without Explicit XML Security Controls

Content
View full analysis

Vulnerability Details

File Location: reader.py:624-632
Vulnerability Type: Unhardened XML parsing of attacker-controlled DOCX content
Risk Level: Medium

python
def __init__(self, docx_path):
    self.docx_path = docx_path
    self.z = zipfile.ZipFile(docx_path, 'r')
    self.resolver = StyleResolver(self.z)
    self.paragraphs = []
    self._parse()

def _parse(self):
    """Parse all paragraphs."""
    doc_root = etree.fromstring(self.z.read('word/document.xml'))

The same parsing pattern is present at:

  • reader.py:63-65
  • reader.py:99-100
  • template_reader.py:63-65
  • template_reader.py:99-100
  • template_reader.py:477-485
  • risk_report.py:58
  • risk_report.py:126
  • risk_report.py:155

Technical Analysis

XML data originating from user-supplied DOCX files is passed to lxml.etree.fromstring() or lxml.etree.parse() without an explicitly hardened parser. The implementation does not directly disable:

  • DTD loading
  • Entity resolution
  • Network access by the XML parser
  • Oversized-tree processing
  • Excessive XML depth or input size

Consequently, security behavior depends on the installed lxml and libxml2 versions and their defaults. Crafted declarations, deeply nested structures, or entity-heavy XML can cause excessive parser resource consumption. Under a configuration or dependency version that permits external entity resolution, the same pattern may expose local files or initiate parser-level external resource access.

Independently of entity behavior, the complete XML entry is first loaded into memory with self.z.read(...), so an oversized decompressed entry can cause memory exhaustion before parsing begins.

Attack Path

  1. An attacker creates a DOCX containing a malicious word/document.xml, word/styles.xml, theme file, header, or footer.
  2. The XML contains excessive nesting, entity expansion constructs, or an oversized decompres ...[truncated 1125 chars]
Remediation
View remediation

Remediation Suggestions

  • Create and consistently use an explicit hardened parser:
python
parser = etree.XMLParser(
    resolve_entities=False,
    load_dtd=False,
    no_network=True,
    huge_tree=False,
    recover=False,
)
root = etree.fromstring(xml_data, parser=parser)
  • Reject XML containing a DOCTYPE declaration before parsing.
  • Enforce a strict maximum decompressed size for every XML archive entry before calling ZipFile.read().
  • Prefer bounded streaming reads rather than loading arbitrary entries fully into memory.
  • Enforce maximum nesting depth, element count, text size, and overall processing time.
  • Apply the same parser configuration to document, style, theme, header, and footer XML.
  • Keep lxml and libxml2 patched and pinned to reviewed versions.
  • Run untrusted document analysis in a sandbox with restricted filesystem access, no unnecessary network access, and operating-system resource limits.
Vulnerability Patterns
  • System Prompt LeakageDirect Leakage, Indirect Extraction, Tool-Based Exfiltration
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
Findings (30)

Tp4

High
Category
MCP Tool Poisoning
Confidence
91% confidence
Finding

The declared function promises comprehensive template-based format comparison, but the observed behavior appears to emphasize risk auditing and undeclared heuristic checks while omitting several advertised categories. This is primarily a trust and safety issue: users may rely on the skill for compliance decisions that it is not actually equipped to make.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
89% confidence
Finding

The declared function promises comprehensive template-based format comparison, but the observed behavior appears to emphasize risk auditing and undeclared heuristic checks while omitting several advertised categories. This is primarily a trust and safety issue: users may rely on the skill for compliance decisions that it is not actually equipped to make.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
93% confidence
Finding

The declared function promises comprehensive template-based format comparison, but the observed behavior appears to emphasize risk auditing and undeclared heuristic checks while omitting several advertised categories. This is primarily a trust and safety issue: users may rely on the skill for compliance decisions that it is not actually equipped to make.

Content

No source excerpt is available for this finding.

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · engine/style_registry.py (reported line 469)May include surrounding context.

python
for rule in self._special_rules:
            for kw in rule.get('keywords', []):
                if kw in text:
                    return rule
        return None

    def _apply_special_format(self, p, fmt: Dict):

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · reader.py (reported line 817)May include surrounding context.

python
for rule in self._special_rules:
            for kw in rule.get('keywords', []):
                if kw in text:
                    return rule
        return None

    def _apply_special_format(self, p, fmt: Dict):

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · template_reader.py (reported line 641)May include surrounding context.

python
for rule in self._special_rules:
            for kw in rule.get('keywords', []):
                if kw in text:
                    return rule
        return None

    def _apply_special_format(self, p, fmt: Dict):

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · reader.py (reported line 334)May include surrounding context.

python
for pattern, itype in INSTRUCTION_PATTERNS:
        for m in pattern.finditer(text):
            instructions.append({'type': itype, 'value': m.group(1) if m.lastindex else m.group(0), 'span': m.span()})
    return instructions


def classify_template_role(paragraph_text, index, total_paras, pStyle_id=None, pStyle_name=''):

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · template_reader.py (reported line 317)May include surrounding context.

python
for pattern, itype in INSTRUCTION_PATTERNS:
        for m in pattern.finditer(text):
            instructions.append({'type': itype, 'value': m.group(1) if m.lastindex else m.group(0), 'span': m.span()})
    return instructions


def classify_template_role(paragraph_text, index, total_paras, pStyle_id=None, pStyle_name=''):

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · reader.py (reported line 704)May include surrounding context.

python
# 3. 样式库独立输出,不混入 rules
        style_library = self._extract_style_rules()
        return rules, style_library

    def _build_rule(self, role, exemplars):
        """从范例段落构建单条规则"""

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · reader.py (reported line 1000)May include surrounding context.

python
# 3. 样式库独立输出,不混入 rules
        style_library = self._extract_style_rules()
        return rules, style_library

    def _build_rule(self, role, exemplars):
        """从范例段落构建单条规则"""

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · reader.py (reported line 1287)May include surrounding context.

python
# 3. 样式库独立输出,不混入 rules
        style_library = self._extract_style_rules()
        return rules, style_library

    def _build_rule(self, role, exemplars):
        """从范例段落构建单条规则"""

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · template_reader.py (reported line 557)May include surrounding context.

python
# 3. 样式库独立输出,不混入 rules
        style_library = self._extract_style_rules()
        return rules, style_library

    def _build_rule(self, role, exemplars):
        """从范例段落构建单条规则"""

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · template_reader.py (reported line 824)May include surrounding context.

python
# 3. 样式库独立输出,不混入 rules
        style_library = self._extract_style_rules()
        return rules, style_library

    def _build_rule(self, role, exemplars):
        """从范例段落构建单条规则"""

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
84% confidence
Finding

The skill advertises command-line operations that read and write local DOCX/JSON/Markdown files, but the manifest does not declare any tool scope or permission boundaries. In an agent environment, undeclared file access increases the chance that the skill can be invoked with broader filesystem reach than users expect, enabling unintended reading or overwriting of documents.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
84% confidence
Finding

The description and metadata present the tool as Chinese-only (e.g. "中文论文格式检查工具" and the zh designation) but do not state that this is an optional locale mode or a region-specific limitation. Under the policy, forcing a specific language without user opt-in is a natural-language policy concern.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The example trigger "帮我检查论文格式,模板是xxx,论文是xxx" is a natural conversational request rather than a narrowly scoped invocation phrase. The file does not provide explicit activation boundaries, exclusions, or negative examples, so the skill could be invoked on general formatting-help requests unintentionally.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The top-level natural-language description is entirely in Chinese and presents the engine as a Chinese论文排版 tool without any indication that language is optional or region-specific by design. Under the policy rule, forcing a specific language/locale without user opt-in is a natural-language policy concern.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill metadata describes a format-checking/comparison tool, but format_document performs extensive in-place document transformations and writes a modified output file. This mismatch is dangerous because users or calling agents may grant read/analysis trust while unintentionally allowing content modification, which can alter thesis documents, damage formatting fidelity, or overwrite expected outputs in automated workflows.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The function saves a modified document to disk as part of the normal code path without any explicit confirmation, dry-run default, or user-facing warning in this layer. In an agent setting, silent writes are dangerous because they can unexpectedly alter user documents or produce deceptive 'analysis' results that are actually transformed artifacts, especially when combined with the skill's analysis-oriented description.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This code file uses Chinese-only natural-language documentation and also hardcodes Chinese defaults such as Chinese fonts and Chinese header text, indicating the skill is oriented to a specific language/locale. Under the policy, locale-specific behavior should offer user choice or provide clear justification, which is not present here.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This Python file contains natural-language strings that present the tool entirely in Chinese, including the title, usage text, and later all user-facing report/output text. Under the language/locale policy, forcing a specific language without user opt-in is a policy concern unless the locale restriction is explicitly justified, which is not stated here.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
84% confidence
Finding

This codebase’s natural-language instructions and API-facing documentation are written entirely in Chinese and explicitly describe handling of Chinese/English-specific document sections and fonts. Under the stated policy, forcing a specific language or locale without opt-in can be a violation unless the locale restriction is clearly documented and justified as region-specific.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
72% confidence
Finding

The module presents itself as a thesis formatting engine, but also alters Python import resolution globally at L40 before importing validator.check. This is not reflected in the surrounding documentation and contradicts a straightforward, self-contained engine description by introducing hidden runtime side effects unrelated to thesis formatting itself.

Content

No source excerpt is available for this finding.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
88% confidence
Finding

The logger creates persistent log files for document-processing operations without clearly constraining or disclosing what data may be recorded. Even though this file mostly logs paths, progress, summaries, and errors, document paths and exception messages can contain sensitive user or institutional information, creating unintended local data exposure and retention.

Content

No source excerpt is available for this finding.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Confidence
50% confidence
Finding

Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Content

Scanner excerpt · engine/__init__.py (reported line 73)May include surrounding context.

python
def log(msg, level="info"):
    """输出日志(控制台 + 文件)"""
    print(f"[format_thesis] {msg}", file=sys.stderr)
    getattr(_logger, level, _logger.info)(msg)


# ═══════════════════════════════════════════════

Static analysis

No suspicious patterns detected.