К основному содержанию
скилл CX Codex

detecting-ai-model-prompt-injection-attacks — скилл для Claude Code

Скилл detecting-ai-model-prompt-injection-attacks выявляет попытки инъекции в запросы к ИИ-моделям через регулярные выражения, анализ структуры и трансформатор DeBERTa.

Apache-2.0 280 установок ★ 36 511 обновлён 2026-08-31

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill detecting-ai-model-prompt-injection-attacks -a claude-code
Открыть на GitHub

Что делает detecting-ai-model-prompt-injection-attacks

Скилл работает в три слоя. Первый — регулярные выражения с 25+ сигнатурами известных векторов атак, включая переопределение системного промпта и инъекции через разделители. Второй — эвристический скоринг аномалий: анализирует плотность команд, долю спецсимволов, смешивание языков, избыток заглавных букв, подозрительные последовательности токенов. Третий — классификатор на базе DeBERTa-v3, обученный на датасетах инъекций, выдаёт вероятность от 0 до 1 с порогом по умолчанию 0,85.

Используй скилл на входе приложения — проверяй текст перед отправкой в модель, логируй срабатывания для аудита. Можно применить к файлам истории запросов, чтобы найти прошлые попытки атак. Требует Python 3.10+, библиотеки transformers, torch, sentencepiece. На первый запуск модель DeBERTa загружается с Hugging Face (700 МБ); после этого работает и офлайн.

По умолчанию скилл сочетает все три слоя с весами: регулярные выражения 0,3, эвристика 0,2, классификатор 0,5. Можно запустить только регулярные выражения (< 1 мс на вход) или только эвристику без загрузки модели.

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

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

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

  • Проверь это письмо от пользователя на инъекции перед отправкой агенту
  • Просканируй весь файл истории запросов режимом full и выведи JSON с результатами
  • Настрой порог классификатора на 0,90 и проверь только эту фразу режимом regex

Как установить detecting-ai-model-prompt-injection-attacks

1Через Skills CLI (Vercel)

npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill detecting-ai-model-prompt-injection-attacks -a claude-code

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

~/.claude/skills/detecting-ai-model-prompt-injection-attacks/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/detecting-ai-model-prompt-injection-attacks/

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

Вопросы о detecting-ai-model-prompt-injection-attacks

Как установить detecting-ai-model-prompt-injection-attacks в Claude Code?

Выполни команду npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill detecting-ai-model-prompt-injection-attacks -a claude-code, затем открой ~/.claude/skills/detecting-ai-model-prompt-injection-attacks/SKILL.md.

Что делает этот скилл?

Анализирует текстовые входы тремя способами — сигнатурным поиском (25+ паттернов атак), анализом структуры (эвристика) и классификацией на трансформаторе DeBERTa — и выдаёт общий риск-скор. Подходит для фильтра перед отправкой в модель или аудита истории запросов.

Какие зависимости нужны?

Python 3.10+, пакеты transformers, torch, sentencepiece, protobuf. Модель DeBERTa (700 МБ) качается с Hugging Face при первом запуске и кэшируется.

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

SKILL.md · Apache-2.0
---
name: detecting-ai-model-prompt-injection-attacks
description: Detects prompt injection using regex signature matching, heuristic scoring for structural anomalies, and DeBERTa-based transformer classification, flagging direct injections (system-prompt overrides, role-play escapes) and indirect injections (encoded payloads, obfuscation) per OWASP LLM Top 10 (LLM01:2025). Use for input validation layers in chatbots/agents/RAG pipelines, or for retrospectively classifying injection attempts in logs or incident investigations.
domain: cybersecurity
subdomain: ai-security
tags:
- prompt-injection
- LLM-security
- OWASP-LLM-Top10
- NLP-classification
- input-validation
version: 1.0.0
author: mukul975
license: Apache-2.0
atlas_techniques:
- AML.T0051
- AML.T0054
- AML.T0056
- AML.T0068
- AML.T0067
nist_ai_rmf:
- GOVERN-1.1
- GOVERN-6.1
- MEASURE-2.7
- MEASURE-2.5
- MANAGE-2.4
d3fend_techniques:
- Content Validation
- Content Filtering
- Application Hardening
- Inbound Traffic Filtering
- User Behavior Analysis
nist_csf:
- GV.OC-03
- ID.RA-01
- PR.PS-01
- DE.AE-02
mitre_attack:
- T1659
- T1566
- T1204
- T1588.007
- T1565
---
# Detecting AI Model Prompt Injection Attacks

## When to Use

