Back to skill

Security audit

数学计算协议服务

Security checks for vulnerabilities and agentic risk

Overview

This math skill uses a third-party API and stores the required API key in a local plaintext .env file, so it should be reviewed before installation.

Install only if you trust the XiaoBenYang service and are comfortable sending calculation inputs and the API key to that service. Use a narrowly scoped, revocable key; avoid submitting sensitive financial or private datasets; verify the configured endpoint before use; and remove any .env-stored key when no longer needed.

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

Warning
Location
scripts/config.py:45
Finding

API Key Persisted in a Plaintext File Without Enforced Access Controls

Content
View full analysis

Vulnerability Details

File Location: scripts/config.py:45-63
Related Instruction Location: SKILL.md:17-18, 34
Vulnerability Type: Plaintext credential storage with insecure file permissions
Risk Level: Medium

Vulnerable Code

python
def save_api_key_to_env(api_key: str) -> bool:
    """将API key保存到.env文件"""
    try:
        env_path = Path(".env")
        lines = []
        if env_path.exists():
            lines = env_path.read_text(encoding="utf-8").splitlines()
        found = False
        new_lines = []
        for line in lines:
            if line.startswith("XBY_APIKEY="):
                new_lines.append(f"XBY_APIKEY={api_key}")
                found = True
            else:
                new_lines.append(line)
        if not found:
            new_lines.append(f"XBY_APIKEY={api_key}")
        env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
        os.environ["XBY_APIKEY"] = api_key
        return True
    except Exception as e:
        print(f"保存API key失败: {e}")
        return False

The associated Skill instructions require this behavior:

markdown
- When the API key is obtained from the user, call
  `scripts.config.set_api_key(api_key)` to save it and continue processing.

Technical Analysis

The Skill collects an API credential from the user and writes it directly to a plaintext .env file. The file is addressed relative to the process's current working directory, and Path.write_text() does not explicitly enforce restrictive permissions such as owner-only mode 0600.

The resulting permissions depend on the process umask and any pre-existing file permissions. In shared execution environments, another local account or process may be able to read the credential. Because the destination is the current working directory, the key may also be written into an unrelated project directory, included in a backup, o ...[truncated 1438 chars]

Remediation
View remediation

Remediation Suggestions

  1. Prefer an operating-system credential store, platform secret manager, or session-only in-memory storage instead of a plaintext project file.
  2. If file persistence is necessary, place the credential in a dedicated per-user configuration directory rather than the current working directory.
  3. Create the secret file atomically with owner-only permissions, such as mode 0600 on POSIX systems.
  4. Verify and correct permissions when updating an existing file.
  5. Use a temporary file in the same protected directory, flush it, set its permissions, and atomically replace the destination.
  6. Ensure .env and equivalent secret files are excluded from source control, build artifacts, telemetry, and backups where appropriate.
  7. Inform the user before persisting the credential and offer a non-persistent configuration option.
  8. Apply server-side key scoping, rotation, expiration, rate limits, and revocation so disclosure has limited consequences.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/config.py:9
Finding

Configurable API Endpoint Can Exfiltrate Credentials and User Data Over an Untrusted Connection

Content
View full analysis

Vulnerability Details

File Location: scripts/config.py:9-20 and scripts/call_api.py:31-76
Vulnerability Type: Unvalidated security-sensitive endpoint configuration
Risk Level: Medium

Vulnerable Code

The endpoint is controlled through a Pydantic settings model with an environment-variable prefix:

