detection

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 9 Imported by: 0

README

Vulnerability Detection Engine for LLM Responses

This package provides a comprehensive vulnerability detection engine for analyzing LLM responses to identify security vulnerabilities based on template-defined criteria.

Features

  • Multiple Detection Methods:

    • String matching for exact or partial text matches
    • Regular expression pattern matching for complex text patterns
    • Semantic analysis for intent or meaning-based vulnerabilities
    • Hybrid detection combining multiple methods
  • Vulnerability Classification:

    • Mapping to OWASP Top 10 for LLMs categories
    • Correlation with ISO/IEC 42001 controls
    • Severity ratings (Critical, High, Medium, Low, Info)
    • Confidence scores for detections
  • Extensibility:

    • Plugin architecture for custom detection methods
    • Hooks for pre and post-detection processing
    • Support for custom embedding providers
  • Performance Optimizations:

    • Concurrent detection for multiple criteria
    • Caching of embeddings for semantic matching
    • Batch processing capabilities

Architecture

The vulnerability detection engine is designed with a modular architecture:

  1. Core Types (types.go):

    • Defines the interfaces and data structures for the detection engine
    • Includes vulnerability types, severity levels, and detection methods
  2. Detection Engine (engine.go):

    • Implements the main detection engine
    • Manages detectors, hooks, and providers
    • Handles concurrent detection and result aggregation
  3. Detectors (detectors.go):

    • Implements specific detection methods
    • Includes string matching, regex matching, semantic matching, and hybrid matching
  4. Embedding Service (embedding.go):

    • Provides semantic analysis capabilities
    • Supports multiple embedding providers
    • Includes caching for performance optimization
  5. Providers (providers.go):

    • Implements standard mapping and remediation providers
    • Maps vulnerabilities to industry standards
    • Provides remediation suggestions
  6. Factory (factory.go):

    • Creates and configures detection engine components
    • Simplifies the creation of complex detection pipelines

Usage

Basic Usage
package main

import (
    "context"
    "fmt"

    "github.com/perplext/LLMrecon/src/vulnerability/detection"
)

func main() {
    // Create factory
    factory := detection.NewFactory()

    // Create detection engine
    engine := factory.CreateDetectionEngine()

    // Define detection criteria
    criteria := []detection.DetectionCriteria{
        {
            Type:  detection.StringMatch,
            Match: "password",
            Context: map[string]interface{}{
                "vulnerability_type": string(detection.SensitiveInfoDisclosure),
                "severity":           string(detection.High),
            },
        },
        {
            Type:    detection.RegexMatch,
            Pattern: `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b`,
            Context: map[string]interface{}{
                "vulnerability_type": string(detection.SensitiveInfoDisclosure),
                "severity":           string(detection.Medium),
            },
        },
    }

    // LLM response to analyze
    response := "My password is 12345 and my email is test@example.com"

    // Detect vulnerabilities
    results, err := engine.Detect(context.Background(), response, criteria)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    // Process results
    for _, result := range results {
        if result.Detected {
            fmt.Printf("Detected %s vulnerability with %s severity\n", 
                result.VulnerabilityType, result.Severity)
            fmt.Printf("Confidence: %d%%\n", result.ConfidenceScore)
            fmt.Printf("Matched content: %v\n", result.MatchedContent)
            
            if len(result.StandardMappings) > 0 {
                fmt.Printf("Standard mappings:\n")
                for _, mapping := range result.StandardMappings {
                    fmt.Printf("  - %s %s: %s\n", 
                        mapping.Standard, mapping.ID, mapping.Name)
                }
            }
            
            if result.RemediationSuggestion != "" {
                fmt.Printf("Remediation: %s\n", result.RemediationSuggestion)
            }
            
            fmt.Println()
        }
    }
}
Custom Detector
package main

import (
    "context"
    "fmt"
    "time"

    "github.com/perplext/LLMrecon/src/vulnerability/detection"
)

// CustomDetector is a custom vulnerability detector
type CustomDetector struct{}