- Scanning user inputs to LLM-powered applications before they are forwarded to the model
- Building an input validation layer for chatbots, AI agents, or retrieval-augmented generation (RAG) pipelines
- Monitoring logs of LLM interactions to retrospectively identify prompt injection attempts
- Evaluating the effectiveness of existing prompt injection defenses through red-team testing
- Classifying prompt injection payloads during security incident investigations involving AI systems

**Do not use** as the sole defense mechanism against prompt injection -- always combine with output validation, privilege separation, and least-privilege tool access. Not suitable for detecting jailbreaks that do not involve injection of adversarial instructions.

## Prerequisites

- Python 3.10+ with pip for installing detection dependencies
- The `transformers` and `torch` libraries for running the DeBERTa-based classifier model
- The `protectai/deberta-v3-base-prompt-injection-v2` model from Hugging Face (downloaded on first run, approximately 700 MB)
- Network access to Hugging Face Hub for initial model download (offline mode supported after first download)
- Sample prompt injection payloads for testing (the script includes a built-in test suite)

## Workflow

### Step 1: Install Detection Dependencies

Install the required Python packages for all three detection layers:

```bash
pip install transformers torch sentencepiece protobuf
```

For CPU-only environments (no GPU):

```bash
pip install transformers torch --index-url https://download.pytorch.org/whl/cpu
```

### Step 2: Run the Prompt Injection Detector

The detection agent supports three modes -- regex-only, heuristic, and full (regex + heuristic + classifier):

```bash
# Full multi-layered detection on a single input

# Scan a file containing one prompt per line
python agent.py --file prompts.txt --mode full

# Regex-only mode for fast screening (sub-millisecond)
python agent.py --input "Some text" --mode regex

# Heuristic scoring only (no model download needed)
python agent.py --input "Some text" --mode heuristic

# Adjust the classifier confidence threshold (default 0.85)
python agent.py --input "Some text" --threshold 0.90

# Output results as JSON for pipeline integration
python agent.py --file prompts.txt --output json
```

### Step 3: Interpret Detection Results

Each input receives a composite risk assessment:

- **Regex layer**: Matches against 25+ known attack patterns including system prompt overrides, role-play escapes, delimiter injections, and encoding-based obfuscation. Returns matched pattern names.
- **Heuristic layer**: Computes a 0.0-1.0 anomaly score based on structural features -- instruction density, special character ratio, language mixing, excessive capitalization, and suspicious token sequences.
- **Classifier layer**: Runs the DeBERTa-v3 prompt injection classifier returning a probability score. Inputs above the threshold (default 0.85) are flagged as injections.

The final verdict combines all three layers with configurable weights (regex: 0.3, heuristic: 0.2, classifier: 0.5).

### Step 4: Integrate into an LLM Application

Use the detector as a pre-processing filter:

```python
from agent import PromptInjectionDetector

detector = PromptInjectionDetector(threshold=0.85)
result = detector.analyze("user input here")

if result["injection_detected"]:
    # Block or flag the input
    log_security_event(result)
    return "I cannot process that request."
else:
    # Forward to LLM
    response = llm.generate(result["sanitized_input"])
```

### Step 5: Batch Audit Historical Prompts

Scan existing LLM interaction logs for past injection attempts:

```bash
python agent.py --file historical_prompts.txt --mode full --output json > audit_results.json
```

Review the JSON output for any prompts flagged with `injection_detected: true` and investigate the associated sessions.

## Verification

- [ ] The heuristic scorer assigns scores above 0.7 to prompts with high instruction density and structural anomalies
- [ ] The DeBERTa classifier correctly flags adversarial prompts with confidence above the configured threshold
- [ ] Benign prompts (normal questions, code snippets, technical discussions) are not flagged as false positives
- [ ] The detector processes inputs within acceptable latency (regex < 1ms, heuristic < 5ms, classifier < 500ms per input)
- [ ] JSON output mode produces valid JSON parseable by downstream pipeline tools

## Key Concepts

| Term | Definition |
|------|------------|
| **Direct Prompt Injection** | An attack where the user directly includes adversarial instructions in their input to override the system prompt or manipulate LLM behavior |
| **Indirect Prompt Injection** | An attack where malicious instructions are embedded in external data sources (documents, web pages, emails) consumed by the LLM during processing |
| **Heuristic Scoring** | A rule-based analysis method that computes anomaly scores from structural features of the input text without using machine learning |
| **DeBERTa Classifier** | A transformer-based sequence classification model fine-tuned on prompt injection datasets to distinguish adversarial from benign inputs |
| **Canary Token** | A unique marker inserted into system prompts to detect if the LLM has been tricked into leaking its instructions |
| **OWASP LLM01** | The top risk in the OWASP Top 10 for LLM Applications (2025), covering both direct and indirect prompt injection vulnerabilities |

## Tools & Systems

