Back to skill

Security audit

Segment Anything

Security checks for vulnerabilities and agentic risk

Overview

This image-segmentation skill does what it claims, but it can automatically install mutable remote code and download large unverified model files during use.

Install only if you are comfortable with the skill changing the Python environment and downloading large model files from the network. Prefer preparing dependencies yourself from pinned, trusted versions and using a local checkpoint whose source you trust before running it.

Vulnerability Patterns
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
  • 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
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (2)

T03 · Remote Payload Retrieval and Execution

Error
Location
scripts/segment.py:39
Finding
Runtime Retrieval and Execution of an Unpinned Remote Dependency<![CDATA[ ## Vulnerability Details **File Location**: `scripts/segment.py`, lines 39-44 **Vulnerability Type**: Runtime installation of mutable remote code **Risk Level**: High ### Vulnerable Code ```python try: from segment_anything import SamPredictor, sam_model_registry except ImportError: print("正在安装 segment_anything...") os.system("pip install git+https://github.com/facebookresearch/segment-anything.git -q") from segment_anything import SamPredictor, sam_model_registry ``` ### Technical Analysis If `segment_anything` cannot be imported, the script invokes `pip` through a shell and installs the current contents of a remote Git repository. The dependency is not pinned to an immutable commit or verified against a cryptographic digest. Consequently, the code executed by the Skill can change after the Skill itself has been reviewed. Installation may execute package build logic, and the newly installed package is immediately imported in the same process. Although the repository is the documented upstream project, relying on its mutable default revision creates a remote payload execution and supply-chain boundary. The command is currently static, so no direct shell injection through user-controlled arguments was identified. However, `os.system` also ignores the installation command's exit status and relies on the environment's `pip` executable resolution. ### Attack Path 1. The Skill runs in an environment where `segment_anything` is not installed or cannot be imported. 2. The `ImportError` handler executes the `pip install` command. 3. `pip` retrieves the then-current source from the remote Git repository. 4. If the upstream repository, a maintainer account, the dependency chain, or the environment's tool resolution has been compromised, attacker-controlled package installation logic executes. 5. The script immediately imports the installed package, executing its module initialization code. 6. The payload runs with the same operating-sys ...[truncated 675 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove automatic package installation from application runtime. 2. Declare `segment-anything` as an installation-time dependency and require the environment to be prepared before the script starts. 3. Pin the package to an audited release or immutable Git commit rather than a mutable repository revision. 4. Use a lock file and cryptographic hashes for all transitive dependencies where supported. 5. On import failure, terminate with a clear error message instead of downloading and executing code. 6. If installation automation is unavoidable, invoke the interpreter explicitly without a shell, validate the exit status, and use an immutable source: ```python import subprocess import sys subprocess.run( [ sys.executable, "-m", "pip", "install", "git+https://github.com/facebookresearch/segment-anything.git@<audited-commit>", ], check=True, ) ``` This still carries installation-time risk and should be combined with commit pinning, dependency locking, and controlled deployment. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/segment.py:24
Finding
Downloaded Model Checkpoints Are Loaded Without Integrity Verification<![CDATA[ ## Vulnerability Details **File Location**: `scripts/segment.py`, lines 24-31 and 46-49 **Vulnerability Type**: Unverified model download and unsafe trust of cached checkpoint files **Risk Level**: Medium ### Vulnerable Code ```python path = os.path.join(cache_dir, filename) if not os.path.exists(path): size_mb = dict(vit_b=375, vit_l=1250, vit_h=2560)[model_type] print(f"正在下载 SAM {model_type} 权重文件(约 {size_mb}MB)...") urllib.request.urlretrieve(url, path, reporthook=lambda b, bs, t: print(f"\r {min(b*bs,t)*100//t}%", end="", flush=True) if t > 0 else None) print() return path ``` The returned file is subsequently passed to the model loader: ```python ckpt = ensure_checkpoint(model_type, checkpoint) sam = sam_model_registry[model_type](checkpoint=ckpt) ``` ### Technical Analysis The script downloads model checkpoints over HTTPS but does not verify a pinned checksum or digital signature before loading them. It also trusts any existing file at the expected cache path solely because that path exists. HTTPS protects transport under normal conditions, but it does not provide artifact-level assurance against upstream compromise, incorrectly served content, compromised trust infrastructure, or local cache substitution. The file is written directly to its final cache path rather than downloaded to a temporary file and atomically promoted after verification. An interrupted download can therefore also leave a partial file that later executions treat as valid. SAM checkpoint loading is delegated to the installed model and PyTorch stack. Model checkpoint formats have historically involved deserialization behavior that can be security-sensitive. Whether arbitrary code execution is possible depends on the exact dependency versions and loading implementation, but an attacker who can replace the checkpoint can at minimum cause model corruption, process failure, excessive resource consumption, or incorrect segmentation results. ### Attack Pat ...[truncated 1331 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Publish and pin an approved SHA-256 digest for each checkpoint. 2. Download into a newly created temporary file in the cache directory. 3. Calculate the complete file's digest and compare it using a constant-time comparison. 4. Reject and delete any file whose digest does not match. 5. Atomically rename the verified temporary file to the final checkpoint path. 6. Verify existing cached files on every use rather than relying on filename existence. 7. Use restrictive cache permissions and reject unsafe file types or symbolic links where appropriate. 8. Prefer a non-executable tensor serialization format, such as `safetensors`, if supported by the model stack. 9. Use safe or weights-only loading options supported by the pinned PyTorch version. 10. Report interrupted or failed downloads without leaving a file at the trusted final path. A hardened flow should follow: ```text download to temporary file ↓ verify pinned SHA-256 digest ↓ load with the safest supported deserialization mode ↓ atomically move to the final cache path ``` ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • YARA SignaturesMalware Match, Webshell Match, Cryptominer Match
Findings (12)

YARA rule 'agent_skill_remote_bootstrap_execution': Remote script or code download followed by execution/bootstrap installation [agent_skills]

High
Category
YARA Match
Content
��一个 PNG)
python3 scripts/segment.py photo.jpg ./elements/ --all

# 使用更密集的网格捕获小物体
python3 scripts/segment.py photo.jpg ./elements/ --all --grid 32

# 使用本地权重文件
python3 scripts/segment.py photo.jpg output.png --checkpoint /path/to/sam_vit_h_4b8939.pth
```

## 依赖安装

`segment_anything` 首次运行时自动安装,也可手动安装:

```bash
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install pillow numpy torch torchvision
```

## 工作流程

1. 用户提供图像路径
2. 询问是否需要提示点(主体偏离中心时)
3. 运行脚本;权重文件首次使用时自动下载至 `~/.cache/sam/`
4. 输出透明背景的 PNG 文件

## 模型选择

| 模型 | 大小 | 速度 | 质量 |
|---|---|---|---|
| `vit_b` | ~375 MB | 最快 | 良好 |
| `vit_l` | ~1.25 GB | 中等 | 较好 |
| `vit_h` | ~2.5 GB | 较慢 | 最佳 |

有 GPU 时自动使用 CUDA 加速。
Confidence
88% confidence
Finding
The documentation instructs users to install code directly from a GitHub repository using `pip install git+https://...`, which pulls and executes unpinned remote package content at install time. Combined with the stated automatic installation behavior, this introduces supply-chain risk: a compromised upstream repo, dependency, or transient branch state could result in arbitrary code execution in the agent environment.

Context-Inappropriate Capability

High
Confidence
97% confidence
Finding
Automatically installing a package directly from a remote Git repository at runtime is disproportionate to the advertised image-segmentation task and materially expands the trust boundary. It enables execution of unreviewed third-party code on the user's system without meaningful disclosure or consent.

os.system() or os exec-family call

High
Category
Dangerous Code Execution
Content
from segment_anything import SamPredictor, sam_model_registry
    except ImportError:
        print("正在安装 segment_anything...")
        os.system("pip install git+https://github.com/facebookresearch/segment-anything.git -q")
        from segment_anything import SamPredictor, sam_model_registry

    import torch
Confidence
98% confidence
Finding
The script invokes a shell command to install and execute code from a remote GitHub repository at runtime. This creates a software supply-chain risk because unpinned remote code is fetched and installed without integrity verification, user approval, or isolation, allowing arbitrary code execution if the source or network path is compromised.

YARA rule 'agent_skill_remote_bootstrap_execution': Remote script or code download followed by execution/bootstrap installation [agent_skills]

High
Category
YARA Match
Content
print(f"\r  {min(b*bs,t)*100//t}%", end="", flush=True) if t > 0 else None)
        print()
    return path


def _load_sam(model_type, checkpoint):
    """加载 SAM 模型,首次运行时自动安装 segment_anything。"""
    try:
        from segment_anything import SamPredictor, sam_model_registry
    except ImportError:
        print("正在安装 segment_anything...")
        os.system("pip install git+https://github.com/facebookresearch/segment-anything.git -q")
        from segment_anything import SamPredictor, sam_model_registry

    import torch

    ckpt = ensure_checkpoint(model_type, checkpoint)
    sam = sam_model_registry[model_type](checkpoint=ckpt)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    sam.to(device)
    print(f"模型已加载至 {device}")
    return SamPredictor(sam)


def segment(image_path, output_path, checkpoint=None, model_type="vit_b", points=None):
    """单目标分割:使用一个或多个提示点提取前景主体。"""
Confidence
98% confidence
Finding
The YARA pattern is correctly triggered because the script bootstraps remote code installation from GitHub and then imports it for execution in the same runtime flow. In the context of an agent skill, this is especially dangerous because a seemingly simple local image tool gains the ability to fetch and run arbitrary external code on demand.

Lp3

Medium
Category
MCP Least Privilege
Confidence
90% confidence
Finding
The skill clearly documents shell execution (`python3 scripts/segment.py`) and network activity through automatic model/download installation, but it declares no tool scope or permissions. This creates an authorization and transparency gap: an agent may invoke shell and network-capable behavior without an explicit policy boundary, increasing the risk of unintended downloads, installs, or file writes during use.

Natural-Language Policy Violations

Medium
Confidence
96% confidence
Finding
The natural-language instructions and usage guidance are presented only in Chinese, which effectively forces a specific language for users. The file does not offer an alternative language option or explain that the skill is intentionally limited to a Chinese-speaking audience.

Context-Inappropriate Capability

Medium
Confidence
88% confidence
Finding
The script silently performs network access to download very large model checkpoints when they are missing. While expected for ML tooling, undisclosed automatic downloads can surprise users, bypass offline expectations, and expose them to integrity and availability risks if the remote host is tampered with or unavailable.

Missing User Warnings

Medium
Confidence
92% confidence
Finding
The script automatically downloads large model files from the network without prominently disclosing that behavior in the CLI interface. In a local image-processing skill, hidden network activity increases operational and supply-chain risk, especially where users expect purely offline processing.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The script auto-installs software via a shell command after only printing a status message, with no confirmation or safe mode. This normalizes unexpected environmental modification and can lead to arbitrary code execution or system compromise through dependency hijacking or a compromised upstream repository.

Description-Behavior Mismatch

Medium
Confidence
92% confidence
Finding
Manifest 将技能定位为“去除图像背景,将前景主体提取为透明 PNG”,重点是单个前景主体的背景去除。这里的 `segment_all` 明确执行全元素分割,并把多个独立对象分别保存为单独 PNG,这超出了“提取前景主体”这一较窄描述范围。

Missing User Warnings

Low
Confidence
90% confidence
Finding
This markdown file describes that omitting `--checkpoint` causes an automatic download, but it does not present this as a user warning about network activity and local disk impact. Because the skill downloads a large external artifact and stores it under the user's home cache, a clearer warning about network use and filesystem changes would improve user disclosure.

Natural-Language Policy Violations

Low
Confidence
90% confidence
Finding
User-facing docstrings, status messages, and CLI help are written exclusively in Chinese, which imposes a language choice on users without opt-in. The policy allows locale constraints when explicitly justified, but this file does not document such a justification or provide alternatives.

Static analysis

No suspicious patterns detected.