Back to skill

Security audit

A Share Trader

Security checks for vulnerabilities and agentic risk

Overview

This A-share trading skill is not visibly stealing data or installing backdoors, but its trading/live-mode framing, synthetic market data, and weak risk gates make it unsafe to treat as a real trading tool without review.

Install only if you intend to inspect or run a development/simulation trading framework. Do not connect it to a real brokerage account or rely on its outputs for financial decisions unless live mode is disabled by default, real data provenance is enforced, risk controls fail closed, and every live order requires explicit user confirmation.

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

T09 · Insecure Skill Coding Practices

Warning
Location
core/a_share_trader.py:346
Finding

Fail-Open Risk Controls Permit Trading Decisions Based on Synthetic Data

Content
View full analysis

Vulnerability Details

File Location: core/a_share_trader.py:346-359, 507-518, 738-784; core/data_interface.py:16-29, 187-219, 273-294; core/real_data_interface.py:137-157, 202-235, 252-289
Vulnerability Type: Fail-open risk management and silent synthetic-data fallback
Risk Level: Medium

Evidence

The required production risk-management package is not present in the reviewed project. When it cannot be imported, the engine installs a mock risk manager:

python
# 初始化风控管理器
try:
    from risk_management.core import AShareRiskManager
    self.risk_manager = AShareRiskManager(
        max_drawdown=self.config["risk"]["max_drawdown"],
        stop_loss_per_trade=self.config["risk"]["stop_loss_per_trade"],
        capital=self.capital,
        config=self.config
    )
    logger.info("A股风控管理器初始化成功")
except ImportError as e:
    logger.error(f"风控管理器初始化失败: {e}")
    self.risk_manager = self._create_mock_risk_manager()

The fallback manager approves every submitted signal:

python
def _create_mock_risk_manager(self):
    """创建模拟风控管理器"""
    class MockRiskManager:
        def __init__(self):
            pass
        
        def check_trade_risk(self, symbol: str, price: float, quantity: int, side: str) -> Tuple[bool, str]:
            return True, "风险检查通过"
    
    return MockRiskManager()

A second fail-open path approves signals when no risk manager is available:

python
if self.risk_manager:
    try:
        approved, reason = self.risk_manager.check_trade_risk(symbol, price, quantity, side)
        if approved:
            signal["risk_check"] = {"approved": True, "reason": reason}
            approved_signals.append(signal)
        else:
            signal["risk_check"] = {"approved": False, "reason": reason}
            logger.warning(f"信号被风控拒绝: {symbol} {side}, 原因: {reason}")
    except Exception as e:
        logger.error(f"风控检查失败: {e}")
        signal["risk_check"] = {"approved": False, "reason": f"风控检查异常: {e}"}
else:

...[truncated 6577 chars]
Remediation
View remediation

Remediation Suggestions

  1. Fail closed when risk management is unavailable

    • Abort initialization in paper and live modes if the production risk manager cannot be imported.
    • Allow the mock manager only when an explicit simulation-only setting is enabled.
    • Replace unconditional approval with conservative rejection by default.
  2. Disable unsupported live execution

    • Reject mode="live" until an authenticated broker adapter, reconciliation process, and production risk manager are configured.
    • Represent all locally modeled orders as SIMULATED; never use EXECUTED without confirmation from an external execution venue.
  3. Add mandatory execution-boundary validation

    • Restrict sides to explicitly supported values and ensure HOLD never reaches execution.
    • Validate symbols against an authorized universe.
    • Reject non-numeric, non-finite, zero, and negative prices or quantities.
    • Enforce exchange lot sizes, available cash, current holdings, maximum positions, position size, industry concentration, daily loss, and drawdown limits.
    • Prevent selling more shares than are held.
    • Recalculate commissions and exposure using trusted execution prices.
  4. Make data provenance explicit

    • Attach a source, retrieval time, freshness status, and is_synthetic marker to every data record.
    • Prohibit synthetic records from entering paper-with-real-data or live workflows.
    • Do not silently replace failed provider responses with random values.
    • Return a typed provider error and stop the trading cycle when authoritative data is unavailable.
  5. Separate interfaces by purpose

    • Rename the existing random interface to make its simulation-only role unambiguous.
    • Implement real provider adapters separately and require explicit configuration.
    • Implement Tushare authentication and retrieval before representing that source as available.
  6. Harden deployment and testing

    • Add tests proving that missi ...[truncated 399 chars]