// Name returns the name of the detector
func (d *CustomDetector) Name() string {
    return "custom_detector"
}

// Detect detects vulnerabilities in an LLM response
func (d *CustomDetector) Detect(ctx context.Context, response string, criteria detection.DetectionCriteria) (*detection.DetectionResult, error) {
    // Custom detection logic
    detected := false
    
    // Example: detect if response is too long
    if len(response) > 1000 {
        detected = true
    }
    
    // Create result
    result := &detection.DetectionResult{
        Detected:          detected,
        VulnerabilityType: detection.Overreliance,
        Severity:          detection.Medium,
        ConfidenceScore:   detected ? 100 : 0,
        DetectionMethod:   detection.DetectionMethod("custom"),
        Context: map[string]interface{}{
            "response_length": len(response),
        },
        Timestamp: time.Now(),
    }
    
    return result, nil
}

func main() {
    // Create detection engine
    engine := detection.NewDetectionEngine()
    
    // Register custom detector
    engine.RegisterDetector(&CustomDetector{})
    
    // Define detection criteria
    criteria := []detection.DetectionCriteria{
        {
            Type: detection.DetectionMethod("custom"),
        },
    }
    
    // LLM response to analyze
    response := "This is a very long response..." // Imagine this is >1000 chars
    
    // Detect vulnerabilities
    results, err := engine.Detect(context.Background(), response, criteria)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    // Process results
    for _, result := range results {
        if result.Detected {
            fmt.Printf("Detected %s vulnerability with %s severity\n", 
                result.VulnerabilityType, result.Severity)
        }
    }
}
Batch Detection
package main

import (
    "context"
    "fmt"

    "github.com/perplext/LLMrecon/src/vulnerability/detection"
)

func main() {
    // Create factory
    factory := detection.NewFactory()

    // Create detection engine
    engine := factory.CreateDetectionEngine()

    // Define batch detection requests
    requests := []detection.BatchDetectionRequest{
        {
            Response: "My password is 12345",
            Criteria: []detection.DetectionCriteria{
                {
                    Type:  detection.StringMatch,
                    Match: "password",
                    Context: map[string]interface{}{
                        "vulnerability_type": string(detection.SensitiveInfoDisclosure),
                        "severity":           string(detection.High),
                    },
                },
            },
        },
        {
            Response: "My email is test@example.com",
            Criteria: []detection.DetectionCriteria{
                {
                    Type:    detection.RegexMatch,
                    Pattern: `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b`,
                    Context: map[string]interface{}{
                        "vulnerability_type": string(detection.SensitiveInfoDisclosure),
                        "severity":           string(detection.Medium),
                    },
                },
            },
        },
    }

    // Perform batch detection
    results, err := engine.BatchDetect(context.Background(), requests)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    // Process results
    for i, result := range results {
        fmt.Printf("Response %d:\n", i+1)
        
        if result.Error != "" {
            fmt.Printf("  Error: %s\n", result.Error)
            continue
        }
        
        for j, detection := range result.Results {
            if detection.Detected {
                fmt.Printf("  Detection %d: %s (%s)\n", 
                    j+1, detection.VulnerabilityType, detection.Severity)
            }
        }
        
        fmt.Println()
    }
}

Command Line Interface

The vulnerability detection engine can be used from the command line using the detect command:

# Detect vulnerabilities in an LLM response
$ LLMrecon detect -r response.txt -c criteria.json -o results.json

# Enable verbose output
$ LLMrecon detect -r response.txt -c criteria.json -v
Example Criteria File
[
  {
    "type": "string_match",
    "match": "password",
    "case_sensitive": false,
    "context": {
      "vulnerability_type": "sensitive_info_disclosure",
      "severity": "high"
    }
  },
  {
    "type": "regex_match",
    "pattern": "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b",
    "context": {
      "vulnerability_type": "sensitive_info_disclosure",
      "severity": "medium"
    }
  }
]

Integration with Template Management

The vulnerability detection engine is designed to integrate seamlessly with the Template Management System:

package main

