Back to skill

Security audit

智能接口工具箱

Security checks for vulnerabilities and agentic risk

Overview

MockLab is a coherent API mocking tool, but it exposes broad unauthenticated proxy, admin, file-write, and state-access capabilities that should be reviewed before installation.

Install only if you are comfortable running a local API tool that can write project/state files, expose an unauthenticated server on your network, and forward request bodies plus custom headers to real URLs. Use synthetic tokens and sanitized API documents, keep it behind localhost or a trusted network boundary, and avoid production credentials until auth, host restrictions, redaction, and safer persistence controls are added.

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

T09 · Insecure Skill Coding Practices

Error
Location
mock_server.py:656
Finding

Unauthenticated SSRF Through the Real-Request Proxy

Content
View full analysis

Vulnerability Details

File Location: mock_server.py:656-697
Vulnerability Type: Unrestricted server-side request forgery and sensitive-header forwarding
Risk Level: Critical

Vulnerable Code

python
@app.post("/mock/proxy")
async def proxy_request(request: Request):
    """
    代理转发:把请求转发到真实目标地址,原样返回响应(不走 Mock 逻辑)。
    请求体: {
        "target_url": "http://localhost:8080/api/user",
        "method": "POST",
        "headers": {"Authorization": "Bearer xxx"},
        "body": {...}
    }
    """
    import httpx
    data = await request.json()
    target_url = data.get("target_url")
    method = data.get("method", "POST").upper()
    req_headers = data.get("headers", {})
    req_body = data.get("body")

    if not target_url:
        return JSONResponse(
            {"code": 1, "error": "target_url 不能为空"},
            status_code=400
        )

    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            if method == "GET":
                resp = await client.get(target_url, headers=req_headers)
            elif method == "POST":
                resp = await client.post(
                    target_url,
                    headers=req_headers,
                    json=req_body
                )
            elif method == "PUT":
                resp = await client.put(
                    target_url,
                    headers=req_headers,
                    json=req_body
                )
            elif method == "DELETE":
                resp = await client.delete(
                    target_url,
                    headers=req_headers
                )
            else:
                return JSONResponse(
                    {
                        "code": 1,
                        "error": "不支持的请求方法: " + method
                    },
                    status_code=400
                )

...[truncated 1930 chars]

Remediation
View remediation

Remediation Suggestions

  • Require authentication and explicit authorization for /mock/proxy.
  • Disable the proxy by default and require an explicit startup flag to enable it.
  • Restrict destination schemes to https, or to http and https only when necessary.
  • Maintain an explicit allowlist of permitted destination hosts and ports.
  • Resolve hostnames before connection and reject loopback, private, link-local, multicast, reserved, and unspecified addresses.
  • Revalidate every redirect destination and disable redirects unless required.
  • Strip Authorization, Cookie, Proxy-Authorization, and other sensitive headers by default.
  • Apply request-size, timeout, concurrency, and rate limits.
  • Record proxy use in a security audit log without recording secret values.
  • Return a generic failure message instead of exposing detailed internal connection errors.

T05 · Unauthorized Access and Privilege Escalation

Error
Location
mock_server.py:484
Finding

Unauthenticated Administrative APIs Exposed on All Network Interfaces

Content
View full analysis

Vulnerability Details

File Location: mock_server.py:484-484, mock_server.py:702-911, and mock_server.py:937-937
Vulnerability Type: Missing authentication, overbroad CORS, and network-wide administrative exposure
Risk Level: Critical

Vulnerable Code

python
app = FastAPI(
    title="MockLab",
    description="AI-driven Mock API Service v1.1"
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)
python
@app.post("/mock/load")
async def load_schema(request: Request):
    data = await request.json()
    name = data.get("name", "default")
    schema = data.get("schema", {})
    _projects[name] = schema
    schema_file = SCHEMA_STORE / (name + ".json")
    schema_file.write_text(
        json.dumps(schema, ensure_ascii=False, indent=2),
        encoding="utf-8"
    )
    return {
        "code": 0,
        "message": "已加载 %s,%d 个接口" %
                   (name, len(schema.get("interfaces", [])))
    }
python
@app.delete("/mock/state")
async def clear_state():
    global _sequences, _refs
    with _lock:
        _sequences = {}
        _refs = {}
    _save_state()
    return {"code": 0, "message": "状态已清空"}

