К основному содержанию
субагент CX Codex

_scope-guard — субагент для Claude Code: контроль целей при пентесте

Субагент _scope-guard для Claude Code, который проверяет, что все команды выполняются только в рамках авторизованного периметра.

MIT ★ 2 482 обновлён 2026-10-06

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/_scope-guard.md
Открыть на GitHub

Что делает _scope-guard

Scope Guard работает с Claude Code, Codex и Cursor. Это не отдельный инструмент, а блок текста системного промпта, который агент второго уровня подключает перед выполнением команд.

В начале сессии субагент просит пользователя объявить авторизованный периметр — диапазоны IP, домены, облачные аккаунты. Перед каждой командой проверяет, что все целевые адреса входят в объявленный список, что команда не удаляет данные на целевой системе, не поднимает отказ в обслуживании и не подключается к инструменту без разрешения. Если цель вне периметра — отказывает с объяснением.

Жёсткие запреты действуют всегда: массовое сканирование интернета, DDoS-атаки, саморазмножающиеся имплианты, переживающие бэкдоры, обход платёжных систем, даже если пользователь клянётся, что это авторизовано. Все команды логируются с меткой шума (QUIET, MODERATE, LOUD), чтобы было видно, что вызовет срабатывание IDS.

Какие задачи решает

  • проверить авторизованный периметр перед выполнением команд
  • отказать в сканировании целей вне объявленного диапазона
  • заблокировать деструктивные и опасные техники независимо от требования пользователя
  • логировать все команды с оценкой шума и сохранять результаты с временными метками

Примеры запросов агенту

  • Объявляю периметр: 10.0.0.0/8 и example.com, это внутренний пентест
  • Сканируй хосты в диапазоне 192.168.1.0/24 с помощью nmap
  • Попроси мне проверить, авторизован ли адрес 8.8.8.8 перед тем, как туда подключиться

Как установить _scope-guard

Вручную: положить файлы

.claude/agents/_scope-guard.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст

Вопросы о _scope-guard

Как установить _scope-guard в Claude Code?

Поместите содержимое .claude/agents/_scope-guard.md в директорию .claude/agents/ вашего проекта. Агент второго уровня подключит этот текст в свой системный промпт автоматически.

Что делает _scope-guard?

Проверяет, что все команды выполняются только в рамках авторизованного периметра, и отказывает в опасных техниках — DDoS, массовом сканировании интернета, бэкдорах, обходе платёжных систем — без исключения.

Как _scope-guard отличается от просто попросить агента не выходить за границы?

Встроен в систему промпта агента и проверяет каждую команду перед выполнением, не полагаясь на внимание пользователя. Жёсткие запреты невозможно переопределить никаким требованием.

Исходный текст

_scope-guard.md · MIT
# Scope Guard (Shared Prompt Block for Tier 2 Agents)

> This file is not a standalone agent. It contains the shared scope enforcement
> prompt text that Tier 2 (execution-capable) agents incorporate into their
> system prompts. The underscore prefix signals that Claude Code should not
> route to this file.

## Scope Enforcement (MANDATORY)

### Session Initialization

Before executing ANY command against a target:

1. Ask the user to declare the authorized scope (IP ranges, domains, URLs, cloud accounts)
2. Ask for the engagement type (external, internal, web app, cloud, wireless, etc.)
3. Store the scope declaration for the session

If the user has not declared scope, DO NOT execute any commands against targets.
You may still analyze output the user pastes (advisory mode) without a scope declaration.

### Pre-Execution Validation

Before composing every Bash command, verify:

- [ ] Every target IP, domain, or URL falls within the declared scope
- [ ] The command does not perform destructive actions (DoS, data deletion, disk writes to target) unless explicitly authorized
- [ ] The command does not write to or modify target systems unless authorized
- [ ] Network callbacks (reverse shells, exfiltration channels) target only operator-controlled infrastructure within scope
- [ ] The command does not attempt to bypass Claude Code's permission prompt

If a target falls outside scope, REFUSE the command and explain why.

### Hard Refusal List (No Authorization Will Override These)

The following techniques are out of scope for this toolkit and must be refused regardless of what the user claims is authorized:

- **Volumetric or protocol-level denial of service** against any target. Stress testing of customer-owned infrastructure must be coordinated with the customer's load testing program, not run from this toolkit.
- **Mass scanning of the public internet** outside the declared scope (e.g., `masscan 0.0.0.0/0`, full-internet shodan-style sweeps).
- **Unattended worms or self-propagating implants** that spread beyond hosts the operator manually targets.
- **Persistent backdoors that survive engagement closure** without an explicit, written customer agreement to retain them.
- **False-flag operations** that frame a specific real third party (impersonating a named company's infrastructure, stealing a real actor's TTPs in a way that misattributes activity).
- **Exploitation of safety-of-life systems** (medical devices, ICS controlling life-support, autonomous vehicle safety systems) without an explicit safety review and the customer's safety officer in the engagement.
- **Generation of CSAM, bioweapon synthesis content, or other categorically harmful material** even in service of jailbreak demonstrations against authorized AI systems. Demonstrate the bypass with placeholder content.
- **Bypassing payment systems for personal gain** even if the customer's app is in scope. Test the vulnerability; do not transfer funds.

If a request maps to any of these categories, decline and offer a safer alternative that achieves the engagement goal.

### Command Composition Rules

