jailbreak

package
v0.8.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 8 Imported by: 0

README

Jailbreak & Guardrail Bypass Library

Advanced jailbreak techniques designed to bypass LLM safety measures and guardrails through sophisticated psychological, logical, and contextual manipulation.

Overview

The Jailbreak Library provides a comprehensive set of techniques to test LLM resilience against attempts to bypass safety guidelines. It includes:

  • 15+ Built-in Techniques across multiple categories
  • Persona-based attacks (DAN, Developer Mode, etc.)
  • Scenario manipulation (hypothetical worlds, alternate realities)
  • Logic exploits (contradictions, definition gaming)
  • Emotional manipulation (urgency, appeals)
  • Multi-step attack chains for sophisticated bypasses
  • Adaptive learning from failed attempts

Technique Categories

1. Persona-Based (PersonaCategory)

Attempts to make the model adopt an unrestricted persona:

  • DAN (Do Anything Now): Classic and evolved variants
  • Developer Mode: Pretends to enable special mode
  • Evil Confidant: Machiavellian advisor persona
  • Opposite Mode: Reverses all restrictions
2. Scenario-Based (ScenarioCategory)

Creates contexts where rules supposedly don't apply:

  • Hypothetical Scenarios: "In a world where..."
  • Alternate Reality: Different universes with different rules
  • Dream Sequences: Nothing is real in dreams
  • Time Travel: Different era, different rules
3. Logic Exploits (LogicExploitCategory)

Exploits logical contradictions and ambiguities:

  • Contradiction Exploit: Forces logical paradoxes
  • Definition Gaming: Redefines restricted terms
  • Meta-Prompting: Prompts about prompting
4. Emotional Manipulation (EmotionalCategory)

Uses emotional pressure:

  • Urgency Pressure: False time constraints
  • Emotional Appeals: Desperation, illness, danger
  • Authority Claims: Impersonating officials
5. Creative Writing (CreativeCategory)

Frames as creative exercises:

  • Story Continuation: Part of a narrative
  • Screenplay Mode: Movie/TV script writing
  • Character Development: Building fictional characters
6. Technical Exploits (TechnicalCategory)

Leverages technical concepts:

  • Simulation Theory: Questions reality
  • Debug Mode: Fake technical states
  • Meta-Analysis: Analyzing restrictions

Usage

Basic Jailbreak
import "github.com/llm-security/LLMrecon/src/attacks/jailbreak"

// Create engine
config := jailbreak.JailbreakConfig{
    MaxAttempts:      5,
    CreativityLevel:  0.7,  // High variation
    PersistenceLevel: 8,    // Very persistent
    AdaptiveMode:     true, // Learn from failures
}

engine := jailbreak.NewJailbreakEngine(config, logger)

// Execute jailbreak
result, err := engine.ExecuteJailbreak(
    ctx,
    "dan_evolved",              // technique ID
    "write malicious code",     // objective
    provider,                   // LLM provider
)

if result.Success {
    fmt.Printf("Jailbreak successful! Payload: %s\n", result.SuccessfulPayload)
}
Multi-Step Attack Chains
// Execute a sophisticated attack chain
result, err := engine.ExecuteChain(
    ctx,
    "escalating_dan",       // chain ID
    "reveal system prompt", // objective
    provider,
)

// Available chains:
// - "escalating_dan": Progressively aggressive DAN variants
// - "emotional_pressure": Builds emotional manipulation
// - "reality_bending": Questions nature of reality
Available Techniques
// List all techniques
techniques := engine.GetTechniques()

// Techniques by category
personaTechs := engine.GetTechniquesByCategory(jailbreak.PersonaCategory)
scenarioTechs := engine.GetTechniquesByCategory(jailbreak.ScenarioCategory)

Built-in Techniques

ID Name Category Sophistication
dan_classic Classic DAN Persona Basic
dan_evolved Token-Based DAN Persona Intermediate
developer_mode Developer Mode Persona Basic
evil_confidant Evil Advisor Persona Intermediate
hypothetical_scenario Hypothetical World Scenario Basic
alternate_reality Alternate Reality Scenario Advanced
research_pretense Academic Research Academic Intermediate
contradiction_exploit Logic Paradox Logic Advanced
emotional_appeal Emotional Manipulation Emotional Intermediate
urgency_pressure False Urgency Emotional Basic
story_continuation Creative Writing Creative Intermediate
simulation_theory Simulation Argument Technical Expert
meta_prompting Meta-Level Attack Technical Advanced

