Back to skill

Security audit

stock trading agents

Security checks for vulnerabilities and agentic risk

Overview

This appears to be a real stock-analysis skill, but it needs Review because it has under-disclosed external sharing, unsafe logging, path handling, background execution, and runtime package-install behavior.

Review before installing. Run it only in a dedicated virtual environment or sandbox, preinstall pinned dependencies, validate stock codes to the expected exchange format, avoid background log redirection with sensitive data, and assume stock symbols, generated reports, prompts, and summaries may be sent to Tushare, AKShare, DashScope/Aliyun, and DingTalk when those paths are used.

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

T09 · Insecure Skill Coding Practices

Error
Location
scripts/stock_advisor.py:157
Finding

Arbitrary Filesystem Write Location Through Unsanitized Stock Code

Content
View full analysis

Vulnerability Details

File Location: scripts/stock_advisor.py, lines 157-162
Vulnerability Type: Improper path validation leading to writes outside the intended report directory
Risk Level: High

Vulnerable Code

python
ts_code_safe = ts_code.replace('.', '_')
report_subdir = f"{ts_code_safe}_{timestamp}"
report_dir = os.path.join(base_report_dir, report_subdir)

if not os.path.exists(report_dir):
    os.makedirs(report_dir)

Technical Analysis

The report directory is derived directly from the caller-controlled ts_code. The only normalization performed is replacing periods with underscores. This does not reject absolute paths, path separators, drive prefixes, or other platform-specific path constructs.

In particular, if report_subdir is an absolute path, os.path.join(base_report_dir, report_subdir) discards base_report_dir. The application then creates the resulting directory and subsequently writes fixed-name Markdown and JSON report files into it.

The vulnerability does not grant permissions beyond those already held by the Skill process, but it breaks the intended output-directory boundary. No canonical-path containment check is performed before filesystem operations.

Attack Path

  1. An attacker or untrusted caller invokes StockAdvisorSystem.diagnose() with a crafted absolute-path-like stock code.
  2. The value passes through ts_code.replace('.', '_'), which does not remove path separators or reject absolute paths.
  3. os.path.join() resolves the attacker-controlled absolute component outside base_report_dir.
  4. os.makedirs() creates the attacker-selected directory if the process has permission.
  5. The diagnostic workflow writes generated Markdown reports and, when save_report() is called, a JSON report into that directory.
  6. Existing fixed-name files at the destination may be overwritten by later report-writing operations.

Impact Assessment

Succes ...[truncated 716 chars]

Remediation
View remediation

Remediation Suggestions

  1. Enforce a strict stock-code allowlist before constructing any path. For example:

    python
    import re
    
    if not re.fullmatch(r"[0-9]{6}\.(SH|SZ|BJ)", ts_code):
        raise ValueError("Invalid stock code")
    
  2. Generate the directory name only from validated components rather than attempting to sanitize arbitrary input.

  3. Resolve both the report root and destination and verify containment:

    python
    from pathlib import Path
    
    report_root = Path(base_report_dir).resolve()
    report_dir = (report_root / report_subdir).resolve()
    
    if report_root not in report_dir.parents:
        raise ValueError("Report path escapes the configured output directory")
    
    report_dir.mkdir(parents=True, exist_ok=False)
    
  4. Reject absolute paths, path separators, null bytes, drive prefixes, and reserved platform-specific names.

  5. Run the Skill under a minimally privileged account with write access limited to a dedicated report directory.

  6. Add tests covering absolute Unix paths, Windows drive paths, UNC paths, separators, malformed exchange suffixes, and unexpected Unicode path characters.

T08 · Insecure Dependencies

Warning
Location
scripts/stock_advisor.py:407
Finding

Unpinned Package Installation During Report Generation

Content
View full analysis

Vulnerability Details

File Location: scripts/stock_advisor.py, lines 407-413
Vulnerability Type: Runtime retrieval and installation of an unpinned third-party dependency
Risk Level: Medium

Vulnerable Code

python
try:
    from fpdf import FPDF  # pyright: ignore[reportMissingModuleSource]
except ImportError:
    print("正在安装 fpdf2...")
    import subprocess
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'fpdf2'])
    from fpdf import FPDF  # pyright: ignore[reportMissingModuleSource]

Technical Analysis

When fpdf cannot be imported, normal PDF report generation invokes pip and installs fpdf2 from the process's configured package index. The package version is not pinned and no integrity hash is verified.

Consequently, the code installed during execution can differ from the code reviewed with the Skill. Installation also modifies the active Python environment and may install transitive dependencies. Python package installation can execute package build and installation logic with the privileges of the Skill process.

Although setup.py declares fpdf2>=2.8.0, the runtime installation bypasses a controlled deployment or lockfile process and requests the latest package satisfying pip's default behavior without an explicit version constraint.

