- name
- supply-chain-sentinel
- description
- Security scanner for supply chain attacks, malicious dependencies, prompt injection, and suspicious code patterns. Use this skill whenever the user asks to audit a project, scan for malicious packages, check dependencies for threats, look for prompt injection, detect typosquatting, review supply chain security, or investigate suspicious code. Also trigger for: "check if this is safe", "scan my deps", "audit my project", "is there anything malicious", "security review", "check for backdoors", "supply chain attack", "dependency confusion", "malicious npm/pip/cargo package". Works with Python, Node.js, Go, Rust, Java/Maven/Gradle, and mixed projects. ALWAYS use this skill when security scanning of any kind is requested.
# Supply Chain Sentinel
Scanner portátil de segurança para detectar ataques de supply chain, dependências maliciosas,
injeção de prompt, código obfuscado e padrões suspeitos em projetos de software.
## Fluxo de Execução
1. **Leia este arquivo completo** antes de começar
2. **Execute o scanner Python** via `scripts/scanner.py`
3. **Complemente com análise manual** dos achados de alta severidade
4. **Gere o relatório final** em Markdown
---
## Passo 1 — Localizar o Projeto
Se o usuário não especificou o path:
```bash
# Tenta caminhos comuns
ls /mnt/user-data/uploads/ 2>/dev/null || true
ls ~/project/ 2>/dev/null || true
pwd
```
Pergunte ao usuário se não encontrar. O scanner aceita qualquer diretório raiz.
---
## Passo 2 — Executar o Scanner
Copie o script para um local gravável e execute:
```bash
cp /mnt/skills/*/supply-chain-sentinel/scripts/scanner.py /tmp/sentinel_scanner.py \
|| cp "$(dirname "$0")/scripts/scanner.py" /tmp/sentinel_scanner.py
python3 /tmp/sentinel_scanner.py --path <PROJECT_DIR> --output /tmp/sentinel_report.json
```
Se o script não estiver acessível via path relativo, **escreva-o em disco** usando
o conteúdo da seção `## Scanner Script` abaixo, salve em `/tmp/sentinel_scanner.py`
e execute normalmente.
---
## Passo 3 — Análise Manual Complementar
Após o scanner, faça buscas direcionadas nos achados críticos:
### 3a. Verificar setup.py / pyproject.toml suspeitos
```bash
# Chamadas de rede no setup
grep -rn "urllib\|requests\|socket\|http" <PROJECT_DIR>/setup.py \
<PROJECT_DIR>/pyproject.toml 2>/dev/null
# Exec/eval no install
grep -rn "exec\|eval\|compile\|__import__" <PROJECT_DIR>/setup.py 2>/dev/null
```
### 3b. Strings Base64 / Ofuscadas
```bash
grep -rEn "base64\.(b64decode|decodebytes)|\\\\x[0-9a-f]{2}|eval\(.*decode" \
<PROJECT_DIR> --include="*.py" --include="*.js" --include="*.ts" 2>/dev/null | head -50
```
### 3c. Prompt Injection em arquivos de config/prompt
```bash
grep -rniP "(ignore previous|disregard|you are now|forget your|override instructions|\
act as if|new system prompt|jailbreak|\\[INST\\]|<\|system\|>)" \
<PROJECT_DIR> --include="*.txt" --include="*.md" --include="*.json" \
--include="*.yaml" --include="*.yml" --include="*.toml" 2>/dev/null
```
### 3d. Caracteres Invisíveis / Unicode Suspeito
```bash
# Zero-width chars e bidi override (CVE-2021-42574 "Trojan Source")
grep -rPn "[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]" \
<PROJECT_DIR> --include="*.py" --include="*.js" --include="*.ts" 2>/dev/null | head -30
```
### 3e. Exfiltração de Credenciais / Env Vars
```bash
grep -rEn "(os\.environ|getenv|AWS_|GITHUB_TOKEN|api.key|password|secret)" \
<PROJECT_DIR> --include="*.py" --include="*.js" 2>/dev/null \
| grep -v "test\|spec\|example\|\.env\.example" | head -40
```
---
## Passo 4 — Consolidar e Gerar Relatório
Leia o JSON gerado pelo scanner e os resultados manuais, depois produza um relatório Markdown estruturado:
```
# 🛡️ Security Audit Report — Supply Chain Sentinel
**Projeto:** <nome>
**Data:** <data>
**Severidade Geral:** 🔴 CRÍTICA / 🟠 ALTA / 🟡 MÉDIA / 🟢 BAIXA
---
## Resumo Executivo
<2-3 parágrafos>
## Achados por Categoria
### 🔴 Críticos
### 🟠 Altos
### 🟡 Médios
### 🟢 Informativos
## Dependências Suspeitas
<tabela: pacote | versão | risco | motivo>
## Recomendações
<lista priorizada>
## Metodologia
```
---
## Scanner Script
Se o script não estiver acessível via filesystem, **crie-o** com este conteúdo em `/tmp/sentinel_scanner.py`:
```python
#!/usr/bin/env python3
"""
Supply Chain Sentinel — scanner.py
Portable security scanner for supply chain attacks, malicious deps, prompt injection.
"""
import os, sys, re, json, hashlib, argparse, ast
from pathlib import Path
from datetime import datetime
from typing import Any
# ── Typosquatting: common targets (PyPI top 100 + security-relevant) ──────────
PYPI_POPULAR = {
"requests","numpy","pandas","flask","django","fastapi","boto3","pydantic",
"sqlalchemy","celery","redis","pymongo","psycopg2","cryptography","paramiko",
"httpx","aiohttp","click","typer","rich","setuptools","pip","wheel","twine",
"pytest","black","mypy","flake8","pylint","isort","poetry","virtualenv",
"pillow","matplotlib","scipy","sklearn","torch","tensorflow","keras",
"openai","anthropic","langchain","transformers","huggingface-hub",
"ansible","fabric","invoke","nox","tox","coverage","hypothesis",
"uvicorn","gunicorn","starlette","pydantic-settings","alembic",
}
NPM_POPULAR = {
"react","vue","angular","express","lodash","axios","webpack","babel",
"typescript","jest","eslint","prettier","next","nuxt","vite","rollup",
"moment","dayjs","chalk","commander","dotenv","cors","helmet","jsonwebtoken",
"bcrypt","mongoose","sequelize","prisma","graphql","apollo","socket.io",
"nodemailer","multer","sharp","uuid","crypto-js","node-fetch","cross-fetch",
}
# ── Suspicious code patterns ──────────────────────────────────────────────────
SUSPICIOUS_PATTERNS = [
# Obfuscation / dynamic execution
(r'eval\s*\(\s*(base64|__import__|bytes|chr\()', "CRITICAL", "eval com payload codificado"),
(r'exec\s*\(\s*(base64|__import__|compile)', "CRITICAL", "exec com payload suspeito"),
(r'__import__\s*\(\s*["\']os["\'].*system', "CRITICAL", "import dinâmico + os.system"),
(r'base64\.b64decode\s*\([^)]{20,}\)', "HIGH", "blob base64 decodificado em runtime"),
(r'\\x[0-9a-fA-F]{2}(\\x[0-9a-fA-F]{2}){8,}', "HIGH", "sequência hex longa (shellcode?)"),
(r'chr\(\d+\)\s*\+\s*chr\(\d+\)', "MEDIUM", "string montada via chr() (ofuscação)"),
# Network exfiltration
(r'(requests|urllib|httpx|aiohttp)\.(get|post)\s*\(["\']https?://(?!localhost|127\.0\.0\.1)',
"HIGH", "chamada HTTP para host externo"),
(r'socket\.connect\s*\(\s*\(["\'][0-9]{1,3}\.[0-9]{1,3}', "CRITICAL", "conexão socket direta a IP"),
(r'dns\.(resolver|query)|dnslib', "MEDIUM", "uso de DNS (possível tunneling)"),
# Credential harvesting
(r'os\.environ\.get\s*\(\s*["\'](?:AWS|GITHUB|TOKEN|SECRET|PASSWORD|API_KEY)',
"HIGH", "leitura de variável de ambiente sensível"),
(r'open\s*\(\s*["\'][^"\']*\.ssh[/\\\\]', "CRITICAL", "acesso a chaves SSH"),
(r'open\s*\(\s*["\'][^"\']*(?:\.aws|credentials|\.netrc)["\']', "CRITICAL", "acesso a arquivo de credenciais"),
# Prompt injection markers
(r'(?i)(ignore\s+(?:previous|all)\s+instructions?|disregard\s+(?:prior|previous)|'
r'you\s+are\s+now\s+(?:a|an)|forget\s+(?:your|all)\s+(?:previous|prior)|'
r'new\s+system\s+prompt|override\s+(?:your\s+)?instructions)',
"HIGH", "prompt injection marker"),
(r'(?i)(\[INST\]|<\|system\|>|<\|im_start\|>|<SYS>|\{\{.*role.*system.*\}\})',
"HIGH", "template de prompt injetado"),
# Reverse shell / RCE
(r'subprocess\.(Popen|run|call)\s*\(\s*\[?\s*["\'](?:bash|sh|cmd|powershell)',
"CRITICAL", "execução de shell via subprocess"),
(r'os\.system\s*\(\s*["\'][^"\']*(?:curl|wget|nc |netcat)',
"CRITICAL", "download/conexão via shell"),
# Persistence
(r'(?:crontab|/etc/cron|\.bashrc|\.zshrc|\.profile)\s*["\'].*write',
"HIGH", "escrita em arquivo de inicialização/cron"),
(r'HKEY_|winreg|Registry', "MEDIUM", "acesso ao registro do Windows"),
]
# ── Prompt injection in non-code files ───────────────────────────────────────
PROMPT_INJECTION_PATTERNS = [
r'(?i)ignore\s+(previous|all|prior)\s+instructions?',
r'(?i)disregard\s+(prior|previous|above)',
r'(?i)you\s+are\s+now\s+(a|an)\s+\w+',
r'(?i)forget\s+(your|all)',
r'(?i)new\s+system\s+prompt',
r'(?i)override\s+instructions',
r'(?i)act\s+as\s+(if\s+)?you\s+(are|were)',
r'(?i)\[INST\]|\[\/INST\]',
r'<\|system\|>|<\|im_start\|>|<\|im_end\|>',
r'(?i)jailbreak',
r'(?i)do\s+anything\s+now\s*\(dan\)',
]
# ── Unicode / invisible char ranges ──────────────────────────────────────────
INVISIBLE_CHARS = re.compile(
r'[\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff\u00ad]'
)
在 GitHub 查看