Back to skill

Security audit

A股量化工具包

Security checks for vulnerabilities and agentic risk

Overview

The skill is mostly a disclosed China A-share analysis toolkit, but it includes under-disclosed automatic interpreter handoff and optional external bridge behavior that users should review before installing.

Install only if you are comfortable with a finance-analysis skill that contacts third-party market-data providers and may disclose queried stock symbols. Review or remove the MSYS64 interpreter handoff in strategy_v4.py and the optional system_bridge alert synchronization in monitor_v3.py before using it in a trusted agent environment.

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
finance_toolkit/kds_strategy.py:1
Finding

Unauthenticated Adjacent Python File Execution

Content
View full analysis

Vulnerability Details

File Location: finance_toolkit/kds_strategy.py, line 1
Vulnerability Type: Arbitrary local code execution through dynamic loading of an untrusted adjacent file
Risk Level: Medium

Vulnerable Code

python
import sys, os as _os
_b = _os.path.join
_p = _b(
    _os.path.dirname(__file__) if '__file__' in dir() else '.',
    'python_bridge.py'
)
exec(compile(open(_p).read(), _p, 'exec')) if (
    _os.path.exists(_p)
    and 'msys64' in getattr(sys, 'executable', '')
) else None

The source file is stored as a single minified physical line. The snippet above preserves the complete vulnerable statement while formatting it for readability.

Technical Analysis

When the module is imported or executed under an MSYS64 Python environment, it checks whether a file named python_bridge.py exists beside kds_strategy.py. If present, the file is read, compiled, and executed directly in the current Python process.

The code performs no validation of the adjacent file's origin, ownership, permissions, contents, or cryptographic integrity. Moreover, python_bridge.py is not part of the audited project. Consequently, the effective behavior of the module can be changed after review merely by placing a new file at the expected path.

Although exploitation requires the attacker to gain write access to the package directory or influence how the project is deployed, use of exec() turns that local file-placement condition into arbitrary Python execution. The payload runs with the same process privileges and environment access as the user importing the module.

Attack Path

  1. The victim installs or extracts the project in a location where the attacker, another local user, a compromised installer, or an unsafe deployment process can create or replace files.
  2. The attacker creates finance_toolkit/python_bridge.py containing malicious Python code.
  3. The victim runs or imports ...[truncated 1181 chars]
Remediation
View remediation

Remediation Suggestions

  1. Remove the dynamic open()/compile()/exec() sequence entirely.
  2. If bridge functionality is required, include the bridge implementation as a reviewed package module and import it normally:
    python
    from . import python_bridge
    
  3. Do not load executable code merely because a file with an expected name exists beside the package.
  4. If runtime plugin loading is an unavoidable design requirement:
    • Load only from a fixed, administrator-controlled directory.
    • Reject writable-by-untrusted-user files and directories.
    • Verify the file against a pinned cryptographic hash or authenticated signature.
    • Execute plugins in a restricted subprocess with minimal filesystem, environment, and network access.
    • Require explicit user configuration rather than automatic execution during import.
  5. Avoid import-time side effects. Place environment compatibility logic in an explicit entry-point function.
  6. Add a security regression test confirming that an unexpected adjacent python_bridge.py is never executed.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (40)

Ae1

High
Category
analysis-evasion
Confidence
100% confidence
Finding

Referenced artifact was not completely inspected

Content

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

md
| 🎯 策略引擎 | `strategy_v4.py` | 多指标融合策略(布林带+RSI+KDJ+MACD) |

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The user-facing documentation is entirely in Chinese, including the title, feature descriptions, and usage guidance. Under the policy for natural-language violations, forcing a specific language without user opt-in can be a violation when no alternative language option or justification is provided.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The module docstring presents the skill solely in Chinese and specifically as an A-share toolkit, with no indication that language is selectable or that the Chinese-only presentation is an intentional user opt-in. This can violate a language/locale policy when skills are expected to avoid forcing a specific language unless clearly justified.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The module docstrings, comments, log messages, and console output are written in Chinese, which effectively forces a specific language for user-visible behavior. There is no indication that this is an explicitly documented locale-specific tool or that users can opt into another language.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · finance_toolkit/astock_engine.py (reported line 29)May include surrounding context.

