Back to skill

Security audit

Nano Banana 2 图片换背景

Security checks for vulnerabilities and agentic risk

Overview

This skill is a disclosed image background replacement workflow that uses a fixed AI Hive image model and user-provided images, with some implementation risks users should understand.

Install only if you are comfortable sending selected reference images and prompts to AI Hive and storing an AI Hive API key locally. Use it with images you are authorized to edit, avoid sensitive files, and prefer a dedicated output directory until the download filename and result URL validation issues are fixed.

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
scripts/imagegen.py:350
Finding

Path Traversal Through Server-Controlled Download Filenames

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py:350-358
Vulnerability Type: Path traversal and arbitrary file overwrite
Risk Level: Medium

python
task_type = task.get("taskType", "task")
for i, item in enumerate(succeeded):
    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)

Technical Analysis

The taskType value is obtained from an API response and incorporated directly into a local output path. It is not restricted to a safe filename character set, normalized, or checked to ensure that the resulting path remains under out_dir.

A malicious value containing traversal components such as ../../ can escape the intended output directory. A value beginning with an absolute path can also cause Python's pathlib path composition to disregard out_dir. The subsequent download_file call opens the resulting path in wb mode, truncating an existing file if one is present.

Exploitation requires control over, or compromise of, the relevant AI Hive API response. The final filename is partially constrained by the appended task identifier, sequence number, and extension, but this does not prevent writes outside the configured directory.

Attack Path

  1. A user submits an image-generation request.
  2. The client polls the remote API for task results.
  3. A compromised or malicious API response supplies a crafted taskType containing traversal components or an absolute path.
  4. The client concatenates that value with task_id, the result index, and an extension.
  5. out_dir / filename resolves to a location outside the intended download directory.
  6. Content retrieved from resultUrl is opened in wb mode and written to the attacker-selected path.

Impact As

...[truncated 408 chars]

Remediation
View remediation

Remediation Suggestions

  • Do not use API-controlled metadata as a local filename.
  • Generate filenames locally from a random identifier or a strictly validated task identifier.
  • If taskType must be retained, allow only a narrow character set such as ASCII letters, digits, underscores, and hyphens.
  • Resolve the output directory and destination path before writing, then verify that the destination remains a child of the output directory.
  • Open newly created files with exclusive-create semantics where overwriting is unnecessary.
  • Reject absolute paths, path separators, . components, and .. components.

Example containment check:

python
import re

safe_task_type = re.sub(r"[^A-Za-z0-9_-]", "_", task_type)
base = out_dir.resolve()
destination = (base / f"{safe_task_type}_{task_id}_{i+1}{ext}").resolve()

if destination.parent != base:
    raise SystemExit("Unsafe output path")

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/imagegen.py:238
Finding

Unrestricted Server-Provided Result Downloads

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py:238-260
Vulnerability Type: Unvalidated remote URL retrieval and unbounded file download
Risk Level: Medium

python
def download_file(url, out_path, timeout=300):
    """Stream and download a file with progress display."""
    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)
                    if total > 0:
                        pct = int(downloaded * 100 / total)
                        bar = "█" * (pct // 5) + "░" * (20 - pct // 5)
                        print(f"\r  {bar} {pct}% ({downloaded // 1024}KB)", end="", flush=True)
        print()
        size_mb = downloaded / (1024 * 1024)
        print(f"[ok] {out_path} ({size_mb:.1f} MB)")
    except requests.exceptions.RequestException as e:
        print(f"\n[error] Download failed: {e}", file=sys.stderr)

The URL reaches this function from an API-controlled task result:

python
result_url = item.get("resultUrl")
if not result_url:
    continue
download_file(result_url, out_path)

Technical Analysis

The application downloads resultUrl without validating its scheme, hostname, port, resolved address, redirect destination, response content type, or maximum response size. The default behavior of requests.get also follows redirects.

Consequently, a compromised API response can direct the client to make requests to arbitrary endpoints reachable from the client environment. The response is streamed to disk until the server ends the transfer; a missing or false `Conte ...[truncated 1370 chars]

Remediation
View remediation

Remediation Suggestions

  • Require result URLs to use HTTPS.
  • Maintain an explicit allowlist of trusted object-storage hostnames.
  • Resolve the hostname and reject loopback, link-local, private, reserved, and otherwise disallowed network ranges where applicable.
  • Disable automatic redirects or validate every redirect destination using the same policy.
  • Validate the response Content-Type against the expected image formats.
  • Enforce a strict maximum response size using both Content-Length and a running byte counter.
  • Delete partial files when validation or download fails.
  • Use separate connection and read timeouts and, where supported, enforce an overall operation deadline.

Example size enforcement:

python
MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024

declared_size = int(resp.headers.get("content-length", 0))
if declared_size and declared_size > MAX_DOWNLOAD_BYTES:
    raise SystemExit("Result exceeds the permitted size")

downloaded = 0
with open(out_path, "wb") as output:
    for chunk in resp.iter_content(chunk_size=8192):
        if not chunk:
            continue
        downloaded += len(chunk)
        if downloaded > MAX_DOWNLOAD_BYTES:
            output.close()
            out_path.unlink(missing_ok=True)
            raise SystemExit("Result exceeds the permitted size")
        output.write(chunk)
Vulnerability Patterns
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
Findings (4)

Tp4

High
Category
MCP Tool Poisoning
Confidence
97% confidence
Finding

The documented behavior presents a specialized, policy-constrained background-replacement workflow, but the described commands expose a more general image-generation/editing interface with task creation, querying, initialization, upload/download, and API-key handling. This mismatch is dangerous because users, reviewers, or automated policy systems may grant trust based on the narrow description while the implementation has materially broader capabilities and lacks the promised channel-specific constraints.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
93% confidence
Finding

The skill exposes shell, file, environment, and network-capable commands without declaring any explicit tool scope or permission boundaries. That increases the chance an orchestrator or reviewer will treat it as a narrow image-editing skill while it can actually initialize credentials, make outbound API calls, and read/write local files, which weakens least-privilege controls.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The invocation language is broad enough to match many ordinary image-editing requests across multiple marketplaces and social platforms, which can cause the skill to be selected outside the narrow conditions implied by the workflow. In context, that increases exposure to accidental misuse of its file/network-enabled backend and makes it easier for a generic editing request to trigger a more capable tool than intended.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The module docstring and all user-facing CLI guidance are written in Chinese, and the skill does not indicate any option to choose another language or locale. Under the policy for natural-language violations, forcing a specific language without opt-in is reportable unless the locale constraint is explicitly justified, which is not present here.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.