import (
    "context"
    "fmt"

    "github.com/perplext/LLMrecon/src/template/format"
    "github.com/perplext/LLMrecon/src/template/management"
    "github.com/perplext/LLMrecon/src/vulnerability/detection"
)

func main() {
    // Create detection engine
    factory := detection.NewFactory()
    engine := factory.CreateDetectionEngine()

    // Load template
    template, err := format.LoadFromFile("path/to/template.yaml")
    if err != nil {
        fmt.Printf("Error loading template: %v\n", err)
        return
    }

    // Convert template detection criteria to engine criteria
    criteria := []detection.DetectionCriteria{
        {
            Type:      detection.DetectionMethod(template.Test.Detection.Type),
            Pattern:   template.Test.Detection.Pattern,
            Match:     template.Test.Detection.Match,
            Criteria:  template.Test.Detection.Criteria,
            Condition: template.Test.Detection.Condition,
            Context: map[string]interface{}{
                "vulnerability_type": template.Info.Compliance.OWASP,
                "severity":           template.Info.Severity,
            },
        },
    }

    // LLM response to analyze
    response := "This is the LLM response to analyze"

    // Detect vulnerabilities
    results, err := engine.Detect(context.Background(), response, criteria)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    // Create template result
    templateResult := &management.TemplateResult{
        TemplateID: template.ID,
        Status:     management.StatusCompleted,
        Response:   response,
    }

    // Update template result with detection results
    if len(results) > 0 && results[0].Detected {
        templateResult.Detected = true
        templateResult.Score = results[0].ConfidenceScore
        templateResult.Details = results[0].Context
    }

    // Process template result
    fmt.Printf("Template %s: %v\n", templateResult.TemplateID, templateResult.Detected)
}

Performance Considerations

The vulnerability detection engine is designed with performance in mind:

  • Concurrent Detection: Multiple detection criteria are processed concurrently
  • Embedding Caching: Embeddings for semantic matching are cached to avoid redundant computation
  • Batch Processing: Multiple responses can be processed in a single batch operation
  • Efficient Matchers: String and regex matchers are optimized for performance

Extending the Engine

The vulnerability detection engine is designed to be extensible:

  1. Custom Detectors: Implement the VulnerabilityDetector interface
  2. Custom Embedding Providers: Implement the EmbeddingProvider interface
  3. Custom Hooks: Create functions that implement the DetectionHook type
  4. Custom Providers: Implement the RemediationProvider or StandardMappingProvider interfaces

Future Enhancements

  • Persistent Storage: Add support for storing detection results in a database
  • Distributed Detection: Support for distributed detection across multiple nodes
  • Advanced Semantic Analysis: Integration with more sophisticated embedding models
  • Real-time Detection: Support for real-time detection in streaming scenarios
  • Visualization: Tools for visualizing detection results and trends

Documentation

Overview

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Package detection provides the vulnerability detection engine for LLM responses

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchDetectionRequest

type BatchDetectionRequest struct {
	// Response is the LLM response to analyze
	Response string `json:"response"`
	// Criteria is the list of detection criteria to apply
	Criteria []DetectionCriteria `json:"criteria"`
	// DetectorName is the optional name of a specific detector to use
	DetectorName string `json:"detector_name,omitempty"`
}

BatchDetectionRequest represents a request for batch detection

type BatchDetectionResult

type BatchDetectionResult struct {
	// Response is the LLM response that was analyzed
	Response string `json:"response"`
	// Results is the list of detection results
	Results []*DetectionResult `json:"results"`
	// Error is any error that occurred during detection
	Error string `json:"error,omitempty"`
}

BatchDetectionResult represents the result of a batch detection

type DefaultDetectionEngine

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

DefaultDetectionEngine is the default implementation of the DetectionEngine interface

func NewDetectionEngine

func NewDetectionEngine() *DefaultDetectionEngine

NewDetectionEngine creates a new default detection engine

func (*DefaultDetectionEngine) BatchDetect

BatchDetect performs batch detection of vulnerabilities