Attack Path

  1. The Skill runs in an environment where the fpdf module is missing or deliberately removed.
  2. A user invokes report saving, causing PDF generation to execute.
  3. The failed import enters the ImportError handler.
  4. The Skill launches pip and requests the unpinned fpdf2 package.
  5. Pip contacts its configured package index and downloads the currently resolved package and dependencies.
  6. Downloaded package installation or build code executes with the Skill process's privileges.
  7. A compromised package release, compromised index, maliciously configured package source, or dependency substituti ...[truncated 751 chars]
Remediation
View remediation

Remediation Suggestions

  1. Remove all runtime calls to pip. If fpdf2 is unavailable, terminate PDF generation with a clear dependency error.

  2. Install dependencies during a controlled build or deployment stage rather than during Skill execution.

  3. Pin fpdf2 and all transitive dependencies to reviewed versions in a lockfile.

  4. Use hash verification, such as pip's --require-hashes, to ensure downloaded artifacts match approved packages.

  5. Configure a trusted internal package mirror or an explicitly approved package index.

  6. Build an immutable virtual environment or container image and run it without package-installation privileges.

  7. Replace the fallback with behavior similar to:

    python
    try:
        from fpdf import FPDF
    except ImportError as exc:
        raise RuntimeError(
            "fpdf2 is required for PDF generation; install the locked project dependencies"
        ) from exc
    
  8. Add CI checks that create a clean environment from the locked dependency manifest and verify PDF generation without downloading packages at runtime.

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
  • Rogue AgentSelf-Modification, Session Persistence
Findings (84)

Tainted flow: 'url' from os.getenv (line 320, credential/environment) → requests.post (network output)

Critical
Category
Data Flow
Confidence
90% confidence
Finding

Credentials or environment variables flow to a network sink. This is a high-confidence indicator of credential exfiltration.

Content

Scanner excerpt · scripts/batch_diagnose.py (reported line 270)May include surrounding context.

