Back to skill

Security audit

04 自动迭代

Security checks for vulnerabilities and agentic risk

Overview

This skill matches its auto-iteration purpose, but it can read arbitrary local files and persist tool results in a plaintext home-directory database, so users should review it carefully before installing.

Install only if you are comfortable with a task runner that can read user-specified local files, write within the current directory, and keep plaintext task/result history in ~/.ai_iteration_log.db. Use it in a dedicated workspace, avoid pointing it at secrets or private files, and delete or protect the SQLite log if sensitive content may have been processed.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • 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)

T05 · Unauthorized Access and Privilege Escalation

Error
Location
iteration_agent.py:246
Finding

Unrestricted Local File Read Through User-Controlled Paths

Content
View full analysis

Vulnerability Details

File Location: iteration_agent.py:246-258
Vulnerability Type: Arbitrary local file read
Risk Level: High

Vulnerable Code

python
def _tool_read(self, file_path: str) -> Dict:
    """读取文件工具"""
    path = Path(file_path)

    if not path.exists():
        return {'error': '文件不存在'}

    if path.stat().st_size > 1024 * 1024:  # 1MB限制
        return {'error': '文件过大'}

    try:
        content = path.read_text(encoding='utf-8')
        return {'content': content[:1000]}  # 限制返回长度
    except Exception as e:
        return {'error': str(e)}

Technical Analysis

The file_path parameter is controlled by the task caller and is converted directly into a Path. The implementation verifies only that the target exists and is no larger than 1 MB. It does not require the resolved path to remain within an authorized workspace, reject absolute paths, restrict symbolic links, or ensure the target is a regular file.

Consequently, the read tool can access any UTF-8-compatible file readable by the operating-system account running the agent. The write implementation has a current-directory boundary check, but no equivalent control is applied to reads.

The one-thousand-character response limit reduces the amount disclosed by a single invocation but does not enforce access control. An attacker can target multiple files, and the implementation reads the entire accepted file into process memory before truncating the returned value.

Attack Path

  1. An attacker or untrusted task author creates a task step using the allowed read tool.
  2. The attacker supplies an absolute path or a relative traversal path pointing outside the intended workspace.
  3. execute_tool() accepts the tool because read is on the allowlist.
  4. _tool_read() opens the target without validating its location against an authorized root.
  5. Up to the first 1,000 characters are returned to the calle ...[truncated 900 chars]
Remediation
View remediation

Remediation Suggestions

  1. Define an explicit workspace root instead of relying on unrestricted caller-provided paths.
  2. Resolve both the workspace and requested path before access, then require the requested path to be a descendant of the workspace.
  3. Reject absolute paths unless they have been explicitly authorized.
  4. Reject symbolic links or verify the final resolved target after following links.
  5. Require the target to be a regular file and reject device files, sockets, directories, and other special files.
  6. Consider an extension or file allowlist where tasks require only specific document types.
  7. Require explicit user confirmation before reading files outside the configured workspace.
  8. Apply the size limit before reading and use bounded or streaming reads so the full file is not loaded into memory.
  9. Add tests for absolute paths, .. traversal, symlink escapes, and workspace-prefix confusion.

A hardened design should use a pattern equivalent to:

python
workspace = configured_workspace.resolve()
requested = (workspace / file_path).resolve()

if not requested.is_relative_to(workspace):
    return {'error': 'File is outside the authorized workspace'}

if not requested.is_file() or requested.is_symlink():
    return {'error': 'Target must be an authorized regular file'}

T09 · Insecure Skill Coding Practices

Warning
Location
iteration_agent.py:126
Finding

Sensitive Tool Results Persisted in a Plaintext SQLite Log

Content
View full analysis

Vulnerability Details

File Location: iteration_agent.py:70, 126-134, 381-384
Vulnerability Type: Plaintext persistence of potentially sensitive data
Risk Level: Medium

Vulnerable Code

The log database is stored persistently in the user's home directory:

python
if db_path is None:
    db_path = Path.home() / ".ai_iteration_log.db"

self.db_path = Path(db_path)
self._init_db()

Complete serialized tool results are inserted into the iteration history:

python
def log_iteration(self, task_id: int, iteration_num: int,
                  action: str, result: str, quality_score: float = 0.0):
    """记录迭代"""
    conn = sqlite3.connect(self.db_path)
    cursor = conn.cursor()

    cursor.execute('''
        INSERT INTO iterations (task_id, iteration_num, action, result, quality_score)
        VALUES (?, ?, ?, ?, ?)
    ''', (task_id, iteration_num, action, result, quality_score))

The task runner serializes and submits each complete result to that logger:

python
self.logger.log_iteration(
    task_id, iteration, tool,
    json.dumps(result, ensure_ascii=False), quality
)

Technical Analysis

Every successful tool result is serialized and stored in a persistent SQLite database. Results from the read tool contain local file contents, while other tools may process task data supplied by users. No redaction, data classification, retention limit, encryption, or logging opt-out is applied before persistence.

The code also does not explicitly create or validate the database with owner-only permissions. Its effective permissions therefore depend on the runtime environment and process umask. Even where filesystem permissions are restrictive, plaintext persistence unnecessarily increases the lifetime and number of copies of sensitive information.

SQL injection is not present in the displayed database operations because parameterized statements are used. The issue ...[truncated 1308 chars]

Remediation
View remediation

Remediation Suggestions

  1. Do not store complete tool results by default. Log metadata such as tool name, status, duration, and a non-sensitive error code instead.
  2. Apply structured redaction before serialization, including removal of file contents, credentials, tokens, private keys, and authentication headers.
  3. Introduce an explicit opt-in setting for content logging and clearly disclose its behavior.
  4. Set a short, configurable retention period and periodically delete expired task and iteration records.
  5. Create the database with owner-only permissions and verify existing permissions before use.
  6. Consider encryption at rest where sensitive result retention is genuinely required, with keys stored separately from the database.
  7. Provide a secure history-deletion mechanism and account for SQLite remnants, backups, and copied database files.
  8. Store only a digest, byte count, or redacted preview when audit correlation is necessary.
  9. Add automated tests confirming that file contents and common secret formats never enter the logging database.
Vulnerability Patterns
  • 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
  • Taint TrackingDirect Taint Flow, Variable-Mediated Taint Flow, Credential Exfiltration Chain
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (14)

eval() call detected

High
Category
Dangerous Code Execution
Confidence
93% confidence
Finding

The calculate tool executes user-controlled input with eval(). Although the regex restricts characters and builtins is removed, using eval for untrusted input is still risky because it can enable denial-of-service via computationally expensive expressions and creates an unnecessary code-execution primitive in a tool advertised as safe. In this skill context, users directly supply task parameters, so the dangerous surface is exposed by design.

Content

Scanner excerpt · iteration_agent.py (reported line 283)May include surrounding context.

python
if not re.match(r'^[\d\s+\-*/().]+$', expression):
                return {'error': '表达式包含非法字符'}

            result = eval(expression, {'__builtins__': {}}, {})
            return {'result': result}
        except Exception as e:
            return {'error': str(e)}

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
91% confidence
Finding

The skill advertises file read/write behavior and references a Python engine, but it does not declare an explicit tool scope such as permissions or allowed-tools. This creates a mismatch between documented capabilities and enforceable restrictions, increasing the risk that an agent may grant broader filesystem or shell access than intended during execution or extension.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The example trigger phrases are broad, natural-language requests that overlap with ordinary user intent, making accidental activation more likely. Because this skill performs automatic iteration, file operations, and user-extensible tooling, unintended invocation could cause unreviewed repeated actions or writes that the user did not explicitly authorize.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The code repeatedly describes itself as safe, but its actual capabilities include arbitrary local file reads and persistent logging, while only writes are partially constrained. This mismatch is security-relevant because it can mislead users and integrators into granting trust or permissions they would not otherwise allow, increasing the chance of sensitive data exposure.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The skill is presented as a safe iteration system, but it silently creates a hidden SQLite database in the user's home directory and stores task metadata and results there. This creates an undisclosed persistence channel for potentially sensitive prompts, outputs, and operational history, increasing privacy and data-retention risk beyond user expectations.

Content

No source excerpt is available for this finding.

Ssd 3

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

Task and iteration logs store user-provided task names, tool actions, results, and potentially file contents in plain text in SQLite. Because the agent can read local files and then log outputs, this persistence can unintentionally retain sensitive data and increase exposure through local compromise, backups, or shared-user environments.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The read tool allows arbitrary local file reads with no confinement to a safe workspace, enabling access to any file the current user can read. In a system marketed as safe and designed to process user-defined task steps, this can expose secrets such as SSH keys, config files, tokens, or personal documents.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The write tool permits file creation and overwrite in the current working directory without user confirmation or file-type restrictions. Even with the cwd boundary, this can alter project files, scripts, configs, or documentation and may be leveraged to tamper with local artifacts or stage malicious content in trusted locations.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The interface exposes file-writing behavior without a clear warning that running tasks may create or overwrite files. In an interactive agent setting, lack of informed consent is dangerous because users may supply or approve task steps without realizing local files will be modified.

Content

No source excerpt is available for this finding.

Tainted flow: 'content' from pathlib.Path.read_text (line 256, file read) → pathlib.Path.write_text (file write)

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 · iteration_agent.py (reported line 271)May include surrounding context.

python
return {'error': '只能写入当前目录'}

        try:
            path.write_text(content, encoding='utf-8')
            return {'success': True, 'file': str(path)}
        except Exception as e:
            return {'error': str(e)}

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
86% confidence
Finding

文档标题、描述、示例和说明均固定为中文,未说明该技能是否仅面向中文用户,也未提供语言切换、用户选择或明确的地域/合规理由。按组织语言/locale 政策,若技能默认强制单一语言而无用户选择,可能构成自然语言策略违规。

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
97% confidence
Finding

All user-facing messages in this installer are in Chinese, including errors, warnings, and usage instructions. This imposes a language choice on users without offering an alternative or documenting that the skill is intended only for a Chinese-speaking audience.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
95% confidence
Finding

User-facing natural language in the module description and CLI is consistently Chinese, which effectively forces a specific language for interaction. The file does not offer an opt-in language choice or explain that the skill is intentionally limited to a Chinese-speaking context.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
86% confidence
Finding

The natural-language content in the file is written entirely in Chinese, including user-facing descriptive comments, with no indication that language choice is optional or that the skill is region-specific. Under the stated policy, forcing a specific language without opt-in can be a locale-policy violation.

Content

No source excerpt is available for this finding.