Back to skill

Security audit

Lazada 电商图片生成与编辑

Security checks for vulnerabilities and agentic risk

Overview

This skill is mostly a coherent AI image workflow, but it has a real API-key exposure risk through custom endpoints and weak URL/download controls.

Install only if you trust AI Hive and the publisher, use a dedicated virtual environment, keep the API key limited and revocable, avoid custom base URLs unless you fully control the endpoint, and prefer --no-download or a constrained output directory when handling untrusted tasks.

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:98
Finding

API Credential Disclosure Through an Unrestricted Base URL

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py, lines 98–106, 118–130, 640–646, and 819–823
Vulnerability Type: User-controlled API endpoint combined with automatic bearer-token transmission
Risk Level: High

Vulnerable Code

python
def _resolve_base_url(self, cli_url):
    if cli_url:
        return cli_url.rstrip("/")
    env_url = os.environ.get("AI_HIVE_BASE_URL")
    if env_url:
        return env_url.rstrip("/")
    file_config = self._read_config_file()
    if file_config.get("base_url"):
        return file_config["base_url"].rstrip("/")
    return DEFAULT_BASE_URL
python
class AiHiveClient:
    """AI Hive OpenAPI HTTP client."""

    def __init__(self, config):
        self.config = config
        self.base = config.base_url
        self.headers = {
            "Authorization": f"Bearer {config.api_key}",
            "Content-Type": "application/json",
        }

    def _url(self, path):
        return f"{self.base}/openapi/v1/{path}"

    def _request(self, method, url, **kwargs):
        self.config.log(f"{method} {url}")
        try:
            resp = requests.request(
                method, url, headers=self.headers,
                timeout=DEFAULT_TIMEOUT, **kwargs
            )
        except requests.exceptions.ConnectionError as e:
            raise SystemExit(
                f"Unable to connect to API server: {url}\n"
                f"Reason: {e}"
            )
        except requests.exceptions.Timeout:
            raise SystemExit(f"API request timed out: {url}")
        except requests.exceptions.RequestException as e:
            raise SystemExit(f"Network request failed: {e}")

        if not resp.ok:
            try:
                detail = resp.json()
            except ValueError:
                detail = resp.text
            raise SystemExit(
                f"API request failed ({resp.s
...[truncated 2244 chars]
Remediation
View remediation

Remediation Suggestions

  1. Default to an immutable allowlist containing only the official HTTPS API origin.
  2. Parse base URLs with urllib.parse.urlparse and reject:
    • Non-HTTPS schemes
    • URLs containing user information
    • Unexpected ports
    • Hosts outside the approved allowlist
  3. Never send an AI Hive API key to a custom host. If custom endpoints are required, use separate credentials scoped to those endpoints.
  4. Require explicit, high-friction confirmation before enabling a custom endpoint.
  5. Reject custom base URLs supplied through ambient environment variables in privileged or automated execution contexts.
  6. Revalidate the destination after redirects, or disable redirects for authenticated API requests.
  7. Document immediate key revocation and rotation procedures if an untrusted endpoint was previously configured.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/imagegen.py:274
Finding

Unvalidated Server-Provided Upload and Download URLs

Content
View full analysis

Vulnerability Details

File Location: scripts/imagegen.py, lines 274–303, 307–329, and 399–414
Vulnerability Type: Server-side request forgery behavior, arbitrary outbound requests, and unbounded file download
Risk Level: Medium

Vulnerable Code

python
def upload_media(client, file_path):
    """Three-step upload: upload-token → PUT → complete. Returns mediaId."""
    path = Path(file_path)
    if not path.is_file():
        raise SystemExit(f"File does not exist: {file_path}")

    filename = path.name
    content_type = guess_mime(str(path))
    size = path.stat().st_size

    token = client.create_upload_token(filename, content_type, size)

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

    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"Object-storage upload failed: {e}")

    if not oss_resp.ok:
        try:
            detail = oss_resp.text
        except Exception:
            detail = "<unable to read response>"
        raise SystemExit(
            f"Object-storage upload failed ({oss_resp.status_code}): {detail}"
        )

    result = client.complete_upload(media_id)
    return media_id