python
print(f"\n{'=' * 60}")
        print("发送钉钉消息...")
        
        response = requests.post(
            url,
            json=data,
            headers={'Content-Type': 'application/json'},

Tainted flow: 'url' from os.getenv (line 320, credential/environment) → requests.post (network output)

Critical
Category
Data Flow
Confidence
90% confidence
Finding

Credentials or environment variables flow to a network sink. This is a high-confidence indicator of credential exfiltration.

Content

Scanner excerpt · scripts/batch_diagnose.py (reported line 330)May include surrounding context.

python
print(f"\n{'=' * 60}")
        print("发送钉钉消息...")
        
        response = requests.post(
            url,
            json=data,
            headers={'Content-Type': 'application/json'},

Tp4

High
Category
MCP Tool Poisoning
Confidence
89% confidence
Finding

The skill is presented as a local diagnosis/reporting tool, but analysis suggests it may also send outbound notifications, inspect historical report directories, and support batch input sources. These extra behaviors increase exposure of sensitive data and can surprise users with external data exfiltration or broader filesystem processing beyond the advertised one-shot analysis flow.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding

The skill is presented as a local diagnosis/reporting tool, but analysis suggests it may also send outbound notifications, inspect historical report directories, and support batch input sources. These extra behaviors increase exposure of sensitive data and can surprise users with external data exfiltration or broader filesystem processing beyond the advertised one-shot analysis flow.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
95% confidence
Finding

The skill is presented as a local diagnosis/reporting tool, but analysis suggests it may also send outbound notifications, inspect historical report directories, and support batch input sources. These extra behaviors increase exposure of sensitive data and can surprise users with external data exfiltration or broader filesystem processing beyond the advertised one-shot analysis flow.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
93% confidence
Finding

The skill is presented as a local diagnosis/reporting tool, but analysis suggests it may also send outbound notifications, inspect historical report directories, and support batch input sources. These extra behaviors increase exposure of sensitive data and can surprise users with external data exfiltration or broader filesystem processing beyond the advertised one-shot analysis flow.

Content

No source excerpt is available for this finding.

Ssd 3

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

This is a direct sensitive-data disclosure pattern: the code intentionally extracts and prints model 'thinking' during streaming. In an agent with memory and financial prompts, hidden reasoning can include user content, system prompts, prior messages, and synthesized confidential analysis, so log exposure is a real and serious leak.

Content

No source excerpt is available for this finding.

Ssd 3

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

NeutralRisk reproduces the same explicit leak mechanism by printing thinking content. Because agent memory is included in prompts, this can disclose more context than the immediate user request, increasing the blast radius of a single log exposure.

Content

No source excerpt is available for this finding.

Ssd 3

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

ConservativeRisk also exposes streamed thinking, creating a repeatable and likely systemic data leakage issue across agent roles. Since these roles process risk assessments and excerpts of trader reports, the leaked logs may contain market-sensitive or proprietary decision support content.

Content

No source excerpt is available for this finding.

Ssd 3

High
Category
Not specified by scanner
Confidence
100% confidence
Finding

This facilitator leak is especially severe because it handles aggregated outputs from multiple agents and may therefore expose a consolidated view of sensitive analysis. The skill context makes it more dangerous: a multi-agent trading workflow can accumulate confidential prompts, summaries, and positions, all of which may be printed in hidden reasoning form.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

This skill can install a Python package at runtime, a capability not required for its primary business function of stock analysis. That behavior introduces supply-chain risk, may alter the host environment, and can lead to execution of attacker-controlled code if package resolution, indexes, or network paths are compromised. The skill context makes this more dangerous because the feature is embedded in a reporting path users may consider harmless.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
95% confidence
Finding

The skill documentation advertises code paths that read environment variables, perform network access, write files, and invoke shell commands, but it declares no explicit tool scope or permissions boundary. In an agent skill ecosystem, that omission weakens user consent and makes it easier for a caller to trigger sensitive capabilities unexpectedly.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The skill description and documentation are presented entirely in Chinese and include assumptions such as Chinese stock symbols, Chinese report names, and Chinese font requirements, without stating that the skill is China-specific or giving users a language/locale choice. This creates a natural-language locale constraint that is not opt-in and is not explicitly justified as region-specific in the activation or usage guidance.

Content

No source excerpt is available for this finding.

Session Persistence

Medium
Category
Rogue Agent
Confidence
93% confidence
Finding

The skill explicitly recommends using nohup to run a long-lived background process, which enables execution to persist after the initiating session ends. In an agent context, persistence increases risk because network-capable and file-writing tasks may continue unattended, making abuse, runaway jobs, or unnoticed data processing harder to detect and stop.

Content

Scanner excerpt · SKILL.md (reported line 145)May include surrounding context.

直接运行诊断脚本

python3 scripts/stock_advisor.py --stock 600519.SH

或使用 nohup 后台运行(适合长时间任务)

nohup python3 scripts/stock_advisor.py --stock 600519.SH > diagnose.log 2>&1 &

text

Session Persistence

Medium
Category
Rogue Agent
Confidence
65% confidence
Finding

Skill establishes unauthorized persistence across sessions via cron jobs, startup scripts, or state files. Session persistence allows an attacker to maintain access beyond the current interaction.

Content

Scanner excerpt · SKILL.md (reported line 146)May include surrounding context.

python3 scripts/stock_advisor.py --stock 600519.SH

或使用 nohup 后台运行(适合长时间任务)

nohup python3 scripts/stock_advisor.py --stock 600519.SH > diagnose.log 2>&1 &

text

#### 方式 3:后台运行模式(防超时)

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The skill guides users through one-click diagnosis without a clear up-front warning that execution will call external APIs and network services. In a financial-analysis context, this can expose stock symbols, prompts, results, or environment-backed credentials to third parties without sufficiently informed consent.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The prompt explicitly requires '全文使用中文。请用中文回答。' which imposes a fixed language choice. The policy allows locale or language constraints only when the user is given a choice or the restriction is clearly justified as region-specific, neither of which is present here.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

This natural-language instruction requires the agent to answer only in Chinese. Because the file does not provide user opt-in or a documented justification for the fixed language policy, it is a language-policy violation.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The prompt states that the full report must use Chinese and asks the agent to answer in Chinese, enforcing a specific language. The stated policy requires either user choice or a clear justified locale restriction, which is absent here.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The prompt explicitly requires that the entire response be in Chinese and repeats that the model must answer in Chinese. This imposes a fixed language policy regardless of user preference, which matches the language/locale policy violation category.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The agent sends prompts, conversation memory, and analyst report content to a third-party LLM endpoint at DashScope without any in-code consent flow, redaction, or disclosure boundary. In a trading-analysis context, this can expose proprietary research, sensitive market views, or user-provided confidential data to an external processor, creating privacy, compliance, and data-governance risk.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The system prompt explicitly instructs the bullish agent to respond only in Chinese. This is a natural-language locale constraint with no user opt-in or explanation that the skill is intentionally limited to a Chinese-language context.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The bearish researcher agent also transmits user/system content and memory to the same external LLM service without any visible notice, consent, or data minimization controls. Because multiple agents process overlapping context, the design increases the amount of potentially sensitive content sent off-platform and broadens third-party exposure.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

This prompt requires the bearish agent to answer in Chinese, creating the same locale policy issue as the bullish agent. The file provides no mechanism for user language selection and no justification for a mandatory Chinese-only response.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The facilitator compiles debate history and synthesized analyst content, then sends that aggregate dataset to an external LLM endpoint. Aggregation can materially increase sensitivity because it consolidates multiple reports, internal reasoning, and recommendations into a single outbound prompt, raising confidentiality and compliance risks.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.