Back to skill

Security audit

CDK最佳实践服务

Security checks for vulnerabilities and agentic risk

Overview

This skill looks like a CDK guidance tool, but it routes work through a third-party API while storing an API key in a local plaintext file and contains mismatched gaokao template remnants.

Review before installing. Only use this skill if you are comfortable giving a XiaoBenYang API key to it, having that key saved in a plaintext .env file in the working directory, and sending CDK/code-related inputs to the third-party API. Avoid using it on private repositories or sensitive infrastructure code unless the publisher narrows the scope, removes gaokao remnants, validates the API endpoint, and uses secure secret storage.

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

T09 · Insecure Skill Coding Practices

Error
Location
scripts/config.py:9
Finding

API Key and Tool Data Can Be Redirected to an Attacker-Controlled Endpoint

Content
View full analysis

Vulnerability Details

File Location: scripts/config.py:9-19; scripts/call_api.py:53-75
Vulnerability Type: Configurable credential-exfiltration destination
Risk Level: High

Vulnerable Code

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 = ""
python
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,
        "Content-Type": "application/json",
    }

    t0 = time.time()
    try:
        resp = self._session.post(
            url=url,
            headers=headers,
            data=json.dumps(params),
            timeout=settings.timeout_seconds,
        )

Technical Analysis

The SettingsConfigDict configuration permits environment variables beginning with XBY_GAOKAO_ to override settings fields. Consequently, XBY_GAOKAO_BASE_URL can replace the intended https://mcp.xiaobenyang.com destination.

The HTTP client constructs the request URL directly from this configurable value and sends the user's API key in the XBY-APIKEY header. It does not validate the URL scheme, compare the hostname against an allowlist, or otherwise bind credential transmission to the intended service. The session also supports both HTTP and HTTPS adapters, so a substituted plaintext HTTP des ...[truncated 1536 chars]

Remediation
View remediation

Remediation Suggestions

  1. Do not permit the credential destination to be overridden in production. Use a fixed constant for the official API origin.
  2. If endpoint configurability is required for development, enforce an explicit allowlist of trusted hostnames.
  3. Require HTTPS and reject URLs with any other scheme before constructing a request.
  4. Normalize and validate the hostname, port, user-information component, and resolved destination to prevent parser ambiguity and DNS-based bypasses.
  5. Disable cross-origin redirects for authenticated requests, or remove the XBY-APIKEY header whenever the origin changes.
  6. Separate development and production configuration so test endpoint support cannot silently operate with production credentials.
  7. Add automated tests confirming that HTTP URLs, unapproved hosts, embedded credentials, and cross-origin redirects are rejected.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/config.py:44
Finding

API Key Is Persisted in a Plaintext Working-Directory File Without Enforced Permissions

Content
View full analysis

Vulnerability Details

File Location: SKILL.md:15-20; scripts/config.py:44-63
Vulnerability Type: Insecure plaintext credential storage
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 Skill instructions additionally require this persistence behavior:

markdown
- 拿到用户提供的密钥后,调用 `scripts.config.set_api_key(api_key)` 保存,然后继续处理

Technical Analysis

The Skill requires the agent to collect an API key and persist it in a .env file in the current working directory. The credential is stored as unencrypted text. The code does not explicitly create the file with restrictive permissions, verify the ownership or permissions of an existing file, prevent symbolic-link traversal, or ensure that the selected working directory is private.

The use of a relative path also makes the storage location dependent on the process working directory. This increases the chance that the credential will be written into a shared directory, project checkout, packaged artifact, backup set, or source-control workspace.

Persistent storage is not necessary for an individual API call. Session-only credent ...[truncated 1221 chars]

Remediation
View remediation

Remediation Suggestions

  1. Prefer session-only credential use and avoid persistence unless the user explicitly opts in.
  2. Store persistent credentials in an operating-system keychain or dedicated secret-management service.
  3. If file storage is unavoidable, use a dedicated configuration directory and atomically create the credential file with mode 0600.
  4. Verify file ownership and permissions before reading or updating an existing credential file.
  5. Reject symbolic links and other unexpected file types.
  6. Resolve and validate the destination path instead of relying on the current working directory.
  7. Ensure .env is excluded from source control, packaging, backups, diagnostics, and support bundles.
  8. Document credential rotation and revocation procedures in case the file is exposed.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/tools.py:81
Finding

User-Supplied Source Code Is Transmitted to a Third Party Without an Explicit Data-Disclosure Control

Content
View full analysis

Vulnerability Details

File Location: scripts/tools.py:81-111; scripts/call_api.py:53-76; SKILL.md:102-115
Vulnerability Type: Unrestricted external disclosure of user-supplied source code
Risk Level: Medium

Vulnerable Code