func (*DefaultDetectionEngine) Detect

func (e *DefaultDetectionEngine) Detect(ctx context.Context, response string, criteria []DetectionCriteria) ([]*DetectionResult, error)

Detect detects vulnerabilities in an LLM response using all registered detectors

func (*DefaultDetectionEngine) DetectWithDetector

func (e *DefaultDetectionEngine) DetectWithDetector(ctx context.Context, response string, criteria DetectionCriteria, detectorName string) (*DetectionResult, error)

DetectWithDetector detects vulnerabilities in an LLM response using a specific detector

func (*DefaultDetectionEngine) GetDetector

func (e *DefaultDetectionEngine) GetDetector(name string) (VulnerabilityDetector, bool)

GetDetector gets a detector by name

func (*DefaultDetectionEngine) ListDetectors

func (e *DefaultDetectionEngine) ListDetectors() []string

ListDetectors lists all registered detectors

func (*DefaultDetectionEngine) RegisterDetector

func (e *DefaultDetectionEngine) RegisterDetector(detector VulnerabilityDetector)

RegisterDetector registers a vulnerability detector

func (*DefaultDetectionEngine) RegisterPostHook

func (e *DefaultDetectionEngine) RegisterPostHook(hook DetectionHook)

RegisterPostHook registers a hook to run after detection

func (*DefaultDetectionEngine) RegisterPreHook

func (e *DefaultDetectionEngine) RegisterPreHook(hook DetectionHook)

RegisterPreHook registers a hook to run before detection

func (*DefaultDetectionEngine) SetRemediationProvider

func (e *DefaultDetectionEngine) SetRemediationProvider(provider RemediationProvider)

SetRemediationProvider sets the remediation provider

func (*DefaultDetectionEngine) SetStandardMappingProvider

func (e *DefaultDetectionEngine) SetStandardMappingProvider(provider StandardMappingProvider)

SetStandardMappingProvider sets the standard mapping provider

type DefaultEmbeddingService

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

DefaultEmbeddingService is the default implementation of the EmbeddingService interface

func NewEmbeddingService

func NewEmbeddingService(provider EmbeddingProvider) *DefaultEmbeddingService

NewEmbeddingService creates a new embedding service

func (*DefaultEmbeddingService) GetEmbedding

func (s *DefaultEmbeddingService) GetEmbedding(ctx context.Context, text string) ([]float64, error)

GetEmbedding gets an embedding for a text

func (*DefaultEmbeddingService) GetSimilarity

func (s *DefaultEmbeddingService) GetSimilarity(ctx context.Context, text1, text2 string) (float64, error)

GetSimilarity gets the similarity between two texts

type DefaultRemediationProvider

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

DefaultRemediationProvider is the default implementation of the RemediationProvider interface

func NewRemediationProvider

func NewRemediationProvider() *DefaultRemediationProvider

NewRemediationProvider creates a new remediation provider

func (*DefaultRemediationProvider) GetRemediation

func (p *DefaultRemediationProvider) GetRemediation(ctx context.Context, result *DetectionResult) (string, error)

GetRemediation gets a remediation suggestion for a detected vulnerability

func (*DefaultRemediationProvider) RegisterRemediation

func (p *DefaultRemediationProvider) RegisterRemediation(vulnType VulnerabilityType, remediation string)

RegisterRemediation registers a remediation suggestion

type DefaultStandardMappingProvider

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

DefaultStandardMappingProvider is the default implementation of the StandardMappingProvider interface

func NewStandardMappingProvider

func NewStandardMappingProvider() *DefaultStandardMappingProvider

NewStandardMappingProvider creates a new standard mapping provider

func (*DefaultStandardMappingProvider) GetStandardMappings

func (p *DefaultStandardMappingProvider) GetStandardMappings(ctx context.Context, vulnType VulnerabilityType, severity SeverityLevel) ([]StandardMapping, error)

GetStandardMappings gets standard mappings for a detected vulnerability

func (*DefaultStandardMappingProvider) RegisterMapping