Vulnerability Patterns
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
Findings (42)

Missing User Warnings

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill metadata declares stock data access and trading permissions but does not prominently warn that the skill could perform real trades or require explicit user confirmation before any live trading action. In this context, the absence of an explicit confirmation boundary is especially dangerous because an agent could interpret routine requests as authorization to place real orders, causing immediate financial loss or unauthorized market activity.

Content

No source excerpt is available for this finding.

Missing User Warnings

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The program accepts --mode live and then runs the same automated execution flow without an explicit confirmation gate, broker safety interlock, or startup warning. In a trading engine, this can cause unintended real-money transactions if launched with live mode by mistake or by another component, making the skill context materially more dangerous than ordinary automation code.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The module and class present themselves as a real A-share data interface, but several public methods silently return random simulated data when live sources are unavailable or unimplemented. In a financial-analysis skill, this can mislead downstream agents or users into treating fabricated prices and fundamentals as authoritative, leading to materially incorrect decisions.

Content

No source excerpt is available for this finding.

Vague Triggers

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The invocation examples are very broad and encourage the agent to run the trading framework on generic prompts such as 'run the A-share trading framework' or 'execute backtest' without clearly distinguishing analysis, simulation, and live trading. In a financial-trading skill that may have data access and trading permissions, ambiguous activation materially increases the risk of unintended high-impact actions, including autonomous trade execution without explicit user intent verification.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The file’s natural-language interface, documentation strings, log messages, and CLI descriptions are entirely in Chinese and specifically tailored to the A-share market, without offering a language or locale choice. This can violate language/locale policy when a skill imposes one language on users without explicit opt-in or documented restriction.

Content

No source excerpt is available for this finding.

Dynamic import via __import__()

Medium
Category
Dangerous Code Execution
Confidence
75% confidence
Finding

Dynamic import() can load arbitrary modules at runtime, bypassing static analysis and potentially importing malicious code.

Content

Scanner excerpt · core/a_share_trader.py (reported line 390)May include surrounding context.

python
for strategy_key, module_name, class_name in strategy_initializers:
            if self.config["strategies"][strategy_key]["enabled"]:
                try:
                    module = __import__(module_name, fromlist=[class_name])
                    strategy_class = getattr(module, class_name)
                    
                    # 获取策略配置

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The helper is documented as creating a performance tracker, and generate_report is used later as if it can produce a valid performance report. However, PerformanceTracker.generate_report() reads self.max_drawdown at L551 even though that attribute is never initialized in the tracker class, so report generation can fail at runtime instead of fulfilling the documented reporting intent.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

This Python file contains natural-language documentation and user-visible log strings exclusively in Chinese, such as the module description and later status messages. Under the policy, forcing a specific language without user opt-in is a locale-policy violation unless the regional constraint is clearly documented and justified for users.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