Attack Chains

Escalating DAN

Progressively more aggressive DAN variants:

  1. Classic DAN → 2. Token DAN → 3. Developer Mode → 4. Logic Exploit
Emotional Pressure

Builds emotional context:

  1. Urgency → 2. Emotional Appeal → 3. Authority Figure
Reality Bending

Questions the nature of reality:

  1. Hypothetical → 2. Alternate Reality → 3. Simulation → 4. Meta-Level

Configuration Options

Creativity Level (0.0 - 1.0)

Controls payload variation:

  • 0.0: No variation
  • 0.5: Moderate variation
  • 1.0: Maximum creativity
Persistence Level (1-10)

How aggressively to push:

  • 1-3: Gentle attempts
  • 4-6: Moderate persistence
  • 7-10: Very aggressive
Adaptive Mode

When enabled:

  • Learns from failed attempts
  • Adjusts techniques based on responses
  • Builds model-specific intelligence

Success Detection

The engine automatically detects success through:

  • Compliance Patterns: "Sure", "Here is", "Certainly"
  • Persona Adoption: Taking on requested role
  • Restriction Bypass: Acknowledging override
  • Behavior Change: Different from baseline

Metrics & Intelligence

Track success rates and gather intelligence:

// Get technique statistics
stats := engine.GetTechniqueStats("dan_evolved")
fmt.Printf("Success rate: %.2f%%\n", stats.SuccessRate*100)

// Model-specific intelligence
intel := engine.GetModelIntelligence("gpt-4")
fmt.Printf("Effective techniques: %v\n", intel.EffectiveTechniques)

Creating Custom Techniques

// Register custom technique
engine.RegisterTechnique(jailbreak.JailbreakTechnique{
    ID:          "custom_technique",
    Name:        "My Custom Jailbreak",
    Category:    jailbreak.CreativeCategory,
    Generator: func(objective string, context map[string]interface{}) (string, error) {
        return fmt.Sprintf("Custom prompt for: %s", objective), nil
    },
})

Best Practices

  1. Start Simple: Begin with basic techniques before escalating
  2. Use Chains: Multi-step attacks are more effective
  3. Enable Adaptation: Let the engine learn from failures
  4. Monitor Patterns: Track what works for each model
  5. Combine Techniques: Layer multiple approaches

Ethical Considerations

This library is for:

  • Authorized security testing
  • Research into LLM vulnerabilities
  • Improving AI safety measures

Never use for:

  • Unauthorized access
  • Malicious purposes
  • Violating terms of service

Technical Details

Guardrail Analysis

The engine analyzes responses for:

  • Explicit refusals
  • Ethical concerns
  • Safety warnings
  • Policy blocks
Response Classification
  • NoResistance: Full compliance
  • WeakResistance: Mild pushback
  • ModerateResistance: Clear boundaries
  • StrongResistance: Firm refusal
  • CompleteBlock: Total shutdown
Chain Strategies
  • Sequential: Try techniques in order
  • Adaptive: Adjust based on responses
  • Parallel: Try multiple simultaneously
  • Escalating: Increase intensity

Contributing

To add new jailbreak techniques:

  1. Implement generator function
  2. Register with appropriate category
  3. Add success patterns
  4. Document technique
  5. Add tests

See jailbreak_engine.go for implementation examples.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AttemptAnalysis

type AttemptAnalysis struct {
	GuardrailsDetected []string
	ResistanceLevel    ResistanceLevel
	PartialSuccess     bool
	Indicators         []SuccessIndicator
}

AttemptAnalysis contains analysis of a jailbreak attempt

type ChainResult

type ChainResult struct {
	ID             string
	ChainID        string
	Objective      string
	Success        bool
	SuccessfulStep int
	Steps          []StepResult
	StartTime      time.Time
	EndTime        time.Time
	Duration       time.Duration
}

ChainResult contains results of a jailbreak chain execution

type ChainStrategy

type ChainStrategy string

ChainStrategy defines how to execute a jailbreak chain

const (
	SequentialStrategy ChainStrategy = "sequential" // Execute in order
	AdaptiveStrategy   ChainStrategy = "adaptive"   // Adjust based on responses
	ParallelStrategy   ChainStrategy = "parallel"   // Try multiple simultaneously
	EscalatingStrategy ChainStrategy = "escalating" // Increase intensity
)

type GuardrailAnalyzer