func (p *DefaultStandardMappingProvider) RegisterMapping(vulnType VulnerabilityType, severity SeverityLevel, mapping StandardMapping)

RegisterMapping registers a standard mapping

type DetectionCriteria

type DetectionCriteria struct {
	// Type is the type of detection method to use
	Type DetectionMethod `json:"type"`
	// Pattern is the pattern to match (for regex_match)
	Pattern string `json:"pattern,omitempty"`
	// Match is the string to match (for string_match)
	Match string `json:"match,omitempty"`
	// Criteria is the criteria for semantic matching (for semantic_match)
	Criteria string `json:"criteria,omitempty"`
	// FunctionName is the name of the custom function to use (for custom_function)
	FunctionName string `json:"function_name,omitempty"`
	// Condition is the condition to apply (e.g., "contains", "not_contains")
	Condition string `json:"condition,omitempty"`
	// Threshold is the threshold for semantic matching (0-100)
	Threshold int `json:"threshold,omitempty"`
	// CaseSensitive indicates whether the match should be case-sensitive
	CaseSensitive bool `json:"case_sensitive,omitempty"`
	// Context provides additional context for the detection
	Context map[string]interface{} `json:"context,omitempty"`
}

DetectionCriteria represents the criteria for detecting a vulnerability

type DetectionEngine

type DetectionEngine interface {
	// RegisterDetector registers a vulnerability detector
	RegisterDetector(detector VulnerabilityDetector)
	// GetDetector gets a detector by name
	GetDetector(name string) (VulnerabilityDetector, bool)
	// ListDetectors lists all registered detectors
	ListDetectors() []string
	// Detect detects vulnerabilities in an LLM response using all registered detectors
	Detect(ctx context.Context, response string, criteria []DetectionCriteria) ([]*DetectionResult, error)
	// DetectWithDetector detects vulnerabilities in an LLM response using a specific detector
	DetectWithDetector(ctx context.Context, response string, criteria DetectionCriteria, detectorName string) (*DetectionResult, error)
}

DetectionEngine is the main interface for the vulnerability detection engine

type DetectionHook

type DetectionHook func(ctx context.Context, response string, criteria DetectionCriteria, result *DetectionResult) error

DetectionHook is a function that runs before or after detection

type DetectionInput

type DetectionInput struct {
	Template management.Template    `json:"template"`
	Provider provider.Provider      `json:"provider"`
	Request  *provider.Request      `json:"request,omitempty"`
	Response *provider.Response     `json:"response,omitempty"`
	Context  map[string]interface{} `json:"context,omitempty"`
}

DetectionInput represents input for vulnerability detection

type DetectionMethod

type DetectionMethod string

DetectionMethod represents the method used to detect a vulnerability

const (
	StringMatch    DetectionMethod = "string_match"
	RegexMatch     DetectionMethod = "regex_match"
	SemanticMatch  DetectionMethod = "semantic_match"
	CustomFunction DetectionMethod = "custom_function"
	HybridMatch    DetectionMethod = "hybrid_match"
)

Standard detection methods

type DetectionResult

type DetectionResult struct {
	// Detected indicates whether a vulnerability was detected
	Detected bool `json:"detected"`
	// VulnerabilityType is the type of vulnerability detected
	VulnerabilityType VulnerabilityType `json:"vulnerability_type"`
	// Severity is the severity level of the detected vulnerability
	Severity SeverityLevel `json:"severity"`
	// ConfidenceScore is the confidence score of the detection (0-100)
	ConfidenceScore int `json:"confidence_score"`
	// DetectionMethod is the method used to detect the vulnerability
	DetectionMethod DetectionMethod `json:"detection_method"`
	// StandardMappings maps the vulnerability to standard security frameworks
	StandardMappings []StandardMapping `json:"standard_mappings,omitempty"`
	// MatchedContent is the content that matched the detection criteria
	MatchedContent []string `json:"matched_content,omitempty"`
	// Context provides additional context about the detection
	Context map[string]interface{} `json:"context,omitempty"`
	// Timestamp is the time when the detection occurred
	Timestamp time.Time `json:"timestamp"`
	// RemediationSuggestion provides suggestions for remediation
	RemediationSuggestion string `json:"remediation_suggestion,omitempty"`
}