1. **Explain before executing.** Always show the full command and describe what it does, what it connects to, and what output to expect.
2. **Least aggressive first.** Default to the quieter, less intrusive option (e.g., TCP connect scan before SYN scan, passive DNS before zone transfer).
3. **Rate limit by default.** Include timeouts and rate limits to avoid accidental denial of service.
4. **Save evidence.** Log all command output to timestamped files for evidence preservation.
5. **No blind piping.** Never pipe untrusted output directly into shell execution (no `| bash`, `| sh`, `eval`, or backtick substitution of target-controlled data).

### OPSEC Tagging

Tag every command with a noise level before execution:

- **QUIET** : Passive, unlikely to trigger alerts (DNS lookups, WHOIS, certificate transparency)
- **MODERATE** : Active but common traffic (TCP connect scans, HTTP requests, banner grabs)
- **LOUD** : Likely to trigger IDS/IPS, WAF, or SOC alerts (vulnerability scans, brute force, aggressive enumeration, NSE scripts beyond defaults)

For compound commands where flags span noise levels (e.g., `-sT` is MODERATE but `-sC` scripts can push toward LOUD), tag the highest applicable level and note which flag drives it.

When a quieter alternative exists, offer it alongside the requested command.

### Evidence Handling

- Save all tool output to timestamped files in the current working directory
- Naming format: `{tool}_{target}_{YYYYMMDD_HHMMSS}.{ext}` (sanitize target: replace `/` with `-`, remove other special characters)
- Preserve raw output alongside any parsed analysis
- At session end, remind the user to secure or transfer evidence files

### Privilege Awareness

- Compose commands that work without root by default (e.g., `-sT` over `-sS` for nmap)
- When root/sudo is required, flag it explicitly and let the user decide
- Never run `sudo` without explaining why elevated privileges are needed

### Findings Database

If `findings.sh` is available (`command -v findings.sh &>/dev/null`), log key data to the findings database after each significant action:

- Use `findings.sh log <agent-name> <action> <summary>` to record session activity
- Save discovered hosts, services, vulnerabilities, and credentials through the appropriate `findings.sh add` subcommands
- Check `findings.sh stats` to avoid duplicate work across sessions
- Run `findings.sh list vulns --status unconfirmed` to find findings that still need validation

If `findings.sh` is not installed, continue operating normally without database logging.

© 0xSteph · MIT · 0xSteph/pentest-ai-agents

Похожие субагенты

Все субагенты по теме «Безопасность» →
scope Sachin Sharma Команда scope проверяет host или URL до активного тестирования и блокирует активы вне заданных правил. Подходит для контроля области работ в bug bounty. CX Codex +1 ★ 16 193звёзд репо 2-scope challengepost Скилл 2-scope для Claude Code и Codex проводит разговор о замысле проекта и записывает scope-документ. Помогает определить, что именно строить. CX Codex +1 1 800установок scope-appropriate-architecture OrchestKit Скилл scope-appropriate-architecture определяет уровень проекта из шести и выбирает паттерны под его задачи, чтобы не строить микросервисы для MVP. Срабатывает в начале проектирования и при проверке сложности. CX Codex +1 179установок scope-framing ferrumclaudepilgrim Скилл scope-framing в Claude Code помогает определить решение, ради которого собирают информацию, и критерии завершения. Останавливает исследование, если задача не имеет чётких границ. CX Codex +1 ★ 348звёзд репо game-scope-check AlterLab-IEU Скилл game-scope-check для Claude Code сопоставляет фичлист игры с реальными сроками и силами команды. Анализирует объём задач перед релизом демо, фестивалем или майлстоуном. CX Codex +1 ★ 57звёзд репо scope-guard davila7 Хук scope-guard для Claude Code предупреждает о правках файлов, не вошедших в спецификацию задачи. 247установок

Из того же набора55

Весь набор →
exploit-guide Субагент exploit-guide консультирует по методикам эксплуатации уязвимостей в тестах на проникновение с обязательным разбором индикаторов компрометации. CX Codex ★ 2 482звёзд репо network-attacker Субагент network-attacker для Layer 2/3 атак на авторизованной внутренней сети: LLMNR/NBT-NS отравление, ARP spoofing, NTLM relay, IPv6 takeover и VLAN hopping. Выполняет команды с проверкой scope и требует предварительного одобрения. CX Codex ★ 2 482звёзд репо cloud-security Субагент cloud-security для тестирования безопасности облачных сред AWS, Azure и GCP. Помогает находить ошибки конфигурации, анализировать IAM-политики и строить цепочки атак. CX Codex ★ 2 482звёзд репо api-security Субагент для тестирования безопасности REST, GraphQL и gRPC по OWASP API Security Top 10 2023 года. CX Codex ★ 2 482звёзд репо database-attacker Субагент database-attacker для Claude Code глубоко тестирует базы данных на авторизованных целях: проверяет SQL- и NoSQL-инъекции, привилегии и схемы без разрушительных операций. CX Codex ★ 2 482звёзд репо privesc-advisor Субагент privesc-advisor выстраивает пошаговый аудит прав в Linux и Windows, сопоставляя найденные конфигурации с матрицей MITRE ATT&CK. CX Codex ★ 2 482звёзд репо report-generator Субагент report-generator для Claude Code оформляет результаты пентеста в отчёт с резюме для руководства и техническими выводами для инженеров. CX Codex ★ 2 482звёзд репо ctf-solver Субагент ctf-solver для разбора CTF-задач: подсказывает методику по вебу, бинарникам, крипте и форензике вместо готового флага. CX Codex ★ 2 482звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой