Back to skill

Security audit

ComfyUI图像生成

Security checks for vulnerabilities and agentic risk

Overview

This skill is a coherent ComfyUI image generator, but it sends prompts and full workflows to a configurable plain-HTTP server and writes downloaded content to caller-chosen paths without enough safety boundaries.

Install only if you trust the configured ComfyUI server and workflow files. Prefer a loopback or authenticated HTTPS endpoint, use reviewed workflow templates, avoid sensitive prompts, and restrict output paths to a dedicated directory where overwrites are acceptable.

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

T09 · Insecure Skill Coding Practices

Error
Location
comfyui_generator.py:57
Finding

Untrusted Workflows Are Submitted Without a Node Allowlist

Content
View full analysis

Vulnerability Details

File Location: comfyui_generator.py:57-75, comfyui_generator.py:303-307; equivalent behavior also appears in __init__.py:43-58 and __init__.py:130-143
Vulnerability Type: Insufficient validation of executable workflow content
Risk Level: High

Vulnerable Code

python
# Validate required nodes
has_clip_text_encode = False
has_save_image = False

for node_id, node in workflow.items():
    class_type = node.get('class_type')
    if class_type == 'CLIPTextEncode':
        has_clip_text_encode = True
    elif class_type == 'SaveImage':
        has_save_image = True

if not has_clip_text_encode:
    raise ValueError("Workflow is missing the required CLIPTextEncode node")

if not has_save_image:
    raise ValueError("Workflow is missing the required SaveImage node")

return workflow

The validated workflow is subsequently submitted in its entirety:

python
url = f"{COMFYUI_SERVER}/prompt"
data = json.dumps({"prompt": workflow}).encode('utf-8')
req = urllib.request.Request(
    url,
    data=data,
    headers={'Content-Type': 'application/json'}
)
response = urllib.request.urlopen(req)
prompt_id = json.loads(response.read())['prompt_id']

Technical Analysis

Workflow validation only confirms the presence of one CLIPTextEncode node and one SaveImage node. It does not reject unknown node classes, custom nodes, dangerous input values, or additional nodes unrelated to image generation.

A ComfyUI workflow is effectively executable configuration. ComfyUI custom nodes can perform filesystem operations, make network requests, load arbitrary resources, or execute other behavior implemented by installed extensions. Consequently, a caller-controlled workflow can include the two required nodes to pass validation while retaining additional unsafe nodes. The complete workflow is then sent to the ComfyUI service for execution.

Exploitability ...[truncated 1401 chars]

Remediation
View remediation

Remediation Suggestions

  1. Treat workflow files as executable, trusted configuration rather than ordinary data.
  2. Restrict workflow_path to a canonicalized, administrator-controlled directory:
    • Resolve the path with Path.resolve().
    • Confirm that it remains beneath the approved workflow root.
    • Reject symlinks and user-writable workflow files where practical.
  3. Define a strict allowlist of approved class_type values and reject every unknown or custom node.
  4. Validate each permitted node's input names, types, ranges, and path values against a schema.
  5. Prefer immutable, pre-reviewed workflow templates. Allow callers to supply only narrowly scoped values such as prompt text and safe generation parameters.
  6. Run ComfyUI under a dedicated, minimally privileged account with restricted filesystem and outbound network access.
  7. Apply resource limits to workflow execution, including queue, memory, runtime, and GPU limits.

T09 · Insecure Skill Coding Practices

Warning
Location
comfyui_generator.py:21
Finding

ComfyUI Workflows and Generated Content Are Transmitted over Unauthenticated Plaintext HTTP

Content
View full analysis

Vulnerability Details

File Location: comfyui_generator.py:21, comfyui_generator.py:303-307; equivalent configuration and request behavior appears in __init__.py:15 and __init__.py:130-143
Vulnerability Type: Cleartext transmission and missing server authentication
Risk Level: Medium

Vulnerable Code

python
COMFYUI_SERVER = os.getenv(
    'COMFYUI_SERVER',
    'http://192.168.18.15:8188'
)
python
url = f"{COMFYUI_SERVER}/prompt"
data = json.dumps({"prompt": workflow}).encode('utf-8')
req = urllib.request.Request(
    url,
    data=data,
    headers={'Content-Type': 'application/json'}
)
response = urllib.request.urlopen(req)
prompt_id = json.loads(response.read())['prompt_id']

Technical Analysis

The default endpoint uses plaintext HTTP. The implementation does not provide application-level authentication, request signing, or endpoint identity verification beyond whatever transport the configured URL supplies.

The submitted body contains the complete workflow and prompt. Polling identifiers and generated image responses also travel through the same configured server. When HTTP is used across a network, an attacker in a suitable network position can observe or alter this traffic. The attacker may capture sensitive prompt data, modify workflow submissions, replace task-history responses, or substitute generated content.