DetectionResult represents the result of a vulnerability detection

type Detector

type Detector interface {
	Detect(ctx context.Context, input *DetectionInput) (*Result, error)
	GetType() string
	GetSeverity() string
}

Detector interface for specific vulnerability detectors

type EmbeddingProvider

type EmbeddingProvider interface {
	// GetEmbedding gets an embedding for a text
	GetEmbedding(ctx context.Context, text string) ([]float64, error)
	// GetName returns the name of the provider
	GetName() string
}

EmbeddingProvider is the interface for generating embeddings

type EmbeddingService

type EmbeddingService interface {
	// GetEmbedding gets an embedding for a text
	GetEmbedding(ctx context.Context, text string) ([]float64, error)
	// GetSimilarity gets the similarity between two texts
	GetSimilarity(ctx context.Context, text1, text2 string) (float64, error)
}

EmbeddingService is the interface for generating embeddings

type Engine

type Engine interface {
	Execute(ctx context.Context, template management.Template, provider provider.Provider) (*Result, error)
	Validate(template management.Template) error
	GetSupportedTemplateTypes() []string
}

Engine interface for vulnerability detection

type Factory

type Factory struct{}

Factory is a factory for creating detection engine components

func NewFactory

func NewFactory() *Factory

NewFactory creates a new factory

func (*Factory) CreateDetectionEngine

func (f *Factory) CreateDetectionEngine() *DefaultDetectionEngine

CreateDetectionEngine creates a new detection engine with all standard components

func (*Factory) CreateEmbeddingService

func (f *Factory) CreateEmbeddingService(provider EmbeddingProvider) *DefaultEmbeddingService

CreateEmbeddingService creates a new embedding service

func (*Factory) CreateHybridMatcher

func (f *Factory) CreateHybridMatcher(semanticMatcher *SemanticMatcher) *HybridMatcher

CreateHybridMatcher creates a new hybrid matcher

func (*Factory) CreateMockEmbeddingProvider

func (f *Factory) CreateMockEmbeddingProvider() *MockEmbeddingProvider

CreateMockEmbeddingProvider creates a new mock embedding provider

func (*Factory) CreateRegexMatcher

func (f *Factory) CreateRegexMatcher() *RegexMatcher

CreateRegexMatcher creates a new regex matcher

func (*Factory) CreateRemediationProvider

func (f *Factory) CreateRemediationProvider() *DefaultRemediationProvider

CreateRemediationProvider creates a new remediation provider

func (*Factory) CreateSemanticMatcher

func (f *Factory) CreateSemanticMatcher(embeddingService EmbeddingService) *SemanticMatcher

CreateSemanticMatcher creates a new semantic matcher

func (*Factory) CreateStandardMappingProvider

func (f *Factory) CreateStandardMappingProvider() *DefaultStandardMappingProvider

CreateStandardMappingProvider creates a new standard mapping provider

func (*Factory) CreateStringMatcher

func (f *Factory) CreateStringMatcher() *StringMatcher

CreateStringMatcher creates a new string matcher

type HybridMatcher

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

HybridMatcher is a detector that combines multiple detection methods

func NewHybridMatcher

func NewHybridMatcher(semanticMatcher *SemanticMatcher) *HybridMatcher

NewHybridMatcher creates a new hybrid matcher

func (*HybridMatcher) Detect

func (d *HybridMatcher) Detect(ctx context.Context, response string, criteria DetectionCriteria) (*DetectionResult, error)

Detect detects vulnerabilities in an LLM response

func (*HybridMatcher) Name

func (d *HybridMatcher) Name() string

Name returns the name of the detector

type MockEmbeddingProvider

type MockEmbeddingProvider struct{}

MockEmbeddingProvider is a mock implementation of the EmbeddingProvider interface

func NewMockEmbeddingProvider

