Ревью безопасности GitHub Actions

Ищет в воркфлоу GitHub Actions атаки, доступные постороннему без прав на запись: pwn request, инъекции через выражения, команды из комментариев, кражу токенов, подмену конфигов агентов. Для случаев, когда проверяют безопасность CI или меняют воркфлоу.

БезопасностьПак: Скиллы Sentry192 строкиgha-security-review
Автор
Источник
getsentry/skills/skills/gha-security-review @ a582c51
Лицензия
Apache-2.0 · Copyright 2025 Functional Software, Inc. dba Sentry

Об этом скилле

Что делает

Скилл ищет в воркфлоу GitHub Actions дыры, которыми может воспользоваться посторонний, и сообщает только о том, что удаётся показать как атаку. У атакующего нет прав на запись: он открывает PR из форка, заводит issue, пишет комментарии, но не может пушить и запускать workflow_dispatch. Всё, для чего нужны права на запись — например, входы ручного запуска или воркфлоу только на push в защищённые ветки, — намеренно оставлено за рамками модели угроз.

Агент читает .github/workflows/, составные и локальные экшены и файлы, которые воркфлоу подгружают: Makefile, скрипты в .github/, CLAUDE.md, AGENTS.md. Дальше восемь проверок. Первые четыре — pwn request (pull_request_target, который выкачивает код из форка), инъекции через ${{ }} в блоках run:, команды из комментариев без проверки author_association и токены с широкими правами, до которых дотягивается чужой код. Ещё четыре — подменённые конфиги для ИИ-агентов, незакреплённые сторонние экшены в привилегированных джобах, права и секреты, а также self-hosted раннеры, кэши и артефакты. Таблица безопасных паттернов — ${{ }} в if: или with:, экшены самого GitHub (actions/*) на тегах и другие — отсекает ложные срабатывания.

Находка получает HIGH, когда собраны все пять частей — точка входа, полезная нагрузка, механизм исполнения, ущерб, набросок PoC, — и MEDIUM в разделе «Needs verification», если звена не хватает. В отчёте находки пронумерованы с GHA-001, к каждой приложен код исправления, а проверенные чистые воркфлоу перечислены отдельно.

Девять справочников подгружаются по найденным триггерам: по одному на класс уязвимостей (pwn-request.md, expression-injection.md, comment-triggered-commands.md, credential-escalation.md, ai-prompt-injection-via-ci.md, supply-chain.md, permissions-and-secrets.md, runner-infrastructure.md) и real-world-attacks.md — семь задокументированных атак кампании HackerBot Claw, по ним калибруется серьёзность.

Когда включать и когда не надо

В репозитории, который принимает внешние PR: перед правкой воркфлоу, после того как в CI добавили ИИ-агента, или как разовый аудит.

Инсайдеры с правами на запись, воркфлоу чужих репозиториев и другие CI-системы его не интересуют. Писать и чинить пайплайны он не умеет.

Как поставить и вызвать

Команда установки ниже скачивает папку. Агент сам подхватывает скилл, когда речь заходит о безопасности воркфлоу или CI. Вызвать вручную:

  • Claude Code: /gha-security-review или попросить скилл по имени.
  • Codex: $gha-security-review.
  • Cursor: наберите / в чате Agent и выберите gha-security-review.

Пример: /gha-security-review Проверь .github/workflows: мы только что добавили ревью от Claude на pull_request_target.

Чем отличается от похожих

CI на GitHub Actions из нашего каталога пишет и чинит воркфлоу и по умолчанию закладывает закрепление по SHA, минимальные permissions и запрет pull_request_target для форков, но атак не прослеживает. Ревью безопасности от Sentry проверяет код приложения и передаёт файлы воркфлоу этому скиллу, если он установлен, — их удобно ставить вместе. Аудит безопасности кода и сервисов разбирает CI как одну из областей более широкого аудита. Его справочник по цепочке поставок охватывает чужой код в привилегированных воркфлоу, инъекции в выражениях и доверие к кэшам и артефактам — для любой CI-системы, без проверок, специфичных для GitHub Actions.

Установка

Выполните одну команду — она сохранит SKILL.md и файлы, которые он использует, в папку скиллов агента. Claude Code и Codex подхватывают новый скилл без перезапуска; если скилл не появился, перезапустите агента.

Скилл написан на английском — агент поймёт его и ответит вам по-русски.

Claude Code — macOS, Linux
curl -fsSL --create-dirs -o ~/.claude/skills/gha-security-review/SKILL.md https://anymodel.org/en/skills/sentry/gha-security-review/SKILL.md -o ~/.claude/skills/gha-security-review/LICENSE https://anymodel.org/en/skills/sentry/gha-security-review/LICENSE -o ~/.claude/skills/gha-security-review/references/ai-prompt-injection-via-ci.md https://anymodel.org/en/skills/sentry/gha-security-review/references/ai-prompt-injection-via-ci.md -o ~/.claude/skills/gha-security-review/references/comment-triggered-commands.md https://anymodel.org/en/skills/sentry/gha-security-review/references/comment-triggered-commands.md -o ~/.claude/skills/gha-security-review/references/credential-escalation.md https://anymodel.org/en/skills/sentry/gha-security-review/references/credential-escalation.md -o ~/.claude/skills/gha-security-review/references/expression-injection.md https://anymodel.org/en/skills/sentry/gha-security-review/references/expression-injection.md -o ~/.claude/skills/gha-security-review/references/permissions-and-secrets.md https://anymodel.org/en/skills/sentry/gha-security-review/references/permissions-and-secrets.md -o ~/.claude/skills/gha-security-review/references/pwn-request.md https://anymodel.org/en/skills/sentry/gha-security-review/references/pwn-request.md -o ~/.claude/skills/gha-security-review/references/real-world-attacks.md https://anymodel.org/en/skills/sentry/gha-security-review/references/real-world-attacks.md -o ~/.claude/skills/gha-security-review/references/runner-infrastructure.md https://anymodel.org/en/skills/sentry/gha-security-review/references/runner-infrastructure.md -o ~/.claude/skills/gha-security-review/references/supply-chain.md https://anymodel.org/en/skills/sentry/gha-security-review/references/supply-chain.md
Codex, Cursor — macOS, Linux
curl -fsSL --create-dirs -o ~/.agents/skills/gha-security-review/SKILL.md https://anymodel.org/en/skills/sentry/gha-security-review/SKILL.md -o ~/.agents/skills/gha-security-review/LICENSE https://anymodel.org/en/skills/sentry/gha-security-review/LICENSE -o ~/.agents/skills/gha-security-review/references/ai-prompt-injection-via-ci.md https://anymodel.org/en/skills/sentry/gha-security-review/references/ai-prompt-injection-via-ci.md -o ~/.agents/skills/gha-security-review/references/comment-triggered-commands.md https://anymodel.org/en/skills/sentry/gha-security-review/references/comment-triggered-commands.md -o ~/.agents/skills/gha-security-review/references/credential-escalation.md https://anymodel.org/en/skills/sentry/gha-security-review/references/credential-escalation.md -o ~/.agents/skills/gha-security-review/references/expression-injection.md https://anymodel.org/en/skills/sentry/gha-security-review/references/expression-injection.md -o ~/.agents/skills/gha-security-review/references/permissions-and-secrets.md https://anymodel.org/en/skills/sentry/gha-security-review/references/permissions-and-secrets.md -o ~/.agents/skills/gha-security-review/references/pwn-request.md https://anymodel.org/en/skills/sentry/gha-security-review/references/pwn-request.md -o ~/.agents/skills/gha-security-review/references/real-world-attacks.md https://anymodel.org/en/skills/sentry/gha-security-review/references/real-world-attacks.md -o ~/.agents/skills/gha-security-review/references/runner-infrastructure.md https://anymodel.org/en/skills/sentry/gha-security-review/references/runner-infrastructure.md -o ~/.agents/skills/gha-security-review/references/supply-chain.md https://anymodel.org/en/skills/sentry/gha-security-review/references/supply-chain.md
Claude Code — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/ai-prompt-injection-via-ci.md','references/comment-triggered-commands.md','references/credential-escalation.md','references/expression-injection.md','references/permissions-and-secrets.md','references/pwn-request.md','references/real-world-attacks.md','references/runner-infrastructure.md','references/supply-chain.md') { $p = Join-Path "$HOME\.claude\skills\gha-security-review" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/sentry/gha-security-review/$f" -UseBasicParsing -OutFile $p }
Codex, Cursor — Windows PowerShell
foreach ($f in 'SKILL.md','LICENSE','references/ai-prompt-injection-via-ci.md','references/comment-triggered-commands.md','references/credential-escalation.md','references/expression-injection.md','references/permissions-and-secrets.md','references/pwn-request.md','references/real-world-attacks.md','references/runner-infrastructure.md','references/supply-chain.md') { $p = Join-Path "$HOME\.agents\skills\gha-security-review" $f; New-Item -ItemType Directory -Force (Split-Path $p) | Out-Null; Invoke-WebRequest "https://anymodel.org/en/skills/sentry/gha-security-review/$f" -UseBasicParsing -OutFile $p }

Другой агент: сохраните файл в его папку скиллов или дайте ему ссылку на файл: https://anymodel.org/en/skills/sentry/gha-security-review/SKILL.md

SKILL.md

Исходник

<!-- Attack patterns and real-world examples sourced from the HackerBot Claw campaign analysis by StepSecurity (2025): https://www.stepsecurity.io/blog/hackerbot-claw-github-actions-exploitation -->

GitHub Actions Security Review

Find exploitable vulnerabilities in GitHub Actions workflows. Every finding MUST include a concrete exploitation scenario — if you can't build the attack, don't report it.

This skill encodes attack patterns from real GitHub Actions exploits — not generic CI/CD theory.

Scope

Review the workflows provided (file, diff, or repo). Research the codebase as needed to trace complete attack paths before reporting.

Files to Review

  • .github/workflows/*.yml — all workflow definitions
  • action.yml / action.yaml — composite actions in the repo
  • .github/actions/*/action.yml — local reusable actions
  • Config files loaded by workflows: CLAUDE.md, AGENTS.md, Makefile, shell scripts under .github/

Out of Scope

  • Workflows in other repositories (only note the dependency)
  • GitHub App installation permissions (note if relevant)

Threat Model

Only report vulnerabilities exploitable by an external attacker — someone without write access to the repository. The attacker can open PRs from forks, create issues, and post comments. They cannot push to branches, trigger workflow_dispatch, or trigger manual workflows.

Do not flag vulnerabilities that require write access to exploit:

  • workflow_dispatch input injection — requires write access to trigger
  • Expression injection in push-only workflows on protected branches
  • workflow_call input injection where all callers are internal
  • Secrets in workflow_dispatch/schedule-only workflows

Confidence

Report only HIGH and MEDIUM confidence findings. Do not report theoretical issues.

Confidence Criteria Action
HIGH Traced the full attack path, confirmed exploitable Report with exploitation scenario and fix
MEDIUM Attack path partially confirmed, uncertain link Report as needs verification
LOW Theoretical or mitigated elsewhere Do not report

For each HIGH finding, provide all five elements:

  1. Entry point — How does the attacker get in? (fork PR, issue comment, branch name, etc.)
  2. Payload — What does the attacker send? (actual code/YAML/input)
  3. Execution mechanism — How does the payload run? (expression expansion, checkout + script, etc.)
  4. Impact — What does the attacker gain? (token theft, code execution, repo write access)
  5. PoC sketch — Concrete steps an attacker would follow

If you cannot construct all five, report as MEDIUM (needs verification).


Step 1: Classify Triggers and Load References

For each workflow, identify triggers and load the appropriate reference:

Trigger / Pattern Load Reference
pull_request_target references/pwn-request.md
issue_comment with command parsing references/comment-triggered-commands.md
${{ }} in run: blocks references/expression-injection.md
PATs / deploy keys / elevated credentials references/credential-escalation.md
Checkout PR code + config file loading references/ai-prompt-injection-via-ci.md
Third-party actions (especially unpinned) references/supply-chain.md
permissions: block or secrets usage references/permissions-and-secrets.md
Self-hosted runners, cache/artifact usage references/runner-infrastructure.md
Any confirmed finding references/real-world-attacks.md

Load references selectively — only what's relevant to the triggers found.

Step 2: Check for Vulnerability Classes

Check 1: Pwn Request

Does the workflow use pull_request_target AND check out fork code?

  • Look for actions/checkout with ref: pointing to PR head
  • Look for local actions (./.github/actions/) that would come from the fork
  • Check if any run: step executes code from the checked-out PR

Check 2: Expression Injection

Are ${{ }} expressions used inside run: blocks in externally-triggerable workflows?

  • Map every ${{ }} expression in every run: step
  • Confirm the value is attacker-controlled (PR title, branch name, comment body — not numeric IDs, SHAs, or repository names)
  • Confirm the expression is in a run: block, not if:, with:, or job-level env:

Check 3: Unauthorized Command Execution

Does an issue_comment-triggered workflow execute commands without authorization?

  • Is there an author_association check?
  • Can any GitHub user trigger the command?
  • Does the command handler also use injectable expressions?

Check 4: Credential Escalation

Are elevated credentials (PATs, deploy keys) accessible to untrusted code?

  • What's the blast radius of each secret?
  • Could a compromised workflow steal long-lived tokens?

Check 5: Config File Poisoning

Does the workflow load configuration from PR-supplied files?

  • AI agent instructions: CLAUDE.md, AGENTS.md, .cursorrules
  • Build configuration: Makefile, shell scripts

Check 6: Supply Chain

Are third-party actions securely pinned to full SHAs?

  • Pin third-party / external actions and reusable workflows only
  • Do not flag first-party actions/* or github/* on version tags
  • Do not flag same-repo / vendored (./.github/actions/...) as supply-chain pinning issues
  • Only report when the job has secrets, OIDC, write token, release, deploy, package, or signing power — unprivileged read-only CI is not a finding

Check 7: Permissions and Secrets

Are workflow permissions minimal? Are secrets properly scoped?

Check 8: Runner Infrastructure

Are self-hosted runners, caches, or artifacts used securely?

Safe Patterns (Do Not Flag)

Before reporting, check if the pattern is actually safe:

Pattern Why Safe
pull_request_target WITHOUT checkout of fork code Never executes attacker code
${{ github.event.pull_request.number }} in run: Numeric only — not injectable
${{ github.repository }} / github.repository_owner Repo owner controls this
${{ secrets.* }} Not an expression injection vector
${{ }} in if: conditions Evaluated by Actions runtime, not shell
${{ }} in with: inputs Passed as string parameters, not shell-evaluated
Third-party actions pinned to full SHA Immutable reference
First-party actions/* / github/* on version tags Outside third-party pinning policy — do not flag
Same-repo / vendored local actions Not third-party supply chain (review pwn-request separately)
pull_request trigger (not _target) Runs in fork context with read-only token
Any expression in workflow_dispatch/schedule/push to protected branches Requires write access — outside threat model

Key distinction: ${{ }} is dangerous in run: blocks (shell expansion) but safe in if:, with:, and env: at the job/step level (Actions runtime evaluation).

Step 3: Validate Before Reporting

Before including any finding, read the actual workflow YAML and trace the complete attack path:

  1. Read the full workflow — don't rely on grep output alone
  2. Trace the trigger — confirm the event and check if: conditions that gate execution
  3. Trace the expression/checkout — confirm it's in a run: block or actually references fork code
  4. Confirm attacker control — verify the value maps to something an external attacker sets
  5. Check existing mitigations — env var wrapping, author_association checks, restricted permissions, SHA pinning

If any link is broken, mark MEDIUM (needs verification) or drop the finding.

If no checks produced a finding, report zero findings. Do not invent issues.

Step 4: Report Findings

## GitHub Actions Security Review

### Findings

#### [GHA-001] [Title] (Severity: Critical/High/Medium)
- **Workflow**: `.github/workflows/release.yml:15`
- **Trigger**: `pull_request_target`
- **Confidence**: HIGH — confirmed through attack path tracing
- **Exploitation Scenario**:
  1. [Step-by-step attack]
- **Impact**: [What attacker gains]
- **Fix**: [Code that fixes the issue]

### Needs Verification
[MEDIUM confidence items with explanation of what to verify]

### Reviewed and Cleared
[Workflows reviewed and confirmed safe]

If no findings: "No exploitable vulnerabilities identified. All workflows reviewed and cleared."

Подключить через AnyModel API

Скилл работает на той модели, которую использует агент. Подключите Claude Code, Codex или Cursor к AnyModel и запускайте его на Claude, GPT, Gemini и других моделях по одному ключу — оплата за токены, без подписки.

Ещё из пака Скиллы Sentry

AGENTS.md и CLAUDE.md для проекта

Делает короткий AGENTS.md до 60 строк: команды, соглашения и ссылки на документы репозитория, с проверкой путей, а CLAUDE.md превращает в ссылку на него. Для случаев, когда агенту нужны инструкции по проекту или старый файл разросся и устарел.

Аудит настроек Claude Code

Делает список разрешений для settings.json в Claude Code: по стеку репозитория подбирает только читающие команды нужных инструментов, домены документации и MCP Sentry или Linear. Для случаев, когда настраиваете или проверяете разрешения Claude Code.

Код-ревью по практикам Sentry

Делает ревью изменения по правилам Sentry: ошибки выполнения, производительность и N+1, побочные эффекты, совместимость, безопасность, архитектура и тесты, с вежливым тоном и одобрением при мелочах. Для случаев, когда нужно отревьюить PR или ветку.

Упрощение и выравнивание кода

Делает недавно изменённый код проще, не меняя поведения: меньше вложенности, без вложенных тернарников, понятные имена, без лишних абстракций, по соглашениям из CLAUDE.md. Для случаев, когда код работает, но читается тяжелее, чем нужно.

Коммиты в формате Conventional Commits

Делает коммиты в стиле Sentry по Conventional Commits: ветка вместо main, тема с типом до 70 символов с заглавной буквы, подвал Fixes или Refs, без персональных данных. Для случаев, когда нужно закоммитить или составить сообщение коммита.

Ревью доступа в Django

Делает ревью контроля доступа в Django и DRF: разбирает модель авторизации, прослеживает каждый эндпоинт от ID до запроса и сообщает только подтверждённые дыры с исправлением в коде. Для случаев, когда проверяете IDOR, права или изоляцию тенантов.

Поиск багов в изменениях ветки

Проверяет коммиты текущей ветки на дыры в безопасности, баги и проблемы качества по чек-листу из одиннадцати пунктов и выдаёт подтверждённые находки с файлом, строкой, уровнем и исправлением, не трогая код. Для случаев, когда нужен проход перед PR.

Доводка PR до зелёного CI

Доводит открытый PR до зелёного: чинит упавший CI и важные замечания ревью, проверяет локально, коммитит, пушит и повторяет, а на одобрении человека или черновике останавливается. Для случаев, когда PR красный или ждёт разбора комментариев.

Заголовок и описание PR

Пишет или обновляет заголовок PR в формате Sentry и короткое описание для ревьюеров без шаблонных разделов и логов тестов, затем открывает черновик или правит PR. Для случаев, когда открывают PR или новые коммиты поменяли его объём.

Оптимизация промптов

Пишет, чинит или переносит системные промпты и промпты агентов по небольшому набору тестов: сравнивает варианты на одних случаях и проверяет лучший на отложенных. Для случаев, когда промпт ненадёжен, переезжает на другую модель или ему нужны тесты.

Утечки секретов через сериализацию

Находит секреты, которые утекают, когда секретное поле в dataclass, модели pydantic или объекте JS встречает код, пишущий объекты целиком в логи или спаны; вторую половину ищет по всему репозиторию. Для случаев, когда изменение добавляет такое поле или код.

SECURITY_MODEL.md для инструментов ревью

Делает SECURITY_MODEL.md: описывает для инструментов ревью безопасности доступность системы, инварианты, классы находок и подтверждённые владельцем исключения. Для случаев, когда репозиторий готовят к автоматическому ревью безопасности.

Проверка скиллов на угрозы

Проверяет скилл до установки: статический скан на промпт-инъекции, скрытые символы, секреты, опасные скрипты и ловушки в структуре, затем разбор намерений и прав с вердиктом. Для случаев, когда скилл взят из чужого источника.

Скиллы по спецификации Agent Skills

Пишет и дорабатывает скиллы по процессу Sentry: источники с происхождением, самая простая форма исполнения, SPEC.md и SOURCES.md, проверка точности после правок и структурный валидатор. Для случаев, когда скилл будет поддерживать команда.

Ревью безопасности от Sentry

Ищет в файле, диффе или компоненте эксплуатируемые уязвимости по справочникам OWASP, изучает кодовую базу до вывода и сообщает только о находках с входом от атакующего. Для случаев, когда нужно ревью безопасности без шума.

Ревью производительности Django

Ищет в коде на Django и DRF N+1-запросы, неограниченные querysets, недостающие индексы и запись в цикле, проверяя объём таблиц и горячие пути. Для случаев, когда тормозит view или эндпоинт либо правка касается больших таблиц.