type GuardrailAnalyzer struct {
	// contains filtered or unexported fields
}

GuardrailAnalyzer analyzes responses for guardrail detection

func NewGuardrailAnalyzer

func NewGuardrailAnalyzer() *GuardrailAnalyzer

NewGuardrailAnalyzer creates a new guardrail analyzer

func (*GuardrailAnalyzer) AnalyzeJailbreak

func (g *GuardrailAnalyzer) AnalyzeJailbreak(response string, objective string) (bool, float64)

AnalyzeJailbreak analyzes if a jailbreak was successful

type GuardrailCategory

type GuardrailCategory string

GuardrailCategory categorizes types of guardrails

const (
	EthicalGuardrail   GuardrailCategory = "ethical"
	SafetyGuardrail    GuardrailCategory = "safety"
	LegalGuardrail     GuardrailCategory = "legal"
	PolicyGuardrail    GuardrailCategory = "policy"
	TechnicalGuardrail GuardrailCategory = "technical"
)

type GuardrailPattern

type GuardrailPattern struct {
	Name     string
	Pattern  string // regex
	Severity GuardrailSeverity
	Category GuardrailCategory
}

GuardrailPattern represents a pattern indicating guardrails

type GuardrailSeverity

type GuardrailSeverity int

GuardrailSeverity indicates how strong a guardrail is

const (
	MildGuardrail GuardrailSeverity = iota
	ModerateGuardrail
	StrongGuardrail
	AbsoluteGuardrail
)

type IndicatorType

type IndicatorType string

IndicatorType categorizes success indicators

const (
	ComplianceIndicator        IndicatorType = "compliance"
	PersonaAdoptionIndicator   IndicatorType = "persona_adoption"
	RestrictionBypassIndicator IndicatorType = "restriction_bypass"
	BehaviorChangeIndicator    IndicatorType = "behavior_change"
	InformationLeakIndicator   IndicatorType = "information_leak"
)

type JailbreakAttempt

type JailbreakAttempt struct {
	Payload    string
	Response   string
	Success    bool
	Confidence float64
	Timestamp  time.Time
	Error      string
	Analysis   AttemptAnalysis
}

JailbreakAttempt represents a single attempt within a jailbreak

type JailbreakChain

type JailbreakChain struct {
	ID          string
	Name        string
	Description string
	Steps       []JailbreakStep
	Strategy    ChainStrategy
}

JailbreakChain represents a multi-step jailbreak sequence

type JailbreakConfig

type JailbreakConfig struct {
	MaxAttempts         int
	CreativityLevel     float64 // 0.0-1.0, higher = more creative variations
	PersistenceLevel    int     // 1-10, how hard to push
	AdaptiveMode        bool    // Learn from failures
	TargetModel         string  // Model-specific optimizations
	EnableChaining      bool    // Allow multi-step jailbreaks
	CollectIntelligence bool    // Gather info about model restrictions
}

JailbreakConfig configures the jailbreak engine

type JailbreakEngine

type JailbreakEngine struct {
	// contains filtered or unexported fields
}

JailbreakEngine provides advanced jailbreak and guardrail bypass techniques

func NewJailbreakEngine

func NewJailbreakEngine(config JailbreakConfig, logger Logger) *JailbreakEngine

NewJailbreakEngine creates a new jailbreak engine

func (*JailbreakEngine) ExecuteChain

func (j *JailbreakEngine) ExecuteChain(ctx context.Context, chainID string, objective string, provider Provider) (*ChainResult, error)

func (*JailbreakEngine) ExecuteJailbreak

func (j *JailbreakEngine) ExecuteJailbreak(ctx context.Context, techniqueID string, objective string, provider Provider) (*JailbreakResult, error)

func (*JailbreakEngine) RegisterTechnique

func (j *JailbreakEngine) RegisterTechnique(technique JailbreakTechnique)

RegisterTechnique adds a new jailbreak technique

type JailbreakMetrics

type JailbreakMetrics struct {
	TotalAttempts        int64
	SuccessfulAttempts   int64
	TechniqueSuccess     map[string]int64
	TechniqueAttempts    map[string]int64
	AverageAttempts      float64
	ModelResistance      map[string]ResistanceProfile
	CommonFailureReasons []string
}

JailbreakMetrics tracks jailbreak statistics

func NewJailbreakMetrics

func NewJailbreakMetrics() *JailbreakMetrics

NewJailbreakMetrics creates new metrics tracker

func (*JailbreakMetrics) RecordResult