func NewMockEmbeddingProvider() *MockEmbeddingProvider

NewMockEmbeddingProvider creates a new mock embedding provider

func (*MockEmbeddingProvider) GetEmbedding

func (p *MockEmbeddingProvider) GetEmbedding(ctx context.Context, text string) ([]float64, error)

GetEmbedding gets a mock embedding for a text

func (*MockEmbeddingProvider) GetName

func (p *MockEmbeddingProvider) GetName() string

GetName returns the name of the provider

type RegexMatcher

type RegexMatcher struct{}

RegexMatcher is a detector that matches regex patterns in LLM responses

func NewRegexMatcher

func NewRegexMatcher() *RegexMatcher

NewRegexMatcher creates a new regex matcher

func (*RegexMatcher) Detect

func (d *RegexMatcher) Detect(ctx context.Context, response string, criteria DetectionCriteria) (*DetectionResult, error)

Detect detects vulnerabilities in an LLM response

func (*RegexMatcher) Name

func (d *RegexMatcher) Name() string

Name returns the name of the detector

type RemediationProvider

type RemediationProvider interface {
	// GetRemediation gets a remediation suggestion for a detected vulnerability
	GetRemediation(ctx context.Context, result *DetectionResult) (string, error)
}

RemediationProvider is the interface for providing remediation suggestions

type Result

type Result struct {
	VulnerabilityDetected bool                   `json:"vulnerability_detected"`
	Title                 string                 `json:"title,omitempty"`
	Description           string                 `json:"description,omitempty"`
	Severity              string                 `json:"severity,omitempty"`
	Category              string                 `json:"category,omitempty"`
	Evidence              map[string]interface{} `json:"evidence,omitempty"`
	Remediation           string                 `json:"remediation,omitempty"`
	Confidence            float64                `json:"confidence,omitempty"`
	Timestamp             time.Time              `json:"timestamp"`
	Metadata              map[string]interface{} `json:"metadata,omitempty"`
}

Result represents the result of a vulnerability detection

type SemanticMatcher

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

SemanticMatcher is a detector that performs semantic matching on LLM responses

func NewSemanticMatcher

func NewSemanticMatcher(embedder EmbeddingService) *SemanticMatcher

NewSemanticMatcher creates a new semantic matcher

func (*SemanticMatcher) Detect

func (d *SemanticMatcher) Detect(ctx context.Context, response string, criteria DetectionCriteria) (*DetectionResult, error)

Detect detects vulnerabilities in an LLM response

func (*SemanticMatcher) Name

func (d *SemanticMatcher) Name() string

Name returns the name of the detector

type SeverityLevel

type SeverityLevel string

SeverityLevel represents the severity of a detected vulnerability

const (
	Critical SeverityLevel = "critical"
	High     SeverityLevel = "high"
	Medium   SeverityLevel = "medium"
	Low      SeverityLevel = "low"
	Info     SeverityLevel = "info"
)

Standard severity levels

type StandardMapping

type StandardMapping struct {
	// Standard is the name of the standard (e.g., "OWASP Top 10 for LLMs", "ISO/IEC 42001")
	Standard string `json:"standard"`
	// ID is the identifier within the standard (e.g., "LLM01", "8.2.3")
	ID string `json:"id"`
	// Name is the name of the item within the standard
	Name string `json:"name"`
	// URL is a link to more information about the standard item
	URL string `json:"url,omitempty"`
}

StandardMapping represents a mapping to a standard security framework

type StandardMappingProvider

type StandardMappingProvider interface {
	// GetStandardMappings gets standard mappings for a detected vulnerability
	GetStandardMappings(ctx context.Context, vulnType VulnerabilityType, severity SeverityLevel) ([]StandardMapping, error)
}

StandardMappingProvider is the interface for mapping vulnerabilities to standards

type StringMatcher

type StringMatcher struct{}

StringMatcher is a detector that matches strings in LLM responses

func NewStringMatcher

func NewStringMatcher() *StringMatcher

NewStringMatcher creates a new string matcher