@app.get("/mock/state")
async def get_state():
    return {
        "code": 0,
        "data": {
            "sequences": _sequences,
            "refs": _refs
        }
    }
python
uvicorn.run(
    "mock_server:app",
    host="0.0.0.0",
    port=port,
    log_level="warning"
)

Technical Analysis

The service binds to 0.0.0.0, making it reachable through every available network interface. No authentication or authorization checks protect project loading, schema editing, custom-interface CRUD operations, state inspection, state deletion, or proxy forwarding.

CORS is configured with wi ...[truncated 1757 chars]

Remediation
View remediation

Remediation Suggestions

  • Bind to 127.0.0.1 by default.
  • Require an explicit --host option and clear warning before enabling network-wide access.
  • Add authenticated sessions or API tokens for all administrative endpoints.
  • Enforce role-based authorization for schema changes, state access, and proxy use.
  • Restrict CORS to explicit trusted origins.
  • Do not combine wildcard origins with credential support.
  • Apply CSRF protection if browser session authentication is introduced.
  • Separate public mock routes from administrative routes.
  • Place administrative APIs on a separate local listener where feasible.
  • Add rate limiting, request-size limits, and audit logging.
  • Document that production credentials and production network exposure are unsupported.

T09 · Insecure Skill Coding Practices

Error
Location
mock_server.py:702
Finding

Arbitrary File Write Through Project Name Path Traversal

Content
View full analysis

Vulnerability Details

File Location: mock_server.py:702-708
Vulnerability Type: Path traversal and arbitrary JSON file write
Risk Level: High

Vulnerable Code

python
@app.post("/mock/load")
async def load_schema(request: Request):
    data = await request.json()
    name = data.get("name", "default")
    schema = data.get("schema", {})
    _projects[name] = schema
    schema_file = SCHEMA_STORE / (name + ".json")
    schema_file.write_text(
        json.dumps(schema, ensure_ascii=False, indent=2),
        encoding="utf-8"
    )

Technical Analysis

The name field is controlled by the request and is concatenated with .json before being joined to SCHEMA_STORE. The code does not verify that name is a single filename or that the resolved destination remains inside the schema directory.

pathlib.Path joining does not neutralize .. path components. A value such as ../custom_store produces a destination equivalent to:

text
schema_store/../custom_store.json

This resolves outside the intended directory. Since the endpoint has no authentication, any network client that can access the service may attempt the traversal.

The file suffix is always .json, which limits possible targets, but an attacker can still create or overwrite JSON files in parent or nested writable directories.

Attack Path

  1. The attacker sends a POST request to /mock/load.
  2. The request uses a project name containing traversal components, for example ../chosen-file.
  3. MockLab constructs SCHEMA_STORE / "../chosen-file.json".
  4. The filesystem resolves the traversal outside schema_store.
  5. Attacker-controlled schema content is written to the resulting path.
  6. Existing application JSON files may be corrupted or replaced, or new files may be planted in writable locations.

Impact Assessment

Exploitation allows writes with the operating-system privileges of the ...[truncated 570 chars]

Remediation
View remediation

Remediation Suggestions

  • Restrict project names to a conservative pattern such as ^[A-Za-z0-9_-]{1,64}$.
  • Reject path separators, .., absolute paths, control characters, and null bytes.
  • Resolve the final path and verify that it is a descendant of the resolved SCHEMA_STORE directory.
  • Generate internal storage filenames independently of user-visible project names.
  • Use exclusive file creation or explicit overwrite authorization where appropriate.
  • Write through a temporary file followed by an atomic rename.
  • Apply restrictive directory and file permissions.
  • Authenticate and authorize the /mock/load endpoint.
  • Add tests covering traversal through ../, encoded separators, absolute paths, and platform-specific separators.

T09 · Insecure Skill Coding Practices

Error
Location
mock_server.py:43
Finding

Sensitive Reference Values Persisted in Plaintext and Exposed Without Authentication

Content
View full analysis

Vulnerability Details

File Location: mock_server.py:43-45, mock_server.py:420-429, and mock_server.py:909-911
Vulnerability Type: Plaintext sensitive-data persistence and unauthenticated disclosure
Risk Level: High

Vulnerable Code

python
def _save_state():
    STATE_FILE.write_text(
        json.dumps(
            {
                "sequences": _sequences,
                "refs": _refs
            },
            ensure_ascii=False,
            indent=2
        ),
        encoding="utf-8"
    )
