agent-security-hardening
Что он делает
Это руководство учит, как защищать ИИ-системы, которые работают с недоверенными данными. Оно помогает создать защитные барьеры, чтобы опасные данные не могли навредить.
Когда использовать
- ✓Когда вы создаете ИИ-систему, которая получает внешние данные.
- ✓Когда вы проверяете код, который превращает данные в действия.
- ✓Когда вы разделяете разных пользователей или задачи внутри ИИ-системы.
Ссылка на скилл
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/agent-security-hardening/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Как сделать так, чтобы ИИ не выполнял опасные команды на основе данных, которые я ему передал?”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Руководство советует определить, где недоверенные данные попадают в систему, тщательно проверять всё до любого действия и ограничивать доступ к файлам и другим частям системы.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Agent Security Hardening
Harden the boundaries where an agent turns untrusted data into filesystem, network, memory, or tool actions. Produce concrete controls and tests for the framework being reviewed; a checklist without enforcement evidence is incomplete.
Important
- Treat model output, retrieved content, tool output, memory, and cross-agent messages as untrusted input.
- Default external integrations to read-only and grant each write capability separately.
- Validate at the action boundary even when an upstream prompt or schema already validated the value.
- Fail closed before a side effect when identity, destination, ownership, or containment cannot be proven.
- Before a delete, publish, credential rotation, or other irreversible action, the real tool entry point must authorize the authenticated principal for that exact operation and resource scope, then require explicit confirmation or a valid scoped pre-approval. Missing or invalid evidence blocks the action.
- Use hard bounds defined by the governing requirement and stricter values verified from deployment configuration. When neither defines a value, mark it as a required decision and test that the implementation rejects an unbounded configuration; do not invent a plausible value.
When to Activate
- Building an autonomous agent, tool gateway, memory service, or agent-to-agent protocol
- Reviewing code that maps model output into commands, paths, URLs, credentials, or API mutations
- Isolating tenants, projects, sessions, or workspaces in a long-running agent process
- Hardening temporary files, logs, tool responses, or external-content ingestion
Hardening Workflow
1. Map Trust Boundaries
List every boundary as source -> parser -> validator -> side effect. Include direct user input, model output, retrieved documents, memory, environment variables, tool results, and messages from other agents.
For each side effect, record:
- the identity and scope authorizing it;
- the exact validator that runs immediately before it;
- the maximum input and output size;
- the audit evidence produced;
- the recovery path if the operation is interrupted.
This step is complete when every write, command, network mutation, and credential use has one named authorization boundary.
2. Validate Identifiers, Environment Values, and URLs
Use an allowlist for identifiers that become filenames, keys, selectors, or command arguments. Agent IDs have the issue-defined hard maximum of 64 characters; deployment configuration may choose a stricter positive limit but cannot raise that boundary:
import re
SAFE_AGENT_ID_CHARS = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]*$")
HARD_MAX_AGENT_ID_LENGTH = 64
def require_agent_id(value: object, *, max_length: int) -> str:
if (
isinstance(max_length, bool)
or not isinstance(max_length, int)
or not 1 <= max_length <= HARD_MAX_AGENT_ID_LENGTH
):
raise RuntimeError("configured agent ID limit must be between 1 and 64")
if (
not isinstance(value, str)
or len(value) > max_length
or not SAFE_AGENT_ID_CHARS.fullmatch(value)
):
raise ValueError("invalid agent identifier")
return value
When an identifier becomes a CLI argument, pass it through an argv API and place it after the command's end-of-options marker where supported. Character validation is not a substitute for argument separation.
Reject missing and whitespace-only environment values before constructing a client:
def require_env(name: str, environ: dict[str, str]) -> str:
value = environ.get(name)
if value is None or not value.strip():
raise RuntimeError(f"{name} is required")
return value
Parse URLs, allow only schemes required by the deployment, require a host, reject embedded credentials, and block private-network destinations when the URL is attacker-controlled. For every outbound connection and redirect hop, pin the connection to a validated public address or verify the connected peer address at connection time so DNS rebinding cannot cross the boundary. A credential-bearing request must use HTTPS with certificate verification before credentials are attached. Disable automatic cross-origin credential forwarding; when the scheme or origin changes, strip the credentials and reauthorize the new destination or reject the redirect. Re-run destination, connected-address, and transport validation on every hop.
…
Частые вопросы
Что означает «относиться к выводу модели как к недоверенному входу»?
Это значит, что всё, что генерирует ИИ, даже если оно выглядит безопасным, нужно проверить перед использованием, потому что там может оказаться что-то неожиданное или опасное.
Зачем проверять данные, если они уже проверялись раньше?
Проверка на каждом этапе, особенно перед действием, которое может что-то изменить (например, удалить файл), гарантирует, что опасное не пройдет незамеченным.
Что такое «fail closed»?
Это правило безопасности: в сомнительных случаях блокируйте доступ или действие. Если нельзя доказать, что что-то безопасно, лучше не позволять этого делать.
Подробности
Оригинальное описание автора
Security hardening guidance for AI agent frameworks that process untrusted content, invoke tools, write workspace files, manage runtime identifiers, or handle credentials. Use when building or reviewing an agent runtime, autonomous worker, tool gateway, memory service, or multi-tenant agent deployment. Do not use for general web application security or offensive testing.
repo: affaan-m/ECC
Популярность
- Звёзды на GitHub
- 280k
- Место в рейтинге
- #131
- Лицензия
- MIT
- Обновлён
- 15.10.2026
Комментарии
- …
Другие скиллы из этого репозитория
accessibility
280kПомогает агенту создавать интерфейсы, которыми может пользоваться каждый. Следит, чтобы сайты и приложения работали для людей с нарушениями зрения или моторики.
agent-architecture-audit
280kЗаставляет агента проверить, всё ли работает правильно. Находит и исправляет проблемы в системах ИИ, чтобы они работали как задумано.
agent-eval
280kПомогает агенту сравнивать ИИ-инструменты для программирования. Измеряет, какой быстрее, дешевле и надёжнее для конкретных задач.
agent-harness-construction
280kПомогает агенту лучше понимать, как выполнять задачи. Оптимизирует инструменты и инструкции агента, чтобы повысить шансы на успех.
Похожие скиллы
add-model-provider
394kПомогает агенту подключить нового провайдера ИИ-моделей к OpenClaw безопасными командами, хранить ключи API не в открытом виде и провести живой тест.
acp-router
394kПомогает агенту передать задачу инструменту для программирования, например Claude Code или Cursor, через OpenClaw, чтобы работа шла в этом инструменте.
browser-automation
394kУчит агента пошагово управлять веб-страницами: входить в аккаунты, работать с вкладками и восстанавливаться, если страница перестала отвечать.