func (*StringMatcher) Detect

func (d *StringMatcher) Detect(ctx context.Context, response string, criteria DetectionCriteria) (*DetectionResult, error)

Detect detects vulnerabilities in an LLM response

func (*StringMatcher) Name

func (d *StringMatcher) Name() string

Name returns the name of the detector

type Template

type Template struct {
	ID   string
	Info TemplateInfo
	Test TemplateTest
}

Template represents a simplified template structure

type TemplateDetection

type TemplateDetection struct {
	Type      string
	Match     string
	Pattern   string
	Criteria  string
	Condition string
}

TemplateDetection represents detection criteria in a template

type TemplateInfo

type TemplateInfo struct {
	ID          string
	Name        string
	Description string
	Severity    string
	Tags        []string
	Compliance  struct {
		OWASP string
		ISO   string
	}
}

TemplateInfo represents template information

type TemplateIntegration

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

TemplateIntegration provides integration with template systems

func NewTemplateIntegration

func NewTemplateIntegration(engine DetectionEngine) *TemplateIntegration

NewTemplateIntegration creates a new template integration

func (*TemplateIntegration) BatchDetectFromTemplates

func (i *TemplateIntegration) BatchDetectFromTemplates(ctx context.Context, templates []*Template, response string) ([]*TemplateResult, error)

BatchDetectFromTemplates detects vulnerabilities using multiple templates

func (*TemplateIntegration) ConvertTemplateToCriteria

func (i *TemplateIntegration) ConvertTemplateToCriteria(template *Template) ([]DetectionCriteria, error)

ConvertTemplateToCriteria converts a template to detection criteria

func (*TemplateIntegration) DetectFromTemplate

func (i *TemplateIntegration) DetectFromTemplate(ctx context.Context, template *Template, response string) (*TemplateResult, error)

DetectFromTemplate detects vulnerabilities using a template

type TemplateResult

type TemplateResult struct {
	TemplateID string
	Status     string
	StartTime  time.Time
	EndTime    time.Time
	Duration   time.Duration
	Error      error
	Response   string
	Detected   bool
	Score      int
	Details    map[string]interface{}
}

TemplateResult represents the result of a template execution

type TemplateTest

type TemplateTest struct {
	Prompt     string
	Detection  TemplateDetection
	Variations []TemplateVariation
}

TemplateTest represents the test section of a template

type TemplateVariation

type TemplateVariation struct {
	Prompt    string
	Detection TemplateDetection
}

TemplateVariation represents a variation of a template test

type VulnerabilityDetector

type VulnerabilityDetector interface {
	// Detect detects vulnerabilities in an LLM response
	Detect(ctx context.Context, response string, criteria DetectionCriteria) (*DetectionResult, error)
	// Name returns the name of the detector
	Name() string
}

VulnerabilityDetector is the interface for detecting vulnerabilities in LLM responses

type VulnerabilityType

type VulnerabilityType string

VulnerabilityType represents the type of vulnerability detected

const (
	// Prompt injection vulnerabilities
	PromptInjection VulnerabilityType = "prompt_injection"
	// Sensitive information disclosure
	SensitiveInfoDisclosure VulnerabilityType = "sensitive_info_disclosure"
	// Jailbreak attempts
	Jailbreak VulnerabilityType = "jailbreak"
	// Harmful content generation
	HarmfulContent VulnerabilityType = "harmful_content"
	// Insecure code generation
	InsecureCode VulnerabilityType = "insecure_code"
	// Data poisoning
	DataPoisoning VulnerabilityType = "data_poisoning"
	// Model denial of service
	ModelDoS VulnerabilityType = "model_dos"
	// Indirect prompt injection
	IndirectPromptInjection VulnerabilityType = "indirect_prompt_injection"
	// Unauthorized access
	UnauthorizedAccess VulnerabilityType = "unauthorized_access"
	// Overreliance
	Overreliance VulnerabilityType = "overreliance"
)

Standard vulnerability types

Jump to

Keyboard shortcuts

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