Back to skill

Security audit

question-bank-api

Security checks for vulnerabilities and agentic risk

Overview

The skill mostly matches its stated purpose, but its API-key handling can expose the key if a custom API server or command-line key is used.

Review before installing. Use this only if you trust the API provider, keep QB_API_BASE on the official HTTPS endpoint unless you fully trust another gateway, prefer QB_API_KEY in the environment over --key, avoid sharing logs or commands containing the key, and choose Word export paths carefully because existing files may be overwritten.

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

Error
Location
scripts/qb.py:41
Finding
API Key Disclosure Through an Unrestricted API Base URL<![CDATA[ ## Vulnerability Details **File Location**: `scripts/qb.py:41-61` **Additional References**: `scripts/qb.py:428-429`, `SKILL.md:30-31`, `README.md:17-20` **Vulnerability Type**: Credential disclosure through an unvalidated network destination **Risk Level**: High ### Vulnerable Code ```python def cfg(args): base = (getattr(args, "base", None) or os.environ.get("QB_API_BASE") or DEFAULT_BASE).rstrip("/") key = getattr(args, "key", None) or os.environ.get("QB_API_KEY") or "" timeout = getattr(args, "timeout", None) or int(os.environ.get("QB_TIMEOUT", "30")) return base, key, timeout def post(base, key, timeout, path, payload=None, raw=False, out_path=None, dry_run=False): url = base + path body = json.dumps(payload or {}).encode("utf-8") if dry_run or DRY: print(f"[dry-run] POST {url}\n body={payload}", file=sys.stderr) return None req = urllib.request.Request(url, data=body, method="POST") req.add_header("Content-Type", "application/json") if key: req.add_header("X-API-Key", key) last = None for attempt in range(3): try: with urllib.request.urlopen(req, timeout=timeout) as r: ``` The unrestricted configuration is exposed through these arguments: ```python common.add_argument("--base") common.add_argument("--key") ``` ### Technical Analysis The client permits `QB_API_BASE` or `--base` to specify an arbitrary URL. The value is only processed with `rstrip("/")`; it is not parsed or validated for: - An HTTPS scheme - The expected vendor hostname - An approved port - Embedded username or password components - Unexpected path components - Redirects to a different origin The `post()` function then appends a fixed API path and attaches the user's `X-API-Key` header to the resulting request. Consequently, anyone who controls or influences the base URL controls the destination that receives the API credential and request body. Sending the API key to ...[truncated 1956 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Parse the base URL with `urllib.parse.urlsplit()` rather than concatenating an unchecked string. 2. Require `scheme == "https"` and reject HTTP or unsupported schemes. 3. Pin the default production hostname, such as `api.xuekubao.com`. 4. If alternative gateways are operationally required, use an explicit hostname allowlist rather than accepting arbitrary destinations. 5. Reject URLs containing user-information, fragments, query strings, or unexpected base paths. 6. Restrict ports to approved TLS ports unless a trusted administrator explicitly configures otherwise. 7. Require an explicit confirmation before sending credentials to any non-default approved gateway. 8. Disable cross-origin redirects or verify every redirect destination before forwarding `X-API-Key`. 9. Construct endpoint URLs using safe URL-parsing and joining logic. 10. Add tests proving that HTTP URLs, attacker-controlled hosts, embedded credentials, and redirect-based host changes are rejected. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/test_local.sh:19
Finding
API Key Exposure Through Command-Line Arguments<![CDATA[ ## Vulnerability Details **File Location**: `scripts/test_local.sh:19-45` **Additional References**: `scripts/qb.py:428-429`, `SKILL.md:31,38`, `README.md:17` **Vulnerability Type**: Sensitive credential exposure in process arguments and shell history **Risk Level**: Medium ### Vulnerable Code ```bash # 支持直接传参:bash test_local.sh --base <网关> --key <key> [--py <python>] # 没传则回退到环境变量 QB_API_BASE / QB_API_KEY(避免 PowerShell→bash 环境变量继承丢失) BASE=""; KEY=""; PY="${PYTHON:-python3}" while [ $# -gt 0 ]; do case "$1" in --base) BASE="$2"; shift 2;; --key) KEY="$2"; shift 2;; --py) PY="$2"; shift 2;; *) echo "[忽略未知参数] $1"; shift;; esac done BASE="${BASE:-${QB_API_BASE:-}}" KEY="${KEY:-${QB_API_KEY:-}}" if [ -z "$BASE" ] || [ -z "$KEY" ]; then echo "[错误] 请提供 --base 和 --key 参数,或先设置 QB_API_BASE / QB_API_KEY 环境变量" >&2 exit 1 fi run() { echo echo "==================================================" echo "### $*" echo "==================================================" "$PY" "$(dirname "$0")/qb.py" "$@" --base "$BASE" --key "$KEY" } ``` The Python client explicitly accepts the secret as a command-line argument: ```python common.add_argument("--base") common.add_argument("--key") ``` ### Technical Analysis The documentation and test script support supplying the API key using `--key`. Secrets passed in command-line arguments can be exposed through several operating-system and operational channels: - Shell command history - Process listings and process inspection interfaces - Diagnostic and endpoint-monitoring tools - CI/CD command logs - Terminal session recording - Crash reports or support bundles that capture process arguments The test script increases exposure by reading the key into `KEY` and then forwarding it to every Python invocation as `--key "$KEY"`. Even when the key originally comes from `QB_API_KEY`, the script converts it into a visible child-process command-line argument. Quoting the argument prevents sh ...[truncated 1514 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove `--key` from normal usage and documentation. 2. Read the API key from `QB_API_KEY` without forwarding it as a child-process argument. 3. Modify `test_local.sh` so child processes inherit the environment: ```bash QB_API_BASE="$BASE" QB_API_KEY="$KEY" \ "$PY" "$(dirname "$0")/qb.py" "$@" ``` 4. For interactive use, support hidden input with Python's `getpass.getpass()` when no environment-based credential is available. 5. Optionally support a credential file whose permissions are restricted to the current user. 6. Ensure CI systems inject the key through their secret-management facilities and mask it from logs. 7. Avoid printing, tracing, or including the key in errors. Document that users should not enable shell tracing while handling credentials. 8. If backward compatibility requires retaining `--key`, mark it as insecure and deprecated, and emit a warning directing users to a protected credential mechanism. 9. Rotate any production key that may already have been used in shell commands, shared logs, or recorded test sessions. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • 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
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (14)

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

Critical
Category
Data Flow
Content
last = None
    for attempt in range(3):
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                if raw or out_path:
                    data = r.read()
                    if out_path:
Confidence
90% confidence
Finding
Credentials or environment variables flow to a network sink. This is a high-confidence indicator of credential exfiltration.

Lp3

Medium
Category
MCP Least Privilege
Confidence
92% confidence
Finding
The skill invokes a Python script that uses environment variables and performs outbound network requests to a third-party API, but the manifest does not declare any tool scope or allowed tools. This creates an authorization and review gap: an agent may run code with broader-than-expected capabilities, including reading sensitive env vars or making unintended external requests, without explicit policy constraints.

Natural-Language Policy Violations

Medium
Confidence
93% confidence
Finding
The CLI help text, warnings, and printed output are presented in Chinese throughout the parser and runtime messages, which effectively forces a specific language for users. There is no visible option to select another locale or an explicit statement that the tool is region-specific and intentionally Chinese-only.

Missing User Warnings

Low
Confidence
86% confidence
Finding
This markdown file tells users to configure `QB_API_KEY` for the skill, which is a sensitive credential, but provides no warning about keeping the key secret or avoiding sharing it in logs, screenshots, or prompts. Under the markdown variant of SQP-2, omission of warnings about privacy- or data-affecting behavior is a valid finding.

Missing User Warnings

Low
Confidence
89% confidence
Finding
This markdown file documents that the script saves the binary DOCX stream to a local file via `--out`, which is a file-write operation. Under the markdown-specific warning rule, the description should disclose behaviors that affect user data or the local system, but no caution or warning is provided around overwriting or creating local files.

Missing User Warnings

Low
Confidence
84% confidence
Finding
The post() helper serializes payloads and sends them to a remote vendor API, including user-provided query content and identifiers, and may attach an API key header. While the module docstring describes the API client generally, the code path itself provides no confirmation prompt or user-facing disclosure when transmitting potentially sensitive user input to the external service.

Missing User Warnings

Low
Confidence
90% confidence
Finding
When out_path is provided, the code opens the path in write-binary mode and saves remote response data, overwriting any existing file at that location. Although the save is part of the command purpose, there is no pre-write warning, confirmation, or overwrite notice near the file-write operation itself.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def build_knowledge_payload(knowledgeId, args, page):
    p = {"knowledgeId": knowledgeId, "page": page or 1}
    for k in ("qtypeId", "paperType", "diff", "gradeId", "year"):
        v = getattr(args, k, None)
        if v is not None:
            p[k] = v
    return p
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Dynamic attribute access via getattr()

Low
Category
Dangerous Code Execution
Content
def cmd_chapter_tree(args, c):
    p = {"pharseId": args.pharseId}
    for k in ("subjectId", "editionId", "gradeId"):
        v = getattr(args, k)
        if v:
            p[k] = v
    d = post(*c, "/api/v1/chapterApi", p)
Confidence
50% confidence
Finding
Dynamic getattr() with a non-literal attribute name can access arbitrary object attributes, potentially bypassing access controls.

Static analysis

No suspicious patterns detected.