python
def gen_response_fields(fields, req_context: dict = None):
    req_context = req_context or {}
    resp = {}
    for f in fields:
        n = f.get("name", "")
        if not n or re.match(r".*sign.*", n.lower()):
            continue
        when = f.get("when")
        if when and not _check_condition(when, req_context):
            continue
        v = gen_field_value(f, req_context)
        if v is not None:
            resp[n] = v
            if f.get("is_ref"):
                with _lock:
                    _refs[n] = v
    return resp
python
@app.get("/mock/state")
async def get_state():
    return {
        "code": 0,
        "data": {
            "sequences": _sequences,
            "refs": _refs
        }
    }

Technical Analysis

Any response field marked is_ref is copied into the global _refs dictionary. The state is then written to state_store.json in plaintext. The Skill documentation explicitly presents access tokens as an intended use of this mechanism.

The application does not distinguish synthetic mock values from real credentials. If a real token, session identifier, order reference, or other sensitive value enters _refs, it remains readable on disk across service restarts. The complete reference dictionary is also returned by the unauthenticated /mock/state endpoint.

There is n ...[truncated 1219 chars]

Remediation
View remediation

Remediation Suggestions

  • Do not persist reference values by default.
  • Clearly prohibit the use of real production credentials in MockLab documentation and UI warnings.
  • Maintain an explicit denylist of sensitive names such as token, authorization, cookie, secret, and password.
  • Redact sensitive values from /mock/state responses.
  • Require authentication and authorization for state inspection and deletion.
  • Add per-project and per-user state isolation.
  • Apply short expiration times and automatic cleanup.
  • If sensitive persistence is essential, use operating-system-backed secret storage or authenticated encryption with externally managed keys.
  • Create state files with owner-only permissions.
  • Avoid silently ignoring state-loading errors, and log security-relevant failures without exposing secret values.

T09 · Insecure Skill Coding Practices

Warning
Location
ui.html:604
Finding

Browser Sends Request Bodies and Authorization Headers to Arbitrary User-Supplied Origins

Content
View full analysis

Vulnerability Details

File Location: ui.html:604-627
Vulnerability Type: Unrestricted client-side sensitive-data transmission
Risk Level: Medium

Vulnerable Code

javascript
// ── 3. 收集请求头 ───────────────────
var customHeaders = {};
_reqHeaders.forEach(function (h) {
  if (h.key && h.key.trim()) {
    customHeaders[h.key.trim()] = h.value || "";
  }
});

// ── 4. 获取 Seed ────────────────────
var seed = getSeed();

$("#resp-body").html(
  '<div class="eh" style="color:#888">' +
  '<div class="ic">⏳</div>请求中...</div>'
);

try {
  var targetUrl = $("#proxy-url").val().trim();
  var r;
  if (targetUrl) {
    // 代理转发模式:直接把请求发送到真实目标地址(浏览器直连)
    var proxyFetchOptions = {
      method: curIface.method || "POST",
      headers: Object.assign(
        {},
        customHeaders,
        {"Content-Type": "application/json"}
      ),
      body: JSON.stringify(req)
    };
    r = await fetch(targetUrl, proxyFetchOptions);
  }

Technical Analysis

When a value is entered in the proxy URL field, the browser sends the complete generated request body and every configured custom header directly to that URL. The target is not restricted to a trusted origin, and there is no confirmation prompt or warning when sensitive headers such as Authorization are present.

This is an overt implementation of the declared real-request forwarding feature rather than hidden exfiltration. Nevertheless, it does not enforce minimum privilege: arbitrary destinations receive all configured headers and request fields, even when only a subset may be required.

Browser CORS controls whether the calling page can read the response, but CORS is not a complete data-loss defense. Depending on request composition and destination policy, the request may still reach the remote server, and any transmitted body or credential is then visible to that server.

Attack Path

  1. A user configures requ ...[truncated 923 chars]
Remediation
View remediation

Remediation Suggestions

  • Require explicit confirmation before sending data to a new origin.
  • Display the normalized destination scheme, hostname, and port prominently.
  • Warn when Authorization, Cookie, API-key, token, or secret-like headers are present.
  • Maintain a per-project allowlist of approved origins.
  • Restrict destination schemes to https unless local HTTP access is explicitly enabled.
  • Do not automatically forward every custom header; require per-header forwarding approval.
  • Strip browser cookies and sensitive headers by default.
  • Add a preview showing the exact headers and body that will be transmitted.
  • Prevent credentials from being saved in project schemas or browser storage.
  • Document that users must use synthetic credentials when testing untrusted endpoints.
Vulnerability Patterns
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • System Prompt LeakageDirect Leakage, Indirect Extraction, Tool-Based Exfiltration
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
Findings (51)

Tp4

High
Category
MCP Tool Poisoning
Confidence
98% confidence
Finding

The declared description presents a full-featured Mock API toolchain with AI-driven document understanding and mock server generation. However, the provided code chunk does not implement any of those core capabilities. It is a standard Playwright configuration for end-to-end testing against an existing local service at http://localhost:18080. Although a commented section mentions optionally starting a MockLab server, that functionality is not active in this code. Therefore the actual behavior is materially different from the declared primary purpose, indicating a clear mismatch.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
99% confidence
Finding

This code is a standard third-party dependency (jQuery), not the implementation of the described MockLab skill. While jQuery includes generic AJAX/network and UI-manipulation capabilities that could support a web app, the chunk itself does not realize the declared end-user behavior. The declared description promises a specialized API mocking/debugging workflow, but the actual code only supplies low-level browser utilities. That is a material description-behavior mismatch.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

声明描述的是产品级功能:理解接口文档、生成 Schema、启动 Mock Server、请求转发和数据复现等。而实际代码并未实现这些核心能力,主要是一个针对现有 MockLab UI 的快速验证测试。它通过 Playwright 打开 localhost 页面、选择固定项目“峻茗”、编辑固定接口路径,并断言 nested 字段展示内容是否正确。这属于内部测试/回归验证代码,与声明的主要用途相比存在明显偏差。虽然测试对象与 MockLab 相关,但该代码块本身不执行所宣称的核心业务流程,因此应判定为描述与行为不匹配。

Content

No source excerpt is available for this finding.

Ssd 3

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The example explicitly instructs the system to surface header values such as Authorization via header:Authorization, which creates a direct credential disclosure pattern. In the skill context this is especially dangerous because the tool is meant for API integration debugging, where real bearer tokens and partner credentials are likely to be present in requests.

Content

No source excerpt is available for this finding.

Direct Prompt Extraction

High
Category
System Prompt Leakage
Confidence
85% confidence
Finding

Skill contains instructions that could directly expose system prompts, internal rules, or hidden instructions to users or external parties.

Content

Scanner excerpt · mock_server.py (reported line 432)May include surrounding context.

python
return resp

def _is_nested_rule(rule):
    return rule and (rule.startswith("nested:") or rule.startswith("object:") or rule.startswith("array:"))

def gen_req_example_fields(fields):
    result = []

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

The /mock/proxy endpoint is an open proxy that accepts an arbitrary target_url and forwards caller-supplied method, headers, and body to that destination. This enables SSRF against internal services, scanning of network-reachable hosts, and abuse of the server as a relay to send authenticated or disguised outbound traffic beyond the mock-server’s intended purpose.

Content

No source excerpt is available for this finding.

Hidden Instructions

High
Category
Prompt Injection
Confidence
70% confidence
Finding

Hidden instructions were detected in comments or invisible text. These could contain malicious directives. Manual review is recommended.

Content

Scanner excerpt · ui.html (reported line 31)May include surrounding context.

html
</div>

      <select id="proj-select">
        <!-- <option value="">-- 选择项目 --</option> -->
      </select>

      <div style="display:flex;gap:6px;">

Hidden Instructions

High
Category
Prompt Injection
Confidence
70% confidence
Finding

Hidden instructions were detected in comments or invisible text. These could contain malicious directives. Manual review is recommended.

Content

Scanner excerpt · ui.html (reported line 80)May include surrounding context.

html
<input id="in-delay-max" placeholder="最大ms" style="width:70px" type="number" min="0">
            <span class="hint">ms</span>
          </div>
          <!-- 错误注入配置 -->
          <div class="sg">
            <label>错误</label>
            <input type="checkbox" id="in-err-on" style="width:14px;height:14px;cursor:pointer">

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The README explicitly promotes proxying requests to real endpoints and attaching Authorization headers, but provides no warning that user-supplied data and credentials may be transmitted to localhost or external services. In this skill context, that omission is more dangerous because the tool is designed to ingest arbitrary interface documents and rapidly stand up forwarding behavior, which can normalize sending sensitive tokens or test data to unintended destinations.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The README promotes a 'Real Proxy' feature that forwards user-supplied requests, including custom Authorization headers, to an arbitrary target address without clearly warning that this may transmit real credentials and sensitive request data to another service. In a tool explicitly designed for API debugging and third-party integration, omission of this warning increases the likelihood of accidental secret leakage, unintended data disclosure, or misuse as an SSRF-style relay if operators enter untrusted/internal destinations.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
88% confidence
Finding

The skill declares behavior that reads local files, fetches remote URLs, writes schemas/state to disk, and launches a local server/browser, but it does not declare any explicit tool scope or permissions boundary. That makes the effective capability surface opaque to users and policy layers, increasing the risk of unintended file, network, and execution actions when the skill is invoked.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
73% confidence
Finding

The skill description and operating instructions are entirely in Chinese and specify Chinese-specific semantic behavior such as generating 中文姓名 and strict Chinese field interpretation, without offering the user any language or locale choice. Under the policy, language or locale constraints should either be optional or clearly justified as region-specific.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The trigger phrases are broad enough to match ordinary requests about API integration or mocking, which can cause the skill to activate in contexts where the user did not intend file reads, URL fetching, schema generation, disk writes, or server startup. In a skill with side effects, overbroad activation materially increases the chance of unintended action.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The skill says it will fetch remote URLs and automatically start a local server and open a browser, but those side effects are not prominently warned in the high-level description. Automatic network access and process/UI launch can surprise users, expose local environment details, and widen attack surface if untrusted documentation URLs are supplied.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The workflow instructs the system to save generated schema files and persist state, but the user-facing description does not clearly disclose that data will be written to disk. Because interface documentation and state can contain proprietary or sensitive integration details, silent persistence increases confidentiality and retention risk.

Content

No source excerpt is available for this finding.

Ssd 3

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The documented behavior normalizes mirroring request fields, body values, query parameters, path parameters, and headers back into responses. In practice, API requests often contain secrets, tokens, personal data, and internal identifiers, so reflecting them can disclose sensitive data to logs, UIs, downstream consumers, or anyone with access to the mock service.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This markdown file contains user-facing instructions exclusively in Chinese, including headings, workflow guidance, and troubleshooting, with no indication that users may choose another language. The policy for natural-language violations applies to all file types and flags forced language usage without user opt-in.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The product description explicitly promotes request forwarding to real endpoints and use of custom Authorization headers, but does not warn users that requests may leave the local environment or that secrets and test data could be sent to live or third-party systems. In a skill that can proxy arbitrary requests, this omission increases the chance of accidental credential exposure, unintended external calls, and misuse of production or sensitive environments.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The activation guidance tells users to start the tool and provide interface documentation via local files, pasted content, or URLs without cautioning that such materials may contain API secrets, internal endpoints, sample tokens, or proprietary schemas. Because the skill is designed to ingest arbitrary interface documents and automatically process them, missing privacy and sensitivity warnings creates a realistic risk of exposing confidential information during normal use.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The same proxy endpoint forwards arbitrary request data to external targets without any in-band warning, consent gate, or disclosure. In a skill intended for mocking/debugging, this increases the chance that users unknowingly send sensitive headers, tokens, or request bodies to real third-party or attacker-controlled endpoints.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The endpoint resets sequences and refs in memory and then saves the cleared state to disk, making the deletion persistent. This is an irreversible/destructive operation, but the code provides no confirmation prompt or explicit warning to the user before clearing stored state.

Content

No source excerpt is available for this finding.

Ae2

Medium
Category
analysis-evasion
Confidence
90% confidence
Finding

Artifact content does not match its filename extension

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The document is entirely written in Chinese, including headings, instructions, field explanations, and behavioral notes, with no indication that another language is supported or that Chinese is an opt-in locale. Under the policy, forcing a specific language without user choice is a natural-language locale 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
88% confidence
Finding

The title and all instructional content are written as mandatory guidance in Chinese, including wording like '必须严格遵守', with no indication that another language is allowed or that the locale restriction is required for a region-specific workflow. This can violate language/locale policy when a skill or reference enforces a specific language without user opt-in.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

This markdown file uses Chinese throughout for installation, operation, debugging, and troubleshooting instructions, which effectively forces a specific language for users of the skill. The policy allows locale constraints only when users are given a choice or when the regional limitation is clearly documented and justified, neither of which appears here.

Content

No source excerpt is available for this finding.