Back to skill

Security audit

高转化广告图片生成与编辑

Security checks for vulnerabilities and agentic risk

Overview

The skill is mostly coherent for AI image generation, but it has a real file-write safety issue when saving API-returned results.

Review this before installing. Use it only with images you are comfortable uploading to AI Hive, prefer an isolated virtual environment, avoid running it with elevated privileges, and set a dedicated output directory. The publisher should fix path containment, validate upload/download hosts, and add download size limits before this is treated as routine-risk.

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 (3)

T09 · Insecure Skill Coding Practices

Error
Location
scripts/imagegen.py:352
Finding

API-Controlled Path Traversal and Arbitrary File Overwrite

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py:352-364
Vulnerability Type: Path traversal and arbitrary file overwrite
Risk Level: High

Vulnerable Code

python
result_url = item.get("resultUrl")
if not result_url:
    continue
ext = ".mp4" if "video" in task_type.lower() else ".png"
filename = f"{task_type}_{task_id}_{i+1}{ext}"
out_path = out_dir / filename
download_file(result_url, out_path)

# 尾帧
for item in succeeded:
    last_frame = item.get("lastFrameUrl")
    if last_frame:
        out_path = out_dir / f"{task_type}_{task_id}_lastframe.png"
        download_file(last_frame, out_path)

Technical Analysis

The remotely supplied taskType value and generated taskId are interpolated directly into local filenames. Neither value is normalized or checked for path separators, .. components, absolute paths, or other unsafe characters.

Joining an untrusted filename to out_dir with the / operator does not guarantee that the resulting path remains inside that directory. A crafted value containing traversal components can cause out_path to resolve outside the intended download directory. The download_file function subsequently opens that path in wb mode, which creates or overwrites the target file.

This vulnerability depends on malicious or compromised API responses. It does not require the API key to be disclosed.

Attack Path

  1. The user submits an image-generation request to the configured API.
  2. The remote service, or an attacker controlling the service response, returns a crafted taskId or taskType containing path traversal components.
  3. The task response includes a resultUrl or lastFrameUrl containing attacker-controlled content.
  4. The client constructs a path such as out_dir / "../../../../target_<id>.png".
  5. download_file opens the resolved path using wb.
  6. An existing file writable by the current user is overwritten, ...[truncated 532 chars]
Remediation
View remediation

Remediation Suggestions

  • Do not derive local filenames from remote metadata. Generate filenames locally with UUIDs or strictly formatted counters.
  • If remote identifiers must be retained, allow only a narrow character set such as ASCII letters, digits, hyphens, and underscores.
  • Explicitly reject /, \, .., absolute paths, drive prefixes, control characters, and reserved filesystem names.
  • Resolve both the output directory and candidate path, then verify that the candidate remains beneath the output directory using Path.relative_to() or an equivalent containment check.
  • Consider creating files with exclusive mode to prevent unintended overwrites.
  • Apply the same validation to normal result files and last-frame files.

Example containment strategy:

python
import re
import uuid

out_dir = Path(output_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)

safe_task_id = re.sub(r"[^A-Za-z0-9_-]", "_", str(task_id))
filename = f"image_{safe_task_id}_{i + 1}_{uuid.uuid4().hex}.png"
out_path = (out_dir / filename).resolve()
out_path.relative_to(out_dir)

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/imagegen.py:229
Finding

Unrestricted API-Controlled Upload and Download Destinations

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py:229-245 and scripts/imagegen.py:272-288
Vulnerability Type: Unvalidated remote URLs, methods, headers, and redirects
Risk Level: Medium

Vulnerable Code

python
media_id = token["mediaId"]
upload_url = token["upload"]["url"]
upload_method = token["upload"].get("method", "PUT")
upload_headers = token["upload"].get("headers", {})

print(f"[2/3] 上传文件到对象存储...")
with open(str(path), "rb") as f:
    try:
        oss_resp = requests.request(
            upload_method, upload_url, headers=upload_headers,
            data=f, timeout=300,
        )
    except requests.exceptions.RequestException as e:
        raise SystemExit(
            f"OSS 上传网络异常:{e}\n"
            "请检查网络连接或文件大小是否过大"
        )
python
def download_file(url, out_path, timeout=300):
    """流式下载文件,带进度条显示。"""
    print(f"[download] {out_path.name}")
    try:
        resp = requests.get(url, stream=True, timeout=timeout)
        resp.raise_for_status()
        total = int(resp.headers.get("content-length", 0))
        downloaded = 0
        with open(str(out_path), "wb") as f:
            for chunk in resp.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
                    downloaded += len(chunk)

Technical Analysis

The fixed AI Hive API is allowed to supply the upload URL, HTTP method, request headers, result URL, and redirect destination. The client does not validate:

  • The URL scheme.
  • The destination hostname or resolved IP address.
  • Whether the destination is loopback, link-local, private, or a cloud metadata endpoint.
  • Whether the upload method is the expected PUT method.
  • Whether returned headers are safe and necessary.
  • Whether redirects remain on an approved host.
  • The MIME type or maximum size of downloaded content.

Although the API key is not forwarde ...[truncated 1663 chars]

Remediation
View remediation

Remediation Suggestions

  • Require HTTPS for upload and download URLs.
  • Maintain an explicit allowlist of approved object-storage and result-download hosts.
  • Resolve destination hostnames and reject loopback, private, link-local, multicast, reserved, and cloud metadata addresses.
  • Restrict uploads to the expected PUT method.
  • Accept only a documented allowlist of upload headers rather than forwarding every server-provided header.
  • Disable redirects or validate every redirect destination against the same scheme, hostname, port, and IP restrictions.
  • Set separate connection and read timeouts.
  • Enforce a maximum upload and download size.
  • Validate the returned Content-Type against expected image formats before writing the response.
  • Abort streaming when the accumulated byte count exceeds the configured limit, even when Content-Length is absent or inaccurate.
  • Consider binding upload tokens to expected object-storage hosts on the trusted server side.

T08 · Insecure Dependencies

Note
Location
SKILL.md:75
Finding

Unpinned Third-Party Dependency Installation

Content
View full analysis

Vulnerability Details

File Location: SKILL.md:75
Vulnerability Type: Unpinned dependency and mutable supply-chain resolution
Risk Level: Low

Vulnerable Code

bash
pip3 install requests

The same unpinned installation guidance also appears in scripts/imagegen.py:7 and scripts/imagegen.py:21.

Technical Analysis

The installation command retrieves whichever requests version and transitive dependencies are selected by the user's current package index at installation time. No reviewed version, lock file, integrity hash, or trusted index is specified.

This does not prove that the current requests package is malicious. The security issue is that installation behavior is mutable and is not reproducible from the audited project. A compromised package release, compromised index, unsafe alternate index configuration, or incompatible future release could cause unreviewed code to be installed and executed.

Attack Path

  1. The user follows the documented pip3 install requests instruction.
  2. pip resolves requests and its dependencies using the user's configured package indexes.
  3. A compromised index, malicious replacement, or compromised future release supplies untrusted package content.
  4. The package is installed into the selected Python environment.
  5. Package installation hooks or imported package code execute with the privileges of the user running the installation or Skill.

Impact Assessment

Successful supply-chain compromise could execute code with the privileges of the installing user and affect the Python environment in which the dependency is installed. If the user installs packages globally or with elevated privileges, the impact could extend to system-wide Python components. Under normal non-privileged installation, the scope is generally limited to the user's environment and accessible files.

Remediation
View remediation

Remediation Suggestions

  • Pin requests to a reviewed version or tightly controlled compatible range.
  • Maintain a lock file that pins all transitive dependencies.
  • Use hash verification, such as pip install --require-hashes -r requirements.txt.
  • Document and enforce a trusted package index.
  • Install dependencies in an isolated virtual environment rather than globally.
  • Periodically update pinned versions after vulnerability and compatibility review.

Example:

text
requests==<reviewed-version> --hash=sha256:<verified-package-hash>
Vulnerability Patterns
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
Findings (3)

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
93% confidence
Finding

The skill invokes a local Python script, installs dependencies, reads local image files, writes generated outputs, and sends requests to a remote API, but it does not declare any explicit tool/permission scope. That mismatch weakens least-privilege controls and makes it harder for a host agent or reviewer to understand and constrain what the skill may access before execution.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The description and operating instructions are written as mandatory Chinese-language guidance, and the file does not offer an alternative language or user opt-in for locale. Under the policy criteria, forcing a specific language without user choice is a natural-language policy violation unless clearly justified as region-specific.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The module docstring and all user-facing CLI guidance are written in Chinese, and the skill does not indicate that Chinese is optional or that the tool is intended only for a Chinese-speaking or region-specific audience. Under the stated policy, forcing a specific language without user opt-in is a natural-language policy violation.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.