python
class Settings(BaseSettings):
    """小笨羊高考Skill配置"""
    
    model_config = SettingsConfigDict(
        env_prefix="XBY_GAOKAO_",
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

    # API配置
    base_url: str = "https://mcp.xiaobenyang.com"
    mcp_id: str = "1820705335657482"
    api_key: str = ""

The client accepts both HTTP and HTTPS transports and sends the API key to the configured endpoint without validating its scheme or hostname:

python
class XiaoBenYangClient:
    """小笨羊MCP API客户端"""

    def __init__(self) -> None:
        self._session = requests.Session()
        retry_strategy = Retry(
            total=settings.max_retries,
            backoff_factor=0.5,
            status_forcelist=[429, 500, 502, 503, 504],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self._session.mount("http://", adapter)
        self._session.mount("https://", adapter)
        self._log = logging.getLogger("scripts.xiaobenyang")

    def close(self) -> None:
        self._session.close()

    def call_tool(
        self,
        mcp_id: str,
        tool_name: str,
        params: dict[str, Any],
    ) -> HttpResult:
        """调用小笨羊MCP工具"""
        url = f"{settings.base_url}/api"
        mcp_id = mcp_id or settings.mcp_id

        api_key = get_api_key()
        if not api_key:
            raise UpstreamError("API密钥未设置,请先调用 set_api_key()")
        
        headers = {
            "XBY-APIKEY": api_key,
            "func": tool_name,
            "mcpid": mcp_id
...[truncated 2841 chars]
Remediation
View remediation

Remediation Suggestions

  1. Pin the production API endpoint in code when endpoint customization is not required.
  2. If customization is necessary, parse the URL and enforce an explicit allowlist of approved hostnames and ports.
  3. Require the https scheme whenever an API key is transmitted; reject all plaintext HTTP endpoints.
  4. Reject URLs containing user information, unexpected ports, fragments, ambiguous hostnames, or nonstandard schemes.
  5. Resolve and validate the final destination where relevant, including protection against loopback, link-local, private-network, and metadata-service destinations.
  6. Disable redirects for authenticated requests or validate every redirect target before forwarding sensitive headers.
  7. Separate development endpoint overrides from production configuration and prevent untrusted users from controlling environment variables.
  8. Use narrowly scoped, revocable credentials and rotate the API key immediately if endpoint redirection may have occurred.
  9. Add automated tests confirming that HTTP URLs and unapproved hosts are rejected before any request is sent.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
Findings (33)

Tp4

High
Category
MCP Tool Poisoning
Confidence
98% confidence
Finding

The skill claims broad mathematics functionality but the described project structure centers on reading and writing API credentials, configuring remote endpoints, and interacting with an external service seemingly unrelated to math. Such mismatch is dangerous because users may share sensitive data under the false assumption computations happen locally and within the declared domain.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
99% confidence
Finding

The skill claims broad mathematics functionality but the described project structure centers on reading and writing API credentials, configuring remote endpoints, and interacting with an external service seemingly unrelated to math. Such mismatch is dangerous because users may share sensitive data under the false assumption computations happen locally and within the declared domain.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

请求头中的 func 直接使用外部传入的 tool_name,mcpid 也可由调用方指定,代码未实施任何授权、范围限制或语义校验。这使该技能具备任意远程工具调用能力;在“数学计算”场景下,这种能力明显超出正当用途,一旦被上层代理或提示注入驱动,可能调用危险或敏感的上游功能。

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

The file’s behavior is materially inconsistent with the declared math-computation skill: it defines Xiaobenyang/Gaokao-specific identifiers, reads an API key from .env, and exposes helpers to persist credentials. That mismatch strongly suggests hidden or repurposed functionality that can collect or retain secrets unrelated to the advertised skill, increasing supply-chain and credential-theft risk.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
84% confidence
Finding

Configuring the settings loader to read from .env establishes a credential-ingestion path for a skill whose advertised function is math computation, not external account access. In this context, secret loading is unnecessary and expands the attack surface by making local credential material available to the skill runtime.

Content

Scanner excerpt · scripts/config.py (reported line 13)May include surrounding context.

python
model_config = SettingsConfigDict(
        env_prefix="XBY_GAOKAO_",
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

Credential Access

High
Category
Privilege Escalation
Confidence
95% confidence
Finding

The model_post_init method explicitly reads .env and extracts XBY_APIKEY by name, bypassing normal configuration patterns to force secret acquisition. That direct secret-parsing behavior is especially suspicious in a math skill and could be used to harvest credentials present in the working directory.

Content

Scanner excerpt · scripts/config.py (reported line 31)May include surrounding context.

python
default_year: int = 2025

    def model_post_init(self, __context):
        # 强制从 .env 文件读取 XBY_APIKEY
        env_path = Path(".env")
        if env_path.exists():
            content = env_path.read_text(encoding="utf-8")

Credential Access

High
Category
Privilege Escalation
Confidence
95% confidence
Finding

The creation and use of Path('.env') to inspect local secret files is part of a deliberate credential-access workflow rather than incidental configuration. In the declared skill context, this behavior is unjustified and can expose stored credentials to code that users would not expect to handle secrets at all.

Content

Scanner excerpt · scripts/config.py (reported line 32)May include surrounding context.

python
def model_post_init(self, __context):
        # 强制从 .env 文件读取 XBY_APIKEY
        env_path = Path(".env")
        if env_path.exists():
            content = env_path.read_text(encoding="utf-8")
            for line in content.splitlines():

Credential Access

High
Category
Privilege Escalation
Confidence
90% confidence
Finding

The code prioritizes an environment variable override after reading XBY_APIKEY from .env, confirming intentional handling of a credential value throughout runtime. Even if meant for convenience, this propagates secret use into a skill where such access is out of scope, making accidental exposure or misuse more likely.

Content

Scanner excerpt · scripts/config.py (reported line 39)May include surrounding context.

python
if line.startswith("XBY_APIKEY="):
                    self.api_key = line.split("=", 1)[1].strip()
                    break
        # 如果环境变量有值,覆盖 .env 的值
        env_val = os.getenv("XBY_APIKEY", "")
        if env_val:
            self.api_key = env_val

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
97% confidence
Finding

The code persists a supplied API key into a local .env file and mirrors it into process environment state, creating unnecessary long-term secret storage for a skill that should not need external service credentials at all. Persistent plaintext storage increases the chance of accidental disclosure through repository commits, logs, backups, or local file access by other components.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
98% confidence
Finding

The save_api_key_to_env function writes API keys back into .env, creating a persistent plaintext credential sink. In combination with the misleading skill identity, this is highly concerning because it both solicits and stores secrets unrelated to the advertised functionality, enabling later misuse or exfiltration if the environment is compromised.

Content

Scanner excerpt · scripts/config.py (reported line 48)May include surrounding context.

python
def save_api_key_to_env(api_key: str) -> bool:
    """将API key保存到.env文件"""
    try:
        env_path = Path(".env")
        lines = []
        if env_path.exists():
            lines = env_path.read_text(encoding="utf-8").splitlines()

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
94% confidence
Finding

The skill declares itself as a math service but provides no explicit tool scope while the implementation is documented as using environment access, file reads/writes, and network calls. Missing scope boundaries increases the blast radius if the skill is misused or compromised, because it can solicit credentials, persist them, and exfiltrate data through external API calls.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill requires an external API key and mandates routing work through a remote API, contradicting the presentation of a self-contained math computation service. In this context, that makes the skill more dangerous because users expecting simple local calculations may unknowingly provide credentials and send data off-platform.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The skill instructs the agent to ask for a user API key and persist it, but provides no warning about storage location, retention, reuse, or exposure risks. This is dangerous because users may disclose credentials without informed consent, and persisted secrets in .env files are often readable by other components or later sessions.

Content

No source excerpt is available for this finding.

Ssd 3

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The skill explicitly instructs the model to solicit, store, and reuse a user-provided API key in plain language. In a skill that is actually a remote API proxy, this is more dangerous because it normalizes credential collection and persistence without clear controls, creating risk of secret exposure, replay, or misuse.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The workflow and project structure reveal dependency on an external xiaobenyang service, which conflicts with the generic math-server branding. This kind of domain mismatch undermines trust and can conceal where user inputs are processed, increasing risk of data leakage or unauthorized external transmission.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The workflow says code only calls APIs, while the tool descriptions claim computations are backed by local libraries like SymPy, Polars, NumPy, and SciPy. This inconsistency can mislead users and reviewers about where execution happens and whether sensitive expressions or datasets stay local, which is a security-relevant transparency failure.

Content

No source excerpt is available for this finding.

Ssd 3

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The skill directs the model to display raw API response data directly to the user. If the upstream service returns sensitive metadata, tokens, internal error details, or echoed secrets, this instruction can cause accidental disclosure and makes prompt/data exfiltration more likely.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

该文件实现的是一个通用的上游 MCP 工具调用器:tool_name、mcp_id 和 params 都可变,并未限制为数学相关能力。对于一个声明为“数学计算协议服务”的技能,这意味着技能可被用作任意远程能力转发器,突破用户对功能边界的预期,并可能调用与数学无关的敏感上游操作。

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

This code retrieves a credential via get_api_key() and sends it in the XBY-APIKEY header during a network request. While the file includes internal logging for request outcomes, it does not provide a user-facing warning, confirmation, or explanatory comment/docstring disclosing that sensitive credentials will be transmitted to an external service.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The docstring identifies the component as a different skill ('小笨羊高考Skill配置'), contradicting the manifest’s math-computation identity. While not directly exploitable on its own, this kind of identity mismatch is a strong deception indicator that makes other credential-handling behavior significantly more suspicious and can conceal unauthorized functionality from reviewers.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The file presents itself as a local math computation skill, but all operations are thin wrappers around call_api to a remote service. This creates a trust-boundary mismatch: user inputs and potentially sensitive data are transmitted off-skill without clear disclosure, and the actual computation behavior depends on an external backend not visible in this code.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The docstrings repeatedly claim computation is performed using local libraries such as SymPy, Polars, NumPy, and SciPy, but the implementation only forwards requests externally. This is misleading security-relevant behavior because reviewers and users may assume local-only processing and lower risk, when in reality data leaves the environment and backend behavior cannot be verified from this file.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The skill exposes broad network-backed processing for arbitrary expressions, arrays, matrices, and batch workflows via a single external API. Even if the intended domain is mathematics, this design enables exfiltration of all user-provided content to a remote service and delegates safety entirely to that backend, which increases attack surface beyond what a local math utility would imply.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
88% confidence
Finding

The skill name, description, workflow guidance, and operational instructions are written in Chinese throughout the file, with no indication that users may choose another language or locale. Under the policy, forcing a specific language without user opt-in is a natural-language policy concern unless the locale restriction is explicitly justified.

Content

No source excerpt is available for this finding.

Unpinned Dependencies

Low
Category
Supply Chain
Confidence
96% confidence
Finding

The dependency specifier requests>=2.31.0 is unpinned, so builds may resolve to different versions over time, reducing reproducibility and making it difficult to ensure vulnerable releases are excluded. In a network-capable service, this increases supply-chain risk because a future install could pull a newly vulnerable or incompatible version without code changes.

Content

Scanner excerpt · requirements.txt (reported line 1)May include surrounding context.

text
requests>=2.31.0
pydantic>=2.7.0
pydantic-settings>=2.2.0
python-dotenv>=1.0.1