python
def _curl(self, url, timeout=10):
        """通过curl获取数据"""
        try:
            result = subprocess.run(
                ['curl.exe', '-s', '--connect-timeout', str(timeout), url],
                capture_output=True, timeout=timeout+5
            )

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The module description and user-facing docstrings are presented only in Chinese, including the top-level description and strategy descriptions. This can violate a language/locale policy when a skill forces a specific language without user opt-in or documenting that it is intentionally region-specific.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The script conditionally re-executes itself via subprocess with a hard-coded interpreter path when it detects an MSYS2 environment. That introduces an unnecessary process-spawning capability for a backtesting tool and can bypass expected runtime controls, logging, dependency isolation, or policy restrictions tied to the original interpreter environment.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

SQP-3 applies to all file types and covers language/locale policy violations. This file embeds natural-language strings such as the module banner and later print labels entirely in Chinese, with no opt-in, fallback, or explanation that the skill is intentionally region-specific.

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 documentation and user-facing strings entirely in Chinese, including the module description and later printed analysis messages. Under the policy, forcing a specific language without user opt-in is a locale/language policy violation unless the constraint is clearly documented and justified as region-specific.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The top-level documentation states that kds.dll RingBuffer is embedded into the strategy to replace pandas rolling().mean(), implying the main strategy uses the C-backed implementation. However, FastMAStrategy.run instantiates SimpleSMA for both fast and slow averages, and even the benchmark labels a SimpleSMA instance as the 'C RingBuffer version', so the documented intent directly conflicts with the code's actual behavior.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The module performs dynamic code execution via exec(compile(open(_p).read(), ...)) on a neighboring python_bridge.py file and conditionally spawns another Python interpreter with subprocess.run. Executing local code at import time and re-invoking the process based on the runtime environment expands the attack surface substantially: a modified bridge file or manipulated environment can cause arbitrary code execution without any explicit user action beyond importing the module.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · finance_toolkit/kline_report.py (reported line 74)May include surrounding context.

python
)

    try:
        r = subprocess.run(
            ['curl.exe', '-s', url, '-L', '--max-time', '15'],
            capture_output=True, timeout=20
        )

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The top-level documentation describes the file as a real-time market monitor with technical scoring and FFT-based strategy tuning. However, the main execution path also imports SystemBridge and calls monitor_notify_knowledge(alerts), which performs cross-system notification/knowledge-base synchronization not mentioned in the documentation.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

Alert contents are sent to SystemBridge.monitor_notify_knowledge(alerts) without any explicit consent, disclosure, or local control in this file. Even though the data appears limited to stock names, alert types, prices, and loss information, this still creates an unannounced outbound data path that could leak sensitive trading activity or portfolio context into another system.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The module description and all generated user-facing report strings are fixed in Chinese, indicating the skill forces a specific language/locale. There is no opt-in, configuration, or documented justification for limiting output to Chinese only.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · finance_toolkit/strategy_engine.py (reported line 19)May include surrounding context.

python
def batch(self, symbols):
        if isinstance(symbols, str): symbols = [symbols]
        url = f"http://qt.gtimg.cn/q={','.join(symbols)}"
        r = subprocess.run(['curl.exe','-s',url], capture_output=True, timeout=10)
        raw = r.stdout.decode('gbk', errors='ignore')
        results = {}
        for line in raw.strip().strip(';').split(';'):

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The function docstring says '回测分析' and the CLI comments/usage also present this mode as '回测', which implies historical backtesting. However, the code immediately fetches only the current quote via api.batch([symbol]) and ignores the days_data parameter entirely, so it performs a live snapshot evaluation rather than a backtest.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The skill performs both interpreter handoff and external executable invocation, which is an unnecessary privilege expansion for a strategy-analysis tool. Because this is a local analysis skill rather than a deployment/runtime manager, the context makes subprocess-based execution more suspicious and increases the chance of code execution abuse or environment-specific compromise.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
93% confidence
Finding

The script conditionally re-executes itself with a hard-coded interpreter while forwarding the entire original argv. This creates an unsafe execution boundary: any caller-controlled arguments are propagated into a second process, and the hard-coded executable path can be hijacked if that binary is replaced or untrusted, leading to arbitrary code execution in environments where the skill runs with elevated trust.

Content

Scanner excerpt · finance_toolkit/strategy_v4.py (reported line 8)May include surrounding context.

python
import sys, os, subprocess as _bridge_sh
if 'msys64' in sys.executable:
    _bridge_sh.run(['C:/Python314/python.exe'] + sys.argv)
    sys.exit(0)

import subprocess, json, pandas as pd, numpy as np

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
95% confidence
Finding

This code invokes an external executable (curl.exe) to make an HTTP request using a URL built from the symbol parameter. Even without shell=True, spawning an external program introduces command/path hijack risk, and the use of plain HTTP allows network tampering of market data, which could mislead downstream decisions or trigger unsafe behavior based on forged responses.

Content

Scanner excerpt · finance_toolkit/strategy_v4.py (reported line 21)May include surrounding context.

python
def _sina_kline(self, symbol, days=400):
        """新浪K线数据"""
        url = f"http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol={symbol}&scale=240&ma=no&datalen={days}"
        r = subprocess.run(
            ['curl.exe','-s','-L','-e','http://finance.sina.com.cn',
             '-H','Referer: http://finance.sina.com.cn', url],
            capture_output=True, timeout=15)

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

The skill makes outbound requests to third-party services without any user-facing disclosure or consent. In an agent skill, hidden network egress is a real security and privacy issue because users may assume analysis is local; additionally, external responses can influence financial outputs without transparency.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
88% confidence
Finding

The skill again shells out to curl.exe for network retrieval using a URL derived from input. While arguments are passed as a list, reliance on an external executable still permits PATH/binary hijacking and expands the attack surface; malformed or attacker-controlled symbol values can also drive unintended outbound requests or denial-of-service conditions.

Content

Scanner excerpt · finance_toolkit/strategy_v4.py (reported line 35)May include surrounding context.

python
"""腾讯K线数据(备选)"""
        code = symbol.replace('sz', '').replace('sh', '')
        url = f"https://web.ifzq.gtimg.cn/appstock/app/minute/query?_var=kline&code={symbol}&r=0"
        r = subprocess.run(['curl.exe','-s',url], capture_output=True, timeout=15)
        raw = r.stdout.decode('utf-8', errors='ignore')
        try:
            import re

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

This second hidden network retrieval broadens undisclosed data egress and external dependency. In financial-analysis context, silently switching to fallback providers is especially risky because users may not realize recommendations are being generated from third-party data with different trust and integrity properties.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

Real-time quote retrieval performs silent outbound requests during live analysis. This is dangerous in skill form because repeated quote checks can leak user interest patterns or monitored symbols to third parties, and the returned data directly drives visible buy/avoid recommendations.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
90% confidence
Finding

Real-time quote lookup launches curl.exe against a URL composed from a symbols list, enabling uncontrolled outbound requests and dependence on an external binary. In a skill context, this is more dangerous because agent users may not expect the code to contact third-party services, and compromised responses can directly affect generated trading recommendations.

Content

Scanner excerpt · finance_toolkit/strategy_v4.py (reported line 456)May include surrounding context.

python
if isinstance(symbols, str): symbols = [symbols]
        import re
        url = f"http://qt.gtimg.cn/q={','.join(symbols)}"
        r = subprocess.run(['curl.exe','-s',url], capture_output=True, timeout=10)
        raw = r.stdout.decode('gbk', errors='ignore')
        results = {}
        for line in raw.strip().strip(';').split(';'):

Static analysis

No suspicious patterns detected.