Back to skill

Security audit

Box-KVCache

Security checks for vulnerabilities and agentic risk

Overview

The skill mostly matches its local Ollama compression purpose, but it includes an unsafe compressed-file loader and automatic local process launching that merit review before installation.

Review the Python scripts before installing, use an isolated virtual environment with pinned dependencies, and do not load compressed .npz/.npy files from untrusted sources unless allow_pickle is removed. Expect the launch helper to run local Ollama commands and potentially leave an Ollama service running.

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

Warning
Location
scripts/lowrank_compress.py:99
Finding
Unsafe NumPy Archive Deserialization with Pickle Enabled<![CDATA[ ## Vulnerability Details **File Location**: `scripts/lowrank_compress.py`, lines 99-104 **Vulnerability Type**: Unsafe deserialization **Risk Level**: Medium ### Vulnerable Code ```python def load_compressed(self, filepath: str): """从文件加载压缩数据""" data = np.load(filepath, allow_pickle=True) self.U = data["U"] self.S = data["S"] self.Vt = data["Vt"] self.original_shape = tuple(data["original_shape"]) print(f"已加载压缩数据,形状: U={self.U.shape}, S={self.S.shape}, Vt={self.Vt.shape}") ``` ### Technical Analysis The method loads a caller-supplied NumPy archive using `allow_pickle=True`. This setting permits object arrays in `.npy` or `.npz` files to be reconstructed through Python's pickle mechanism. Pickle is not a safe data format for untrusted input. A crafted object can define a reduction operation that invokes arbitrary Python functions during deserialization. In an `.npz` archive, loading is generally deferred until an archive member such as `data["U"]` is accessed. Therefore, the subsequent array accesses can trigger the malicious pickle payload. The archive format used by `save_compressed()` contains only numeric arrays and does not require pickle support. Enabling it unnecessarily expands the trust boundary from numeric data parsing to arbitrary Python object reconstruction. ### Attack Path 1. An attacker creates a malicious `.npz` archive containing an object array with a crafted pickle reducer. 2. The attacker convinces a user or integrating application to treat that archive as compressed KV-cache data, or replaces an existing archive in a writable location. 3. The application calls `KVCacheLowRank.load_compressed()` with the attacker's file path. 4. `np.load()` accepts the archive because `allow_pickle=True` is enabled. 5. Accessing an object-backed member such as `data["U"]` causes the embedded pickle object to be deserialized. 6. The attacker's reducer executes arbitrary Python code under the identity of the proce ...[truncated 694 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Disable pickle support because the expected archive members are numeric arrays: ```python with np.load(filepath, allow_pickle=False) as data: required = {"U", "S", "Vt", "original_shape"} if not required.issubset(data.files): raise ValueError("Compressed archive is missing required fields") U = data["U"] S = data["S"] Vt = data["Vt"] original_shape = data["original_shape"] ``` 2. Reject object dtypes explicitly: ```python for name, array in { "U": U, "S": S, "Vt": Vt, "original_shape": original_shape, }.items(): if array.dtype.hasobject: raise ValueError(f"Object dtype is not permitted for {name}") ``` 3. Validate that arrays have the expected dimensions, compatible shapes, finite values, and reasonable element counts before retaining them. 4. Enforce a maximum input file size and maximum decompressed array dimensions to reduce memory-exhaustion risk. 5. If archives cross a trust boundary, distribute a cryptographic hash or signature and verify it before loading. 6. Use a context manager for `np.load()` so the underlying archive is closed reliably. ]]>

T08 · Insecure Dependencies

Note
Location
SKILL.md:30
Finding
Unpinned Third-Party Dependency Installation<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md`, lines 30-34; `README.md`, lines 70-74 **Vulnerability Type**: Unpinned supply-chain dependencies **Risk Level**: Low ### Vulnerable Code `SKILL.md`: ```bash pip install numpy scipy ``` `README.md`: ```bash pip install numpy scipy ``` ### Technical Analysis The installation instructions request mutable package names without specifying versions, hashes, a lock file, or an expected package index. As a result, installation behavior depends on the user's current pip configuration and whichever package releases are available at installation time. Although `numpy` and `scipy` are legitimate package names, the instructions do not provide reproducible dependency resolution or artifact integrity verification. A compromised package repository, compromised future release, malicious package served through an attacker-controlled pip index, or unsafe local pip configuration could cause unintended code to run during package installation. No malicious dependency is present in the audited project, and no typosquatted package name was identified. This finding concerns the absence of supply-chain hardening in the documented installation process. ### Attack Path 1. A user follows the documented `pip install numpy scipy` command. 2. Pip selects its repository according to the user's global configuration, environment variables, or command defaults. 3. If the selected repository or dependency artifact is compromised, pip downloads the malicious or altered package. 4. Package build or installation logic executes in the user's Python environment. 5. The malicious package obtains the same privileges as the user running pip and remains available to the skill whenever imported. This path requires compromise or manipulation of the dependency source, package release, network trust configuration, or local pip configuration; the project itself does not perform that manipulation. ### Impact Assessment A compromised ...[truncated 651 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Provide a reviewed dependency file with tested version constraints, for example: ```text numpy==<reviewed-version> scipy==<reviewed-version> ``` 2. For stronger artifact integrity, generate and publish a lock file containing cryptographic hashes, then require hash verification: ```bash python -m pip install --require-hashes -r requirements.lock ``` 3. Document installation inside an isolated virtual environment rather than the system Python environment. 4. Use `python -m pip` to ensure dependencies are installed into the interpreter that will run the scripts. 5. Document the intended trusted package index and advise users to review pip configuration and relevant environment variables before installation. 6. Add automated dependency update and vulnerability scanning so pinned versions can be reviewed and updated safely rather than remaining stale. ]]>
Vulnerability Patterns
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Tool MisuseTool Parameter Abuse, Chaining Abuse, Unsafe Defaults
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • Taint TrackingDirect Taint Flow, Variable-Mediated Taint Flow, Credential Exfiltration Chain
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
Findings (20)

Tainted flow: 'user_input' from input (line 114, user input) → subprocess.run (code execution)

Critical
Category
Data Flow
Content
break
            
            # 调用 ollama
            result = subprocess.run(
                ["ollama", "run", model, user_input],
                capture_output=True, text=True, timeout=120
            )
Confidence
90% confidence
Finding
External input (network, user) flows to a code execution sink. This enables remote code execution or command injection.

Tool Parameter Abuse

High
Category
Tool Misuse
Content
def run_cmd(cmd, timeout=5):
    """执行命令并返回输出"""
    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True,
            text=True, timeout=timeout
        )
Confidence
95% confidence
Finding
Using shell=True causes the shell to interpret the command string, which is a classic command-injection sink. Although this script currently builds command strings from fixed literals rather than CLI arguments, the utility function normalizes an unsafe pattern across the codebase and skill context, making later misuse likely and potentially leading to arbitrary OS command execution.

External Model or Provider Selection

High
Category
Excessive Agency
Content
下一步:
  1. 安装 Ollama: https://ollama.com
  2. 下载模型: ollama pull llama3
  3. 使用压缩启动: python scripts/launch_compressed.py --model llama3 --compress
        """)
Confidence
90% confidence
Finding
Skill selects an external model or provider that may use a different account or billing plan than the operator expects. Undisclosed model switches can cause unexpected cost or quota consumption.

Tool Parameter Abuse

High
Category
Tool Misuse
Content
def check_ollama_running() -> bool:
    """检查 Ollama 是否在运行"""
    result = subprocess.run(
        "tasklist | findstr ollama",
        shell=True, capture_output=True, text=True
    )
Confidence
94% confidence
Finding
Using shell=True for a simple status check is an avoidable tool-parameter abuse pattern because it grants shell interpretation where none is needed. In an agent or automation context, even constant shell commands are more dangerous because future refactors or environmental influence can turn a harmless check into command execution exposure.

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
The skill documentation is written entirely in Chinese, including headings, usage guidance, warnings, and examples, with no indication that users may choose another language or that the skill is intended only for a Chinese-speaking context. This can violate language/locale policy when a skill imposes a specific language without user opt-in or documented justification.

Natural-Language Policy Violations

Medium
Confidence
88% confidence
Finding
The entire skill description is written in Chinese, with no indication that other languages are supported or that the locale restriction is intentional and justified. Under the language/locale policy, forcing a specific language without user opt-in can be a natural-language policy violation.

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
This code file contains natural-language strings that force a specific language/locale for all users, including the module docstring and runtime messages. Under the policy, locale-specific language is only acceptable when users can opt in or when the restriction is explicitly justified, neither of which is present here.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
def run_cmd(cmd, timeout=5):
    """执行命令并返回输出"""
    try:
        result = subprocess.run(
            cmd, shell=True, capture_output=True,
            text=True, timeout=timeout
        )
Confidence
93% confidence
Finding
The helper executes arbitrary shell command strings via subprocess.run(..., shell=True). In this file the current callers use hardcoded commands, so immediate exploitability is limited, but the wrapper is generic and unsafe by design: any future or indirect use with user-controlled input would enable command injection and arbitrary command execution.

Natural-Language Policy Violations

Medium
Confidence
95% confidence
Finding
This Python file contains natural-language documentation and user-facing output entirely in Chinese, beginning with the module docstring. Under the policy, forcing a specific language without user opt-in is a locale/language policy violation unless the tool is clearly documented as region-specific, which is not stated here.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
def check_ollama_running() -> bool:
    """检查 Ollama 是否在运行"""
    result = subprocess.run(
        "tasklist | findstr ollama",
        shell=True, capture_output=True, text=True
    )
Confidence
95% confidence
Finding
This uses shell=True to execute a shell pipeline, which unnecessarily invokes the Windows shell and increases command-execution risk. Although the command string is constant and not directly user-controlled here, shell invocation expands the attack surface and can be abused via environment manipulation, shell behavior, or future code changes that introduce untrusted input.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
try:
        # Windows: 启动 ollama serve
        subprocess.Popen(
            ["ollama", "serve"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
break
            
            # 调用 ollama
            result = subprocess.run(
                ["ollama", "run", model, user_input],
                capture_output=True, text=True, timeout=120
            )
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Natural-Language Policy Violations

Medium
Confidence
94% confidence
Finding
The argparse description, help strings, and other runtime messages are all written in Chinese, with no option for users to choose another language. Because this is user-facing natural language in a general-purpose script, it constitutes a language policy issue under the stated rules.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
# 列出模型
    if args.list_models:
        print("已下载的模型:")
        subprocess.run(["ollama", "list"])
        return
    
    # 启动 Ollama
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
else:
        # 直接运行(单次查询)
        try:
            result = subprocess.run(cmd, timeout=120)
            sys.exit(result.returncode)
        except Exception as e:
            print(f"运行出错: {e}")
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Intent-Code Divergence

Medium
Confidence
93% confidence
Finding
This finding describes the same unsafe behavior in the file-loading path: the method appears to load compressed numeric data, but it enables pickle-capable deserialization. That mismatch is dangerous because callers may reasonably assume the routine is safe for ordinary data files when it can actually deserialize attacker-controlled objects.

Insecure deserialization: numpy.load(allow_pickle=True)

Medium
Category
Dangerous Code Execution
Content
def load_compressed(self, filepath: str):
        """从文件加载压缩数据"""
        data = np.load(filepath, allow_pickle=True)
        self.U = data["U"]
        self.S = data["S"]
        self.Vt = data["Vt"]
Confidence
98% confidence
Finding
The loader calls numpy.load with allow_pickle=True on a user-supplied filepath, which permits deserialization of pickled object arrays. If an attacker can supply or replace the .npz/.npy file, loading it may execute arbitrary code during deserialization, making this a genuine insecure deserialization issue.

Missing User Warnings

Low
Confidence
84% confidence
Finding
The markdown states that the skill can '一键启动压缩模式' by changing Ollama startup parameters, but it does not warn the user about possible configuration impact or that local runtime behavior may be altered. For a markdown file, configuration-affecting behavior should be disclosed when it could affect system integrity or runtime setup.

Natural-Language Policy Violations

Low
Confidence
95% confidence
Finding
This is a natural-language policy issue because the file forces a specific language for its title and description, and the same pattern continues in user-visible strings throughout the script. There is no indication that the tool is region-specific or that users can opt into another language.

Natural-Language Policy Violations

Low
Confidence
90% confidence
Finding
The file’s user-facing description and instructional text are written entirely in Chinese, and the script’s visible CLI/demo output and error guidance continue that assumption. Under the policy, language constraints should either offer user choice or be clearly justified as region-specific; this file does neither.

Static analysis

No suspicious patterns detected.