Although an operator can configure an HTTPS URL through COMFYUI_SERVER, the implementation neither requires HTTPS for non-loopback addresses nor documents an authenticated transport mechanism.

Attack Path

  1. The Skill connects to the default HTTP endpoint or another remote HTTP endpoint.
  2. An attacker obtains a network position capable of observing or modifying traffic, such as a compromised gateway, local network segment, or routing path.
  3. The attacker captures the /prompt request and reads the prompt and complete workflow.

...[truncated 654 chars]

Remediation
View remediation

Remediation Suggestions

  1. Require HTTPS for every non-loopback ComfyUI endpoint.
  2. Use certificates issued by a trusted internal or public authority and retain Python's certificate verification.
  3. For private deployments, place ComfyUI behind a mutually authenticated TLS proxy or a properly authenticated VPN/SSH tunnel.
  4. Require an authorization token or client certificate and avoid placing credentials in URL query parameters.
  5. Reject endpoint URLs containing embedded credentials or unsupported schemes.
  6. Consider allowlisting expected hosts and ports to reduce endpoint substitution risks.
  7. Document that plain HTTP is acceptable only when communication is strictly confined to a trusted loopback interface or comparably protected transport.

T09 · Insecure Skill Coding Practices

Warning
Location
comfyui_generator.py:216
Finding

Image Downloads Are Unbounded and Their Content Is Not Validated

Content
View full analysis

Vulnerability Details

File Location: comfyui_generator.py:216-242
Vulnerability Type: Unbounded network response and unrestricted content storage
Risk Level: Medium

Vulnerable Code

python
def download_image(filename: str, output_path: str) -> Dict[str, Any]:
    # Ensure directory exists
    output_dir = os.path.dirname(output_path)
    if output_dir:
        os.makedirs(output_dir, exist_ok=True)

    # Construct download URL
    url = f"{COMFYUI_SERVER}/view?filename={quote(filename)}&type=output"

    req = urllib.request.Request(
        url,
        headers={'User-Agent': 'nanobot/1.0'}
    )

    with urllib.request.urlopen(req) as response:
        content = response.read()

    with open(output_path, 'wb') as f:
        f.write(content)

    return {
        'file_path': output_path,
        'file_size_bytes': len(content),
        'file_size_mb': len(content) / 1024 / 1024
    }

Technical Analysis

urlopen() is called without a timeout, and response.read() reads the entire response into memory without a maximum size. The returned content is then written to disk without checking the HTTP status, declared content length, MIME type, file signature, or successful image decoding.

A malicious or compromised endpoint can therefore return an indefinitely slow stream, an extremely large response, or arbitrary non-image content. Reading the entire body before writing makes memory exhaustion particularly likely. Disk exhaustion remains possible once the body is accepted.

The caller intentionally controls output_path, so the destination selection is part of the API rather than an independent path-traversal flaw. However, the absence of content validation means a compromised server can control the bytes stored at that selected path.

Attack Path

  1. An attacker compromises, impersonates, or controls the configured ComfyUI endpoint.
  2. The Skill requests a ...[truncated 820 chars]
Remediation
View remediation

Remediation Suggestions

  1. Supply explicit connection and read timeouts to every network operation.
  2. Stream the response in fixed-size chunks rather than calling an unrestricted read().
  3. Enforce a conservative maximum image size and abort as soon as the limit is exceeded.
  4. Validate the HTTP status, Content-Type, and Content-Length when available, while still enforcing a streamed byte limit.
  5. Decode and verify the image with a maintained image library before accepting it as generated output.
  6. Write to a securely created temporary file in the destination directory, validate it, flush it, and atomically rename it to the final path.
  7. Delete partial temporary files on timeout, validation failure, or size-limit violation.
  8. Apply filesystem quotas or process-level resource limits as defense in depth.

T09 · Insecure Skill Coding Practices

Warning
Location
__init__.py:187
Finding

Prefix-Based Output Selection Can Copy Stale, Cross-Job, or Symlinked Files

Content
View full analysis

Vulnerability Details

File Location: __init__.py:187-209, __init__.py:285-309
Vulnerability Type: Insecure shared-file selection and symlink handling
Risk Level: Medium

Vulnerable Code

python
def find_generated_file(filename_prefix):
    if not os.path.exists(OUTPUT_DIR):
        return False, None, 0

    files = [
        f for f in os.listdir(OUTPUT_DIR)
        if f.startswith(filename_prefix)
    ]

    if not files:
        return False, None, 0

    # Take the first file
    file_path = os.path.join(OUTPUT_DIR, files[0])
    file_size_mb = os.path.getsize(file_path) / (1024 * 1024)

    return True, file_path, file_size_mb

The selected path is later copied without verifying its origin or file type:

