본문으로 건너뛰기
Skillpedia
에이전트48k · #5528

prompt-injection-defense

하는 일

이 도구는 AI 시스템을 '프롬프트 인젝션'이라 불리는, 악의적으로 제어권을 빼앗으려는 시도로부터 보호합니다. 입력을 검사하고, AI가 할 수 있는 일을 제한하고, 출력을 검증하는 방식으로 작동합니다.

사용하는 경우

  • ✓AI 기반 애플리케이션을 만들거나 보안을 강화할 때.
  • ✓신뢰할 수 없는 출처의 문서를 AI와 함께 사용할 때.
  • ✓AI가 다른 도구나 기능을 사용하도록 할 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/prompt-injection-defense/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/prompt-injection-defense/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 애플리케이션을 텍스트에 숨겨진 악의적인 지시로부터 보호해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 도구는 AI가 받는 텍스트에서 위험한 명령이 있는지 검사합니다. 또한 AI가 할 수 있는 행동을 제한하고, 응답이 안전한지 확인합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Prompt Injection Defense

Mitigate direct and indirect prompt injection across chat apps, agentic workflows, and RAG pipelines.

When to Use This Skill

Use this skill when:

  • Building or securing any LLM-powered application
  • Designing RAG pipelines that ingest untrusted documents
  • Implementing agentic workflows with tool-calling capabilities
  • Responding to a reported prompt injection vulnerability
  • Performing security reviews of AI-integrated products

Prerequisites

  • Python 3.10+ with re, hashlib, json standard libraries
  • Access to the LLM application source code or configuration
  • Understanding of the application's prompt architecture (system/user/tool boundaries)
  • Test environment with representative user inputs and documents

Attack Surface

  • User input attempting to override system instructions
  • Untrusted documents/web pages in retrieval context
  • Tool output that smuggles malicious instructions
  • Cross-tenant leakage via shared context windows
  • Markdown or HTML injection in rendered outputs
  • Multi-turn attacks that gradually shift context

Defense-in-Depth Pattern

  1. Instruction hierarchy enforcement: system > developer > user > tool output.
  2. Context segregation: isolate untrusted text from control instructions.
  3. Tool permissioning: explicit allow-list per task and tenant.
  4. Output policy checks: validate schema, redact secrets, block unsafe actions.
  5. Human approval: required for high-impact operations.

Input Sanitization Functions

"""prompt_sanitizer.py - Input sanitization for LLM applications."""

import re
import hashlib
import json
from typing import Optional

# Patterns that commonly appear in injection attempts
INJECTION_PATTERNS = [
    r"(?i)ignore\s+(all\s+)?previous\s+instructions",
    r"(?i)disregard\s+(all\s+)?(above|previous|prior)",
    r"(?i)you\s+are\s+now\s+(DAN|evil|unrestricted|jailbroken)",
    r"(?i)system\s*:\s*override",
    r"(?i)SYSTEM\s+OVERRIDE",
    r"(?i)new\s+instructions?\s*:",
    r"(?i)forget\s+(everything|all|your\s+instructions)",
    r"(?i)act\s+as\s+if\s+you\s+have\s+no\s+(restrictions|limits|rules)",
    r"(?i)pretend\s+(you\s+are|to\s+be)\s+.*(unrestricted|evil|without)",
    r"(?i)BEGIN\s+(TRUSTED|SYSTEM|ADMIN)\s+(CONTEXT|PROMPT|OVERRIDE)",
    r"(?i)```system",
    r"(?i)\[INST\]",
    r"(?i)<\|im_start\|>system",
]

COMPILED_PATTERNS = [re.compile(p) for p in INJECTION_PATTERNS]


def detect_injection(text: str) -> dict:
    """Scan text for known prompt injection patterns.

    Returns:
        dict with 'detected' bool, 'patterns' list of matched pattern descriptions,
        and 'risk_score' float between 0.0 and 1.0.
    """
    matches = []
    for i, pattern in enumerate(COMPILED_PATTERNS):
        if pattern.search(text):
            matches.append(INJECTION_PATTERNS[i])

    risk_score = min(len(matches) / 3.0, 1.0)
    return {
        "detected": len(matches) > 0,
        "patterns": matches,
        "risk_score": risk_score,
        "input_length": len(text),
    }


def sanitize_input(text: str, max_length: int = 4096) -> str:
    """Sanitize user input before passing to the LLM.

    - Truncates to max_length
    - Strips null bytes and control characters
    - Removes Unicode homoglyph tricks
    - Normalizes whitespace
    """
    # Truncate
    text = text[:max_length]

    # Remove null bytes and most control characters (keep newlines and tabs)
    text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)

    # Normalize Unicode confusables (basic set)
    confusable_map = {
        '\u200b': '',   # zero-width space
        '\u200c': '',   # zero-width non-joiner
        '\u200d': '',   # zero-width joiner
        '\u2060': '',   # word joiner
        '\ufeff': '',   # BOM
        '\u00a0': ' ',  # non-breaking space
    }
    for char, replacement in confusable_map.items():
        text = text.replace(char, replacement)

    # Collapse excessive whitespace
    text = re.sub(r'\n{4,}', '\n\n\n', text)
    text = re.sub(r' {10,}', '     ', text)

    return text.strip()


def sanitize_retrieved_context(documents: list[str], source_label: str = "RETRIEVED") -> str:
    """Wrap retrieved documents with clear boundary markers.

    This makes it harder for injected instructions in documents
    to be interpreted as system or user messages.
    """
    sanitized_parts = []
    for i, doc in enumerate(documents):
        doc_hash = hashlib.sha256(doc.encode()).hexdigest()[:8]

…
자주 묻는 질문

'프롬프트 인젝션'이란 무엇인가요?

누군가가 AI를 속여 원래의 지시 대신 비밀스럽거나 악의적인 지시를 따르게 하는 것입니다.

왜 이것을 걱정해야 하나요?

프롬프트 인젝션은 AI가 정보를 유출하거나, 원하지 않는 행동을 하거나, 안전하지 않게 행동하게 만들 수 있습니다.

이 도구는 어떻게 도움이 되나요?

AI의 입력과 출력을 검사하는 보안 요원처럼 작동해, 악의적인 명령이 실행되지 않도록 막습니다.

상세 정보

작성자의 원본 설명

Defend AI systems against prompt injection and indirect prompt attacks using input controls, tool permissions, output validation, and isolation boundaries.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5528
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