python
def download_file(url, out_path, timeout=300):
    """Stream a remote file to the output path."""
    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(
...[truncated 3327 chars]
Remediation
View remediation

Remediation Suggestions

  1. Parse every server-provided URL before use and require HTTPS.
  2. Maintain an allowlist of approved object-storage and result-delivery domains.
  3. Resolve hostnames and reject loopback, private, link-local, multicast, reserved, and unspecified addresses for both IPv4 and IPv6.
  4. Protect against DNS rebinding by validating the actual connected address or using a controlled networking layer.
  5. Disable redirects, or validate the scheme, hostname, port, and resolved address at every redirect.
  6. Permit only the expected upload method, normally PUT, rather than accepting an arbitrary method from the response.
  7. Filter server-provided upload headers and allow only required storage headers.
  8. Define maximum upload and download sizes. Abort streaming immediately when the enforced byte count is exceeded.
  9. Write downloads to a temporary file and atomically rename them only after successful size and content validation.
  10. Apply image or video signature validation before treating downloaded content as generated media.

T08 · Insecure Dependencies

Warning
Location
SKILL.md:75
Finding

Unpinned Runtime Dependency Installation

Content
View full analysis

Vulnerability Details

File Location: SKILL.md, line 75
Vulnerability Type: Unpinned third-party package installation without integrity verification
Risk Level: Medium

Vulnerable Code

bash
pip3 install requests

Technical Analysis

The installation instructions retrieve the latest available requests package and its transitive dependencies at execution time. No exact version, lock file, package hash, or trusted index configuration is supplied.

This makes the runtime environment non-reproducible and allows dependency contents to change after the Skill has been reviewed. If a future package release, transitive dependency, package-index account, mirror, or network path is compromised, malicious code could be installed into the Python environment.

Package installation executes package build and installation logic with the privileges of the user running pip3. The risk increases if users follow the instruction under an administrator account or install into a shared system Python environment.

Attack Path

  1. A package-index account, configured mirror, dependency release, or distribution artifact is compromised.
  2. A malicious or modified version becomes the version selected by the unpinned pip3 install requests command.
  3. A user follows the documented setup command.
  4. pip downloads and installs the compromised artifact or one of its compromised transitive dependencies.
  5. Malicious installation or runtime code executes with the privileges of the invoking user.

Impact Assessment

A compromised dependency can execute arbitrary Python code with the privileges of the user who installs or runs the Skill. Depending on those privileges, the attacker could access local files and credentials, alter Python packages, intercept uploaded product media and API keys, or establish further persistence.

The finding does not demonstrate that the current requests package is malicious. The risk ...[truncated 90 chars]

Remediation
View remediation

Remediation Suggestions

  1. Add a reviewed dependency file containing exact versions.

  2. Generate and require cryptographic hashes for all direct and transitive dependencies, for example with pip-compile --generate-hashes.

  3. Install with hash enforcement:

    bash
    python3 -m pip install --require-hashes -r requirements.txt
    
  4. Use a dedicated virtual environment rather than the system Python environment.

  5. Configure an explicitly trusted package index and avoid uncontrolled mirrors.

  6. Regularly scan and deliberately update the lock file after security review.

  7. Avoid running dependency installation as root or with administrator privileges.

Vulnerability Patterns
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • 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 (8)

Description-Behavior Mismatch

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

The skill is marketed as a Lazada image-generation/editing tool, but the file also contains broad generic AI-hub capabilities including account info retrieval, model discovery, chat, video generation, and arbitrary media upload. This scope mismatch is dangerous because users and orchestrators may grant trust, permissions, or deployment approval based on the narrower description while the code exposes materially broader data access and action surface.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
94% confidence
Finding

The skill invokes shell commands, installs packages, reads image inputs, writes outputs, and makes network-backed model calls, but it does not declare any explicit tool scope such as permissions or allowed-tools. That creates an avoidable trust gap: an agent may grant broader capabilities than intended, increasing the risk of filesystem access, package installation, environment exposure, or network use beyond what is necessary for image generation tasks.

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 user-facing CLI guidance are written entirely in Chinese, and the script’s prompts, status messages, and help text consistently assume Chinese-language interaction. This imposes a specific language/locale on users without offering an opt-in, fallback, or documented region-specific justification, which matches the language policy violation criteria.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

Retrieving user account information and wallet balance is not necessary for generating or editing product images. In the context of a narrowly described ecommerce image skill, this creates unjustified access to sensitive account/billing data and can violate user expectations about what the tool is allowed to inspect.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The presence of text chat functionality is inconsistent with a purpose-limited image generation/editing skill. Even if not exposed through the final skill entrypoint, retaining generic chat capability in the same file creates a latent misuse path, broadens prompt/data exfiltration surface, and undermines least-privilege expectations.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The code includes full video-generation support even though the stated skill purpose is image generation/editing for Lazada catalog assets. Unnecessary capability expansion increases attack surface, allows policy bypass through off-purpose media generation, and can lead to unexpected cost or data handling beyond what users intended to authorize.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
95% confidence
Finding

This markdown file contains substantive user-facing natural-language content entirely in Chinese, but does not indicate that the skill is region-specific or provide any user opt-in for language/locale. Under the policy, forcing a specific language without user choice can be a natural-language policy violation.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
89% confidence
Finding

The placeholder value for api_key includes Chinese text (请替换为你的APIKey), which embeds a specific language choice in a user-facing config example. This can violate language/locale policy when no user opt-in or documented locale-specific scope is provided.

Content

No source excerpt is available for this finding.