python
if filename_prefix:
    success, file_path, file_size_mb = find_generated_file(
        filename_prefix
    )
else:
    prefix = None
    for node in workflow.values():
        if node.get('class_type') == 'SaveImage':
            prefix = node.get(
                'inputs', {}
            ).get('filename_prefix', 'output')
            break

    success, file_path, file_size_mb = find_generated_file(prefix)

if not success:
    return {'success': False, 'error': 'Generated file not found'}

if output_path:
    try:
        output_dir = os.path.dirname(output_path)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)

        shutil.copy2(file_path, output_path)
        file_path = output_path
    except Exception as e:
        return {
            'success': False,
            'error': f"Failed to copy file: {e}"
        }

Technical Analysis

The code does not associate the selected file with the completed prompt_id. Instead, it enumerates a shared output directory and accepts every filename beginning with a caller-influenced prefix. It then selects files[0], even ...[truncated 1773 chars]

Remediation
View remediation

Remediation Suggestions

  1. Obtain the exact output filename and subdirectory from the history response for the current prompt_id.
  2. Do not discover outputs by scanning for a prefix.
  3. Generate a cryptographically unique, per-job prefix or isolated output directory when task metadata cannot provide an exact path.
  4. Resolve the selected path and verify that it remains beneath the canonical OUTPUT_DIR.
  5. Use os.lstat() and reject symbolic links and non-regular files.
  6. Open the source with no-follow semantics where supported and copy from the verified file descriptor to reduce race conditions.
  7. Validate ownership and permissions where the output directory is shared.
  8. Ensure each request can only retrieve output associated with its own prompt_id.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Taint TrackingDirect Taint Flow, Variable-Mediated Taint Flow, Credential Exfiltration Chain
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (17)

Tainted flow: 'COMFYUI_SERVER' from os.environ.get (line 15, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
93% confidence
Finding

The server URL is taken directly from an environment variable and used for outbound requests without validation, allowlisting, or transport-security enforcement. In an agent/skill context, this can enable SSRF-like behavior, redirection of prompts and metadata to attacker-controlled hosts, and accidental transmission to an internal or non-TLS endpoint.

Content

Scanner excerpt · __init__.py (reported line 23)May include surrounding context.

python
def test_connection():
    """测试 ComfyUI 连接"""
    try:
        response = urllib.request.urlopen(f"{COMFYUI_SERVER}/system_stats", timeout=5)
        data = json.loads(response.read().decode())
        return True, data
    except Exception as e:

Tainted flow: 'req' from os.environ.get (line 174, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
92% confidence
Finding

The polling request to /history/{prompt_id} also uses the environment-controlled COMFYUI_SERVER without validation. This extends the same risk surface across repeated requests, allowing an attacker who controls configuration to receive workflow status traffic or direct the skill toward unintended internal/external services.

Content

Scanner excerpt · __init__.py (reported line 175)May include surrounding context.

python
try:
            req = urllib.request.Request(f"{COMFYUI_SERVER}/history/{prompt_id}")
            response = urllib.request.urlopen(req)
            history = json.loads(response.read().decode())

            if prompt_id in history:

Tainted flow: 'COMFYUI_SERVER' from os.getenv (line 21, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
93% confidence
Finding

The code trusts COMFYUI_SERVER from an environment variable and uses it directly for outbound HTTP requests without any validation, allowlisting, or scheme restrictions. If an attacker can influence the environment, this becomes an SSRF-style primitive that can redirect requests to internal services or attacker-controlled hosts, especially since the API also sends workflow data and consumes returned content.

Content

Scanner excerpt · comfyui_generator.py (reported line 30)May include surrounding context.

python
def test_connection() -> Dict[str, Any]:
    """测试 ComfyUI 服务器连接"""
    try:
        response = urllib.request.urlopen(f"{COMFYUI_SERVER}/system_stats", timeout=5)
        data = json.loads(response.read().decode())
        return {
            'success': True,

Tainted flow: 'req' from os.getenv (line 179, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
92% confidence
Finding

Polling task history via a URL derived from COMFYUI_SERVER repeatedly issues requests to a potentially attacker-chosen host. This creates a sustained SSRF channel and increases exposure by making multiple requests over time, which can aid internal network probing or data harvesting if the environment variable is compromised.

Content

Scanner excerpt · comfyui_generator.py (reported line 180)May include surrounding context.

python
while time.time() - start < timeout:
        try:
            req = urllib.request.Request(url)
            with urllib.request.urlopen(req, timeout=5) as response:
                data = json.loads(response.read().decode())
        except Exception as e:
            time.sleep(3)

Tainted flow: 'req' from os.getenv (line 179, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
92% confidence
Finding

After success, the code performs an additional fetch to the same unvalidated server, extending trust in a tainted endpoint and creating another opportunity to consume attacker-controlled JSON. In context, this compounds the SSRF/exfiltration risk rather than being an isolated issue, because the skill is explicitly designed to exchange data with a remote service and then act on the results.

Content

Scanner excerpt · comfyui_generator.py (reported line 195)May include surrounding context.

python
if status == 'success':
            time.sleep(1)  # 等待文件完全保存
            # 再次获取最新信息
            with urllib.request.urlopen(req, timeout=5) as response2:
                data2 = json.loads(response2.read().decode())
            return data2[prompt_id]
        elif status == 'error':

Tainted flow: 'req' from os.getenv (line 179, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
95% confidence
Finding

The download endpoint is built from the tainted COMFYUI_SERVER value and then fetched, causing the program to retrieve arbitrary bytes from whatever host the environment variable points to. Because the response is then written to disk at a caller-controlled path, this expands the risk from SSRF to arbitrary file write of untrusted remote content within the permissions of the running process.

Content

Scanner excerpt · comfyui_generator.py (reported line 230)May include surrounding context.

python
req = urllib.request.Request(url, headers={'User-Agent': 'nanobot/1.0'})

    with urllib.request.urlopen(req) as response:
        content = response.read()

    with open(output_path, 'wb') as f:

Tainted flow: 'req' from os.getenv (line 179, credential/environment) → urllib.request.urlopen (network output)

Critical
Category
Data Flow
Confidence
94% confidence
Finding

The code posts the full workflow JSON to a server selected via COMFYUI_SERVER with no trust verification. If the environment is manipulated, sensitive workflow contents, prompts, and operational metadata may be exfiltrated to an attacker-controlled endpoint, and the service behavior can be influenced through malicious responses.

Content

Scanner excerpt · comfyui_generator.py (reported line 306)May include surrounding context.

python
url = f"{COMFYUI_SERVER}/prompt"
        data = json.dumps({"prompt": workflow}).encode('utf-8')
        req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
        response = urllib.request.urlopen(req)
        prompt_id = json.loads(response.read())['prompt_id']

        # 5. 等待完成

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The natural-language instructions and headings throughout the skill are presented exclusively in Chinese. Under the stated policy, forcing a specific language without user opt-in or clear justification is a language/locale policy violation.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The documentation states that the skill connects to a remote ComfyUI server at a fixed private-network address and includes retry/download behavior, but it does not warn users that prompts, workflows, and generated data may traverse the network or be processed by another host. In environments handling sensitive prompts or images, this omission can cause unintentional data exposure and unexpected network access.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

User-supplied prompts are serialized and sent over plain HTTP to a remote ComfyUI server, with no encryption guarantee and no explicit disclosure to the caller. Prompts can contain sensitive or proprietary data, so network observers or an untrusted server could capture them.

Content

No source excerpt is available for this finding.

Tainted flow: 'req' from urllib.request.urlopen (line 137, network input) → urllib.request.urlopen (network output)

Medium
Category
Data Flow
Confidence
65% confidence
Finding

Data from a source is assigned to a variable that is later passed to a sink, creating a variable-mediated taint flow.

Content

Scanner excerpt · __init__.py (reported line 142)May include surrounding context.

python
data=data,
            headers={'Content-Type': 'application/json'}
        )
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())

        prompt_id = result.get('prompt_id')

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The API performs network operations and writes remote content to a caller-specified filesystem path without safeguards, confirmation, or path restrictions. In a skill/agent context this is more dangerous because an upstream caller may unknowingly trigger outbound traffic and disk writes, enabling misuse for unsafe file placement, overwriting application data, or storing hostile content.

Content

No source excerpt is available for this finding.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
94% confidence
Finding

The skill explicitly documents an output_path parameter and demonstrates writing generated images to arbitrary filesystem locations, but it does not warn users that invoking the skill will create or overwrite files at that path. In an agent setting, this can lead to unintended writes to sensitive or important locations, especially if paths are user-influenced or generated automatically.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
79% confidence
Finding

The module docstring presents the skill description in Chinese only, with no indication that users can choose another language or locale. Per 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.

Missing User Warnings

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

When output_path is provided, the function creates directories and copies the generated file to that path. The operation writes to the filesystem, but there is no user-facing disclosure, confirmation, or warning in the code about creating directories and writing files outside the default output location.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
88% confidence
Finding

The module docstring and all user-facing CLI messages are in Chinese, which imposes a specific language on users without any opt-in or alternative. Under the language/locale policy, fixed-language behavior should be optional or explicitly justified as region-specific.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Low
Category
Not specified by scanner
Confidence
93% confidence
Finding

The docstring states the function returns '(workflow, info): 工作流字典和节点信息', implying a tuple with workflow and node metadata. However, the implementation validates nodes and returns only 'workflow' at L075, so the documentation actively misstates the function's behavior.

Content

No source excerpt is available for this finding.