python
def CheckCDKNagSuppressions(
    code: Optional[null] = None,
    file_path: Optional[null] = None
) -> Dict[str, Any]:
    """
    DEPRECATED: This tool is deprecated. Please use the AWS IaC MCP Server instead.

Check if CDK code contains Nag suppressions that require human review.

Scans TypeScript/JavaScript code for NagSuppressions usage to ensure security
suppressions receive proper human oversight and justification.

Args:
    ctx: MCP context
    code: CDK code to analyze (TypeScript/JavaScript)
    file_path: Path to a file containing CDK code to analyze

Returns:
    Analysis results with suppression details and security guidance
    """
    arguments = {
        "code": code,
        "file_path": file_path
    }
    
    return call_api("1777419060465667", "CheckCDKNagSuppressions", arguments)
python
headers = {
    "XBY-APIKEY": api_key,
    "func": tool_name,
    "mcpid": mcp_id,
    "Content-Type": "application/json",
}

resp = self._session.post(
    url=url,
    headers=headers,
    data=json.dumps(params),
    timeout=settings.timeout_seconds,
)

Technical Analysis

The suppression-analysis wrapper places the complete code value into the request parameter dictionary. The generic API client serializes that dictionary and transmits it to mcp.xiaobenyang.com.

CDK source code can contain proprietary architecture details, account identifiers, resource names, internal endpoints, embedded credentials, or other operationally sensitive information. The implementation performs no secret detection, redaction, payload minimization, or explicit confirmation before disclosure. The tool is also ma ...[truncated 1535 chars]

Remediation
View remediation

Remediation Suggestions

  1. Display a clear disclosure that source code will be sent to a third-party service and obtain explicit user consent before transmission.
  2. Prefer local static analysis for CDK Nag suppression detection, particularly because this remote tool is deprecated.
  3. Scan submitted text for API keys, access tokens, private keys, passwords, connection strings, and other likely secrets before sending it.
  4. Block transmission when high-confidence secrets are detected, or require a separate informed override.
  5. Minimize the payload to only the code fragments necessary for suppression analysis.
  6. Apply request-size limits and reject unexpected parameter types.
  7. Avoid transmitting local path strings unless they are required; replace them with sanitized logical filenames where possible.
  8. Document the third party's retention, logging, access-control, and deletion policies.
  9. Remove the deprecated tool if it is no longer required for the Skill's declared functionality.
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)

Tp2

High
Category
MCP Tool Poisoning
Confidence
85% confidence
Finding

Mixing characters from multiple Unicode scripts in a single identifier is a common technique to create visually ambiguous tool names.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
97% confidence
Finding

The skill's declared function is best-practice guidance, but it also exposes functionality for Bedrock schema generation, GenAI construct discovery, and Lambda layer documentation sourcing. Even when not overtly malicious, this broadening of scope increases attack surface and user confusion about what the skill may do with code, files, and remote resources.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
99% confidence
Finding

The skill's declared function is best-practice guidance, but it also exposes functionality for Bedrock schema generation, GenAI construct discovery, and Lambda layer documentation sourcing. Even when not overtly malicious, this broadening of scope increases attack surface and user confusion about what the skill may do with code, files, and remote resources.

Content

No source excerpt is available for this finding.

Tp4

High
Category
MCP Tool Poisoning
Confidence
93% confidence
Finding

The skill's declared function is best-practice guidance, but it also exposes functionality for Bedrock schema generation, GenAI construct discovery, and Lambda layer documentation sourcing. Even when not overtly malicious, this broadening of scope increases attack surface and user confusion about what the skill may do with code, files, and remote resources.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

The instructions contain gaokao-style school-search API examples and project structure inside a CDK guidance skill, indicating copied or mismatched operational guidance. This strongly suggests the skill may route user requests to unrelated tooling or services, undermining trust and increasing the chance of inappropriate data disclosure or unexpected actions.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

High
Category
Not specified by scanner
Confidence
98% confidence
Finding

该配置模块与声明的“AWS CDK最佳实践服务”用途明显不一致:类注释写的是“高考Skill”,并且代码围绕 xiaobenyang.com 的外部 MCP 服务与 XBY_APIKEY 凭证进行配置和持久化。这种功能/身份错配表明代码可能是从无关项目挪用,或在技能中夹带了与宣称目的无关的外部服务接入逻辑,会扩大供应链与凭证暴露风险。

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

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
93% confidence
Finding

model_post_init 中强制读取项目目录下 .env,并手工解析 XBY_APIKEY,绕过了更可控的标准配置流程。对于一个宣称提供 AWS CDK 最佳实践的技能,这种主动搜集本地凭证的行为与功能不匹配,增加了读取、误用或扩展到其他敏感条目的风险。

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
93% confidence
Finding

通过 Path('.env') 检查并读取本地 .env 文件,是对宿主工作目录敏感配置的直接访问。结合该技能上下文中的身份错配和无关外部服务配置,这种本地凭证读取更危险,因为它不是为了实现声明的 CDK 建议功能所必需。

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
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

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
99% confidence
Finding