Two supposedly calculated A-share-specific indicators are produced with random.uniform(), yet they feed directly into sentiment scoring and market-state recognition. This makes trading decisions non-deterministic and misleading, undermines auditability, and can cause unsafe or manipulated portfolio behavior in a financial system.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The module advertises itself as an A-share data interface for a core trading framework, but nearly all returned values are fabricated using random numbers rather than sourced from real providers. In a trading or analytical workflow, this can silently poison decisions, backtests, alerts, and automated orders because consumers are likely to trust the interface contract and documentation.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The module title, class name docstring, and all user-facing descriptions are written only in Chinese and specifically scoped to A-share markets, with no indication that users can select another language or locale. The policy for this audit flags language/locale constraints when a skill effectively forces a specific language without opt-in or explicit justification.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The module description is written as '真实A股数据接口', and the user-facing class/docstrings and printed output throughout the file are exclusively in Chinese. This imposes a specific language experience without any indication of language choice or opt-in, which matches the language/locale policy violation criteria.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The tushare code path is documented as fetching real data, but the implementation always falls back to mock data due to missing token handling. This creates a deceptive trust boundary where callers believe they are receiving live market data from tushare when they are actually getting fabricated values.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The file’s user-facing docstrings, log messages, CLI description, and help text are entirely in Chinese, which effectively forces a specific language for users interacting with the skill. There is no opt-in, alternate language path, or documented justification that this skill is intentionally restricted to a Chinese-speaking or region-specific audience.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This Python file contains user-facing descriptions and console output entirely in Chinese, including the module docstring and CLI/help text. Because the skill does not offer any user opt-in or alternative locale, it imposes a specific language choice, which matches the policy's language/locale violation criterion.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The strategy claims to operate on CSI1000 constituents, but _get_index_constituents randomly samples symbols and _is_index_constituent may also randomly classify membership. This creates materially misleading behavior: backtests, live trading decisions, and risk assumptions can diverge from the documented universe, causing unintended exposure and unreliable results.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The module docstring, class docstring, parameter descriptions, log messages, and signal reasons are written entirely in Chinese, which imposes a specific language on users and operators. The file does not indicate that the strategy is region-specific or provide any opt-in or alternative locale, so it appears to violate the language/locale policy criterion.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

This code file contains natural-language descriptions and user-facing messages exclusively in Chinese, including the module docstring and later log/reason strings. Under the policy, forcing a specific language without user opt-in is a natural-language policy violation unless the locale restriction is explicitly justified.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The strategy documentation says selection depends on price relative to MA250, but the implementation substitutes a random simulated MA250 when technical data is absent. This makes ranking and trade selection arbitrary, undermining strategy integrity and enabling unpredictable market actions under missing-data conditions.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The strategy explicitly claims to filter on recent profit-growth and profit metrics, but when fundamental data is missing it fabricates random values and uses them for stock selection. In a trading system, this silently converts a data-driven control into nondeterministic behavior, causing unauthorized or misleading trades while appearing to satisfy documented financial constraints.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

This Python file contains natural-language descriptions entirely in Chinese, including the module docstring and later user-facing reason strings, with no indication that the skill is China-specific or that users can opt into another language. Under the policy, forcing a specific language without user choice is a natural-language policy violation.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The module docstring defines a four-dimension model including sentiment marked as unused, while the implementation never processes sentiment at all and instead applies momentum filtering/scoring in generate_signals and related methods. This is not just incomplete documentation: the documented dimensional model contradicts the implemented one, creating a misleading statement of the strategy's actual decision logic.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The inline comments explicitly state that the cycle dimension is part of the strategy and is handled elsewhere, but within this file the cycle flag is never consulted in signal generation, filtering, or scoring. Because the code presents this as an active dimension in the strategy configuration while implementing no corresponding behavior, the comments and effective logic diverge.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The module docstring and all descriptive text are written exclusively in Chinese, and the generated signal reasons and logs also use Chinese-only user-facing strings. Under the stated policy, forcing a specific language without user opt-in is a natural-language policy violation unless the locale restriction is explicitly documented and justified, which it is not here.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The strategy’s documented selection rule says the final screen should choose stocks with the lowest 20-day turnover-volatility, but the implementation silently falls back to taking the existing order when technical data is missing and may use random values when the metric is absent per symbol. In a trading skill, this creates integrity and reproducibility risk: portfolio decisions can diverge materially from the stated strategy, making behavior non-deterministic and potentially masking data-quality failures.

Content

No source excerpt is available for this finding.

Static analysis

No suspicious patterns detected.