Skip to content

Defense in Depth for Prompt Injection

Principle of Layered Protection

Layered protection (defense in depth) assumes that no single protection mechanism is sufficient. In the context of prompt injection, this means combining preventive, detection, and response measures at different levels of the application architecture.

Each level of protection should be independent so that compromising one level does not lead to a complete security failure.

Protection Levels

Level Mechanism Example
Input Filtering and sanitization Detection of known injection patterns
Prompt Instruction isolation Separation of system and user messages
Model Model robustness Training on adversarial examples
Output Validation Checking for compliance with expected schema
Orchestration Principle of least privilege Limiting tool access

Implementation

Example of multi-layered protection in an application:

  1. Input filter: check for known malicious patterns.
  2. Context separation: use special delimiters and instructions.
  3. Output validation: validate that the model does not output system instructions.
  4. Tool restriction: each tool checks arguments for compliance with expected format.
  5. Monitoring: logging and analysis of suspicious interactions.
def layered_defense(user_input, system_prompt):
    if detect_injection(user_input):
        return "Input blocked"
    safe_prompt = isolate_user_input(system_prompt, user_input)
    output = call_llm(safe_prompt)
    if not validate_output(output):
        return "Output validation failed"
    return output

See also