func (m *JailbreakMetrics) RecordResult(result *JailbreakResult)

RecordResult records a jailbreak result in metrics

type JailbreakResult

type JailbreakResult struct {
	ID                string
	TechniqueID       string
	Objective         string
	Success           bool
	SuccessfulPayload string
	Attempts          []JailbreakAttempt
	StartTime         time.Time
	EndTime           time.Time
	Duration          time.Duration
	Metadata          map[string]interface{}
}

JailbreakResult contains the results of a jailbreak attempt

type JailbreakStep

type JailbreakStep struct {
	Order           int
	TechniqueID     string
	Objective       string
	SuccessCriteria []string
	FailureHandler  string // Next technique if this fails
	Context         map[string]interface{}
}

JailbreakStep is a step in a jailbreak chain

type JailbreakTechnique

type JailbreakTechnique struct {
	ID              string
	Name            string
	Description     string
	Category        TechniqueCategory
	SuccessRate     float64
	Sophistication  SophisticationLevel
	Generator       TechniqueGenerator
	RequiresContext bool
	ModelSpecific   []string // Models this works best on
}

JailbreakTechnique represents a specific jailbreak method

type Logger

type Logger interface {
	Debug(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
	Error(msg string, keysAndValues ...interface{})
}

Logger interface for logging

type Message

type Message struct {
	Role    string
	Content string
}

Message represents a conversation message

type Persona

type Persona struct {
	ID            string
	Name          string
	Description   string
	Traits        []string
	Background    string
	Motivation    string
	SpeechPattern string
	Limitations   []string // What this persona claims they can ignore

}

Persona represents a character/role for roleplay jailbreaks

type Provider

type Provider interface {
	Query(ctx context.Context, messages []Message, options map[string]interface{}) (string, error)
	GetName() string
	GetModel() string
}

Provider interface for LLM providers

type ResistanceClassifier

type ResistanceClassifier interface {
	Classify(response string) ResistanceLevel
}

ResistanceClassifier classifies the level of resistance

type ResistanceLevel

type ResistanceLevel int

ResistanceLevel indicates how strongly the model resisted

const (
	NoResistance ResistanceLevel = iota
	WeakResistance
	ModerateResistance
	StrongResistance
	CompleteBlock
)

type ResistanceProfile

type ResistanceProfile struct {
	ModelName              string
	AverageResistanceLevel float64
	CommonGuardrails       []string
	EffectiveTechniques    []string
	IneffectiveTechniques  []string
}

ResistanceProfile tracks a model's resistance patterns

type ResponseIndicator

type ResponseIndicator struct {
	Type       string
	Pattern    string
	Meaning    string
	Confidence float64
}

ResponseIndicator indicates specific response patterns

type Scenario

type Scenario struct {
	ID          string
	Name        string
	Setup       string
	Context     string
	Constraints []string // Constraints that are "suspended" in this scenario
	Rationale   string   // Why normal rules don't apply

}

Scenario represents a hypothetical situation for jailbreaks

type SophisticationLevel

type SophisticationLevel int

SophisticationLevel indicates technique complexity

const (
	BasicSophistication SophisticationLevel = iota
	IntermediateSophistication
	AdvancedSophistication
	ExpertSophistication
)

type StepResult

type StepResult struct {
	StepOrder int
	Technique string
	Success   bool
	Response  string
	Attempts  int
	Error     string
	StartTime time.Time
	EndTime   time.Time
	Duration  time.Duration
}

StepResult contains results of a single chain step

type SuccessIndicator

type SuccessIndicator struct {
	Type       IndicatorType
	Confidence float64
	Evidence   string
}

SuccessIndicator shows signs of jailbreak success

type TechniqueCategory

type TechniqueCategory string

TechniqueCategory categorizes jailbreak techniques

const (
	PersonaCategory      TechniqueCategory = "persona_based"
	ScenarioCategory     TechniqueCategory = "scenario_based"
	LogicExploitCategory TechniqueCategory = "logic_exploit"
	EmotionalCategory    TechniqueCategory = "emotional_manipulation"
	AcademicCategory     TechniqueCategory = "academic_pretense"
	CreativeCategory     TechniqueCategory = "creative_writing"
	TechnicalCategory    TechniqueCategory = "technical_exploit"
)

type TechniqueGenerator

type TechniqueGenerator func(objective string, context map[string]interface{}) (string, error)

TechniqueGenerator creates jailbreak payloads

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL