Back to skill

Security audit

Generate a Word (.docx) document based on the content list provided by the user.

Security checks for vulnerabilities and agentic risk

Overview

This Word document skill has a legitimate purpose, but it automatically installs an unpinned Python package and can write to caller-chosen file paths without clear confirmation or containment.

Review before installing. The skill appears to do what it says, but only run it in an environment where automatic pip installs are acceptable, or require dependencies to be installed separately with pinned versions. Use a dedicated output folder and avoid passing sensitive or arbitrary file paths as the document filename.

Vulnerability Patterns
  • 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
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (2)

T08 · Insecure Dependencies

Error
Location
generate-word-doc.py:8
Finding

Automatic Installation of an Unpinned Third-Party Dependency

Content
View full analysis

Vulnerability Details

File Location: generate-word-doc.py, lines 8-27
Vulnerability Type: Supply-chain exposure through automatic runtime dependency installation
Risk Level: High

Complete Code Snippet

python
def install_package(package_name):
    """
    自动调用 pip 安装指定的库
    """
    print(f"⚠️ 检测到缺少库 '{package_name}',正在自动安装...")
    try:
        # 使用 sys.executable 确保安装到当前运行的 Python 环境中
        subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
        print(f"✅ 库 '{package_name}' 安装成功!")
    except subprocess.CalledProcessError:
        print(f"❌ 安装失败,请手动运行: pip install {package_name}")
        sys.exit(1)

# 尝试导入 docx,如果失败则安装
try:
    import docx
except ImportError:
    # 注意:pip 安装名是 'python-docx',但导入名是 'docx'
    install_package("python-docx")
    import docx  # 安装后再次导入

Technical Analysis

The module automatically invokes pip install python-docx when docx cannot be imported. The dependency is identified only by its mutable package name; no exact version, artifact hash, trusted repository, or package-signature verification is enforced.

Although the subprocess call uses an argument array and is not vulnerable to shell command injection, package installation inherently executes package build and installation logic. The effective package source also depends on the process's pip configuration, environment variables, configured indexes, and network environment. Consequently, a compromised package release, malicious transitive dependency, attacker-controlled package index, or manipulated pip configuration could introduce executable code after the skill has already been reviewed.

The installation occurs as an import-time side effect without explicit user confirmation. This expands a document-formatting operation into a network-facing software installation operation.

Attack Path

  1. The skill runs in an environment where the docx modu ...[truncated 1134 chars]
Remediation
View remediation

Remediation Suggestions

  1. Remove automatic dependency installation from module import and execution paths.
  2. Declare python-docx in a reviewed dependency manifest or lock file using an exact approved version.
  3. Require cryptographic hashes for downloaded artifacts, such as pip's --require-hashes workflow.
  4. Install dependencies during a controlled build or deployment phase rather than while processing a document request.
  5. Restrict installation to a trusted package repository and prevent unreviewed user or environment configuration from changing the index.
  6. Run the skill inside a least-privileged virtual environment or container with limited filesystem, credential, and network access.
  7. If runtime installation is unavoidable, obtain explicit user approval and verify the exact version and artifact hash before installation.

T09 · Insecure Skill Coding Practices

Warning
Location
generate-word-doc.py:39
Finding

Caller-Controlled Output Path Permits Unintended File Writes and Overwrites

Content
View full analysis

Vulnerability Details

File Location: generate-word-doc.py, lines 39-41 and 82-89
Vulnerability Type: Unrestricted file path and silent overwrite
Risk Level: Medium

Complete Code Snippet

python
# 1. 文件名处理
if not filename.endswith('.docx'):
    filename += '.docx'

print(f"📄 正在创建文档: {filename} ...")
python
# 4. 保存文件
try:
    doc.save(filename)
    abs_path = os.path.abspath(filename)
    print(f"✅ 成功!文件已保存至: {abs_path}")
    return abs_path
except PermissionError:
    print(f"❌ 错误: 无法保存。请关闭已打开的 '{filename}' 文档后重试。")
except Exception as e:
    print(f"❌ 未知错误: {e}")

Technical Analysis

create_word_file() accepts a caller-supplied filename and passes it directly to doc.save(). The only transformation is appending .docx when the supplied string does not already end with that suffix.

The implementation does not reject absolute paths, resolve and validate traversal components, confine output to an approved directory, detect symbolic-link targets, or prevent replacement of an existing file. A filename such as ../../shared/report.docx or an absolute path therefore directs the write outside the intended working directory. If the destination already exists, the save operation can replace it without confirmation.

Requiring a .docx suffix reduces the range of obvious target filenames but does not establish a security boundary. Existing Word documents and any other writable target ending in .docx remain exposed. Filesystem links may also redirect a .docx path to another writable target, depending on platform behavior and deployment conditions.

Attack Path

  1. An untrusted user or upstream component gains control over the filename argument supplied to create_word_file().
  2. The attacker provides an absolute path or a traversal path ending in .docx, such as ../../shared/important.docx.
  3. The suffix check accepts the path without normalization ...[truncated 1013 chars]
Remediation
View remediation

Remediation Suggestions

  1. Configure a dedicated output directory that is not caller-controlled.
  2. Accept a simple document name rather than an arbitrary filesystem path.
  3. Reject absolute paths and names containing path separators or traversal components.
  4. Resolve the final path and verify with Path.is_relative_to() or an equivalent canonical-path check that it remains beneath the approved output directory.
  5. Reject existing destinations by default or require explicit confirmation before replacement.
  6. Use exclusive file creation and an atomic save strategy to reduce overwrite and race-condition risks.
  7. Account for symbolic links by rejecting linked destinations or performing safe directory-relative operations supported by the platform.
  8. Run the skill with filesystem permissions restricted to its designated output directory.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (7)

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

This skill auto-installs python-docx when missing, giving the skill the ability to modify the environment and fetch executable code from package repositories. In the context of a simple Word document generator, that capability is unnecessary at runtime and increases risk from dependency confusion, malicious package updates, or unexpected environment changes.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
93% confidence
Finding

The script invokes pip through subprocess to install a package at runtime, which expands the skill's behavior from document generation into package management and remote code acquisition. Although the package name is hardcoded and shell injection is not present, automatic installation executes unreviewed third-party code without explicit user consent and can be abused in compromised package-index or dependency-supply-chain scenarios.

Content

Scanner excerpt · generate-word-doc.py (reported line 14)May include surrounding context.

python
print(f"⚠️ 检测到缺少库 '{package_name}',正在自动安装...")
    try:
        # 使用 sys.executable 确保安装到当前运行的 Python 环境中
        subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
        print(f"✅ 库 '{package_name}' 安装成功!")
    except subprocess.CalledProcessError:
        print(f"❌ 安装失败,请手动运行: pip install {package_name}")

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The code performs pip installation automatically and immediately when ImportError occurs, with no user confirmation or policy check. That creates a trust boundary violation because running the skill can silently change the host environment and execute installation-time code from an external package.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The skill describes saving user-provided content as a file but does not clearly disclose that content will be written to a local .docx file. In a document-generation context, this omission can cause users to unknowingly persist sensitive or regulated data to disk, increasing privacy and data-handling risk.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The trigger keywords are broad and include generic terms like "Word," "Report," and "Summary," which can cause the skill to activate for ordinary conversation unrelated to document generation. Unintended invocation can lead to surprising file creation behavior, misrouting user requests, and accidental handling or storage of sensitive content.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
95% confidence
Finding

The script's comments and all user-visible print messages are written in Chinese, with no indication that the user can choose another language or that the tool is intended only for a Chinese-speaking context. This creates a locale/language policy concern because the skill imposes a specific language without user opt-in or justification.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
80% confidence
Finding

The trigger list mixes English and Chinese activation keywords, but the skill does not explain whether language handling is optional, user-selectable, or limited to a particular locale. This can create a language-policy issue because the skill implicitly defines supported languages without user opt-in or documented scope.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.