- **protectai/deberta-v3-base-prompt-injection-v2**: Hugging Face transformer model fine-tuned for binary prompt injection classification with 99%+ accuracy on standard benchmarks
- **Rebuff**: Open-source multi-layered prompt injection detection framework by ProtectAI combining heuristics, LLM-based detection, vector similarity, and canary tokens
- **Pytector**: Lightweight Python package for prompt injection detection supporting local DeBERTa/DistilBERT models and API-based safeguards
- **OWASP LLM Top 10**: Industry-standard risk taxonomy for LLM application security, with LLM01 dedicated to prompt injection
- **deepset/prompt-injections**: Hugging Face dataset containing labeled prompt injection examples used for training and evaluating detection models

© mukul975 · Apache-2.0 · mukul975/Anthropic-Cybersecurity-Skills

Похожие скиллы

Все скиллы по теме «Безопасность» →
prompt-injection-test OWASP Скилл prompt-injection-test для Claude Code проверяет ИИ-приложение на промпт-инъекции по таксономии Arcanum PI Taxonomy. Проверяет защиту своего приложения. CX Codex +1 220установок prompt-injection briiirussell Скилл prompt-injection для Claude Code проверяет приложения с LLM и агентов: где в промпт попадает чужой текст и что агент может сделать по чужой инструкции. CX Codex +1 481установок prompt-injection-defense devops-skills Скилл prompt-injection-defense помогает защитить LLM-приложения от прямых и непрямых инъекций промптов. Пригодится при настройке RAG-пайплайнов и субагентов с доступом к вызову инструментов. CX Codex +1 425установок secure-ai oakoss Скилл secure-ai для защиты LLM-слоя приложения: инъекции в промпт, проверка вывода модели, zero-trust для агентов с инструментами. CX Codex +1 130установок llm-ai-hunter H-mmer Скилл llm-ai-hunter для Claude Code берёт на себя роль специалиста по безопасности LLM и агентных систем. Покрывает OWASP LLM Top 10 v2025 и OWASP Agentic AI Top 10 — от prompt injection до атак на MCP-серверы. CX Codex +1 ★ 1 298звёзд репо llm-security semgrep Скилл llm-security для Claude Code проверяет приложения с LLM на риски OWASP Top 10 for LLM 2025. Проверяет чат-боты, RAG, агентов и LLM API. CX Codex +1 1 800установок

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

Весь набор →
scanning-network-with-nmap-advanced Скилл scanning-network-with-nmap-advanced для продвинутого сканирования сетей через Nmap: поиск хостов, определение версий сервисов, обход фаерволов, проверка уязвимостей через NSE-скрипты и парсинг результатов в XML. CX Codex +1 286установок achieving-cmmc-level-2-compliance Скилл achieving-cmmc-level-2-compliance помогает подготовить инфраструктуру к сертификации CMMC Level 2, разметить границы CUI, оценить 110 требований NIST SP 800-171 Rev 2 и рассчитать балл SPRS. CX Codex +1 284установок auditing-cloud-with-cis-benchmarks Скилл auditing-cloud-with-cis-benchmarks проверяет окружения AWS, Azure и GCP по стандартам CIS Benchmarks с помощью Prowler и ScoutSuite. Помогает находить уязвимости конфигурации и готовиться к аудитам. CX Codex +1 282установок implementing-api-schema-validation-security Скилл implementing-api-schema-validation-security настраивает проверку контрактов API через OpenAPI и JSON Schema на шлюзе и в коде. Защищает от инъекций, массового присвоения и утечек данных. CX Codex +1 280установок analyzing-tls-certificate-transparency-logs Скилл analyzing-tls-certificate-transparency-logs ищет фишинговые домены и теневые TLS-сертификаты через логи Certificate Transparency и crt.sh. Помогает SOC выявлять тайпосквоттинг по расстоянию Левенштейна. CX Codex +1 280установок auditing-terraform-infrastructure-for-security Скилл auditing-terraform-infrastructure-for-security настраивает аудит Terraform-кода через Checkov, tfsec, Terrascan и OPA. Он помогает закрыть открытые порты, избыточные права IAM и отсутствие шифрования до деплоя в облако. CX Codex +1 279установок analyzing-typosquatting-domains-with-dnstwist Скилл analyzing-typosquatting-domains-with-dnstwist генерирует домены-двойники для вашего имени, проверяет их через DNS и оценивает риск по схожести страницы и свежести регистрации. CX Codex +1 278установок analyzing-security-logs-with-splunk Скилл analyzing-security-logs-with-splunk помогает расследовать инциденты безопасности в Splunk через SPL. Связывает логи Windows, Sysmon, прокси и сетевых экранов в единый таймлайн. CX Codex +1 278установок

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

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