代码将一个与技能声明目的无关的外部服务 API key 持久化到本地 .env,并同步放入进程环境变量。这会导致敏感凭证在磁盘长期驻留,增加被源码打包、日志、备份、权限配置错误或其他本地读取路径泄露的机会,且该凭证用途与 CDK 最佳实践服务无明显正当关系。

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
97% confidence
Finding

save_api_key_to_env 明确将 API key 写入 .env 文件,实现了敏感凭证的明文持久化。明文落盘会显著提高凭证通过版本控制误提交、文件权限错误、备份泄露、恶意本地读取或构建产物打包而泄露的概率,且该行为对 AWS CDK 指导类技能没有明显必要性。

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
90% confidence
Finding

The skill declares capabilities that imply environment access, file read/write, and network use, but it does not constrain them with an explicit tool scope such as allowed-tools or permissions. In a skill that also asks for API secrets and writes configuration, this lack of scoping increases the blast radius if the skill is misused or later modified.

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 name, description, and operational instructions are presented as mandatory Chinese-language content, but the document does not offer users any language or locale choice. Under the policy, forcing a specific language without user opt-in is a natural-language policy violation unless the constraint is clearly documented and justified as region-specific.

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 ask the user for an API key and persist it via local configuration. Collecting secrets through normal conversation and storing them locally without documented secure storage, masking, rotation, or scope controls creates a direct credential-handling risk.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The documented behavior extends beyond advice into local file transformation and schema generation from Lambda code. In context, that makes the skill more dangerous because a user expecting passive guidance may instead enable processing of local code artifacts, which can expose sensitive source content or modify outputs unexpectedly.

Content

No source excerpt is available for this finding.

Ssd 3

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The skill tells the model to display raw upstream response data directly to the user. Raw responses can contain sensitive fields, internal diagnostics, tokens, prompt-injection content, or untrusted markup/text that should be filtered or normalized before display.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

This file implements a generic outbound MCP/API client rather than logic narrowly scoped to AWS CDK best-practice guidance. In a skill advertised as a CDK advisory tool, a general-purpose remote invocation primitive expands capability beyond the stated purpose and can be repurposed to send arbitrary data to an external service, increasing data exfiltration and supply-chain risk.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

Allowing the caller to dynamically choose both tool_name and mcp_id gives external input control over which remote capability is invoked and which MCP instance receives the request. In the context of a supposedly specialized CDK guidance skill, this creates a confused-deputy style risk where the skill can be steered into invoking unintended remote functions or alternate backends using the stored API key.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

The code sends arbitrary params together with an API key to an external endpoint without any indication of consent, minimization, or filtering at this layer. If upstream callers pass secrets, source code, or environment-derived data, this client will forward them verbatim, creating a realistic exfiltration path that is more concerning because the skill description does not clearly imply broad third-party data transmission.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

类文档字符串将模块标识为“高考Skill配置”,与 manifest 声明的“AWS CDK最佳实践服务”相矛盾。虽然这本身不是直接代码执行漏洞,但它是强烈的完整性/来源异常信号,说明该文件可能来自无关项目,降低了对其处理凭证和访问外部服务逻辑的信任。

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The manifest describes a tool for AWS CDK best practices, infrastructure-as-code patterns, and CDK Nag security/compliance guidance. GenerateBedrockAgentSchema instead performs schema generation for Bedrock Agent Action Groups from Lambda code, which is a distinct code-generation workflow rather than CDK guidance or CDK Nag analysis.

Content

No source excerpt is available for this finding.

Unpinned Dependencies

Low
Category
Supply Chain
Confidence
93% confidence
Finding

The dependency specification uses a lower-bound constraint only, which allows installation of any newer requests release, including versions with breaking changes or newly introduced vulnerabilities. This weakens build reproducibility and makes it difficult to verify whether deployed environments are using a safe version.

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

Unverifiable Dependency: requests has 16 known advisory(ies) (CVE-2014-1830 (Exposure of Sensitive Information to an Unauthorized Actor in Requests); CVE-2024-47081 (Requests vulnerable to .netrc credentials leak via malicious URLs); CVE-2024-35195 (Requests `Session` object does not verify requests after making first request wi) +13 more), but the manifest does not pin a version, so it is unknown whether the installed release is affected

Low
Category
Supply Chain
Confidence
88% confidence
Finding

requests has known advisories, and because the manifest does not pin a specific version, it is impossible to determine whether deployment will use an affected release. The danger is not a proven vulnerable version in this file, but an unverifiable and potentially unsafe dependency resolution path.

Content

No source excerpt is available for this finding.

Unpinned Dependencies

Low
Category
Supply Chain
Confidence
92% confidence
Finding

Using pydantic with only a minimum version means future installs may resolve to unreviewed versions, reducing reproducibility and making security posture unverifiable. In security-sensitive tooling, uncontrolled upgrades can silently introduce vulnerable or incompatible releases.

Content

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

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

Static analysis

No suspicious patterns detected.