fuzzer

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package fuzzer provides the core fuzzing engine

Package fuzzer provides the core fuzzing engine

Package fuzzer provides the core fuzzing engine

Package fuzzer provides the core fuzzing engine

Package fuzzer provides the core fuzzing engine

Package fuzzer provides the core fuzzing engine

Index

Constants

This section is empty.

Variables

View Source
var AutoExtractionPatterns = []struct {
	Name         string
	Pattern      *regexp.Regexp
	ResourceType string
}{
	{
		Name:         "uuid",
		Pattern:      regexp.MustCompile(`"(?:id|uuid|_id)":\s*"([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})"`),
		ResourceType: "id",
	},
	{
		Name:         "numeric_id",
		Pattern:      regexp.MustCompile(`"(?:id|user_id|order_id|product_id|account_id)":\s*(\d+)`),
		ResourceType: "id",
	},
	{
		Name:         "jwt_token",
		Pattern:      regexp.MustCompile(`"(?:token|access_token|jwt|auth_token)":\s*"(eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]*)"`),
		ResourceType: "token",
	},
	{
		Name:         "bearer_token",
		Pattern:      regexp.MustCompile(`"(?:bearer|access_token)":\s*"([a-zA-Z0-9_-]{20,})"`),
		ResourceType: "token",
	},
	{
		Name:         "api_key",
		Pattern:      regexp.MustCompile(`"(?:api_key|apiKey|api-key)":\s*"([a-zA-Z0-9_-]{16,})"`),
		ResourceType: "api_key",
	},
	{
		Name:         "session_id",
		Pattern:      regexp.MustCompile(`"(?:session|session_id|sessionId)":\s*"([a-zA-Z0-9_-]{16,})"`),
		ResourceType: "session",
	},
	{
		Name:         "csrf_token",
		Pattern:      regexp.MustCompile(`"(?:csrf|csrf_token|_csrf)":\s*"([a-zA-Z0-9_-]{16,})"`),
		ResourceType: "csrf",
	},
	{
		Name:         "refresh_token",
		Pattern:      regexp.MustCompile(`"(?:refresh_token|refreshToken)":\s*"([a-zA-Z0-9_-]{20,})"`),
		ResourceType: "refresh_token",
	},
}

AutoExtractionPatterns contains patterns for auto-extraction

Functions

func ApplyContextToRequest

func ApplyContextToRequest(req *http.Request, authCtx types.AuthContext)

ApplyContextToRequest applies an auth context to an http.Request

func CompareContextResults

func CompareContextResults(resultA, resultB *FuzzResult) []string

CompareContextResults compares results between two auth contexts

func FilterWebSocketRequests added in v1.4.0

func FilterWebSocketRequests(requests []payloads.FuzzRequest) (httpReqs, wsReqs []payloads.FuzzRequest)

FilterWebSocketRequests separates WebSocket-tagged requests from HTTP requests

Types

type AdaptiveRateLimiter

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

AdaptiveRateLimiter adjusts rate based on response

func NewAdaptiveRateLimiter

func NewAdaptiveRateLimiter(baseRate, minRate, maxRate float64) *AdaptiveRateLimiter

NewAdaptiveRateLimiter creates an adaptive rate limiter

func (*AdaptiveRateLimiter) CurrentRate

func (a *AdaptiveRateLimiter) CurrentRate() float64

CurrentRate returns the current rate

func (*AdaptiveRateLimiter) RecordError

func (a *AdaptiveRateLimiter) RecordError(statusCode int)

RecordError records a failed request

func (*AdaptiveRateLimiter) RecordResponseHeaders added in v1.4.0

func (a *AdaptiveRateLimiter) RecordResponseHeaders(headers map[string]string)

RecordResponseHeaders parses rate-limit headers and adjusts rate accordingly

func (*AdaptiveRateLimiter) RecordResponseTime added in v1.4.0

func (a *AdaptiveRateLimiter) RecordResponseTime(d time.Duration)

RecordResponseTime records a response time and adjusts rate if p95 exceeds threshold

func (*AdaptiveRateLimiter) RecordSuccess

func (a *AdaptiveRateLimiter) RecordSuccess()

RecordSuccess records a successful request

func (*AdaptiveRateLimiter) SetBaselineResponseTime added in v1.4.0

func (a *AdaptiveRateLimiter) SetBaselineResponseTime(d time.Duration)

SetBaselineResponseTime sets the baseline response time for adaptive throttling

func (*AdaptiveRateLimiter) Wait

Wait waits until a request can be made

type AuthHandler

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

AuthHandler handles authentication flows

func NewAuthHandler

func NewAuthHandler(session *SessionManager, config *types.AuthConfig) *AuthHandler

NewAuthHandler creates a new auth handler

func (*AuthHandler) ConfigureAuth

func (h *AuthHandler) ConfigureAuth()

ConfigureAuth configures authentication based on the auth config

type CacheConfig

type CacheConfig struct {
	MaxSize         int           // Maximum number of cached responses
	TTL             time.Duration // Time-to-live for cache entries
	DedupeEnabled   bool          // Enable request deduplication
	BaselineEnabled bool          // Enable baseline caching
}

CacheConfig holds cache configuration

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig returns default cache configuration

type CacheStats

type CacheStats struct {
	BaselineEntries int
	ResponseEntries int
	Fingerprints    int
}

CacheStats holds cache statistics

type CachedBaseline

type CachedBaseline struct {
	Response  *types.HTTPResponse
	Timestamp time.Time
	Endpoint  string
}

CachedBaseline represents a cached baseline response

type CachedResponse

type CachedResponse struct {
	Response  *types.HTTPResponse
	Timestamp time.Time
	HitCount  int
}

CachedResponse represents a cached response for a specific request

type ComparisonResult

type ComparisonResult struct {
	StatusCodeMatch   bool
	StatusCodeDiff    int
	ContentLengthDiff int64
	BodySimilarity    float64
	HeaderChanges     []string
	IsAnomaly         bool
	TimeDiff          time.Duration
}

ComparisonResult holds the comparison between baseline and fuzzed response

type DryRunSimulator

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

DryRunSimulator simulates fuzzing without making actual requests

func NewDryRunSimulator

func NewDryRunSimulator() *DryRunSimulator

NewDryRunSimulator creates a simulator for dry run mode

func (*DryRunSimulator) GetSummary

func (d *DryRunSimulator) GetSummary(results []SimulateResult) *DryRunSummary

GetSummary returns a summary of the dry run

func (*DryRunSimulator) GroupByEndpoint

func (d *DryRunSimulator) GroupByEndpoint(results []SimulateResult) map[string][]SimulateResult

GroupByEndpoint groups simulation results by endpoint

func (*DryRunSimulator) Simulate

func (d *DryRunSimulator) Simulate(requests []payloads.FuzzRequest) []SimulateResult

Simulate returns what would be tested without making requests

type DryRunSummary

type DryRunSummary struct {
	TotalRequests   int
	UniqueEndpoints int
	ByAttackType    map[string]int
	ByEndpoint      map[string]int
	ByParameter     map[string]int
}

Summary returns a summary of what would be tested

type Engine

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

Engine is the core fuzzing engine

func NewEngine

func NewEngine(config types.Config) *Engine

NewEngine creates a new fuzzing engine

func (*Engine) Client added in v1.3.0

func (e *Engine) Client() *http.Client

Client returns the underlying HTTP client for use by passive checks.

func (*Engine) Fuzz

func (e *Engine) Fuzz(ctx context.Context, requests []payloads.FuzzRequest) <-chan *FuzzResult

Fuzz starts fuzzing the given requests

func (*Engine) GetBaseline

func (e *Engine) GetBaseline(ctx context.Context, endpoint types.Endpoint) (*types.HTTPResponse, error)

GetBaseline fetches a baseline response for comparison

func (*Engine) GetStats

func (e *Engine) GetStats() *Stats

GetStats returns current statistics

type ExtractionRule

type ExtractionRule struct {
	Name       string `yaml:"name" json:"name"`
	Type       string `yaml:"type" json:"type"`               // json, regex, header, cookie
	Path       string `yaml:"path" json:"path"`               // JSONPath for json type
	Pattern    string `yaml:"pattern" json:"pattern"`         // Regex pattern for regex type
	HeaderName string `yaml:"header_name" json:"header_name"` // Header name for header type
	CookieName string `yaml:"cookie_name" json:"cookie_name"` // Cookie name for cookie type
	SaveAs     string `yaml:"save_as" json:"save_as"`         // Variable name to save as
	Group      int    `yaml:"group" json:"group"`             // Regex capture group (default 0)
}

ExtractionRule defines how to extract data from a response

type Extractor

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

Extractor extracts data from HTTP responses

func NewExtractor

func NewExtractor(state *StateTracker, autoExtract bool) *Extractor

NewExtractor creates a new extractor

func (*Extractor) AddRule

func (e *Extractor) AddRule(rule ExtractionRule)

AddRule adds an extraction rule

func (*Extractor) AddRules

func (e *Extractor) AddRules(rules []ExtractionRule)

AddRules adds multiple extraction rules

func (*Extractor) ExtractFromResponse

func (e *Extractor) ExtractFromResponse(resp *types.HTTPResponse, endpoint string) map[string]string

ExtractFromResponse extracts data from an HTTP response

func (*Extractor) GetRules

func (e *Extractor) GetRules() []ExtractionRule

GetRules returns the configured extraction rules

func (*Extractor) LoadRulesFromYAML

func (e *Extractor) LoadRulesFromYAML(data []byte) error

LoadRulesFromYAML loads extraction rules from YAML content

type FuzzResult

type FuzzResult struct {
	Request       *payloads.FuzzRequest
	ActualRequest *types.HTTPRequest // The actual HTTP request that was sent (with payload, session headers, etc.)
	Response      *types.HTTPResponse
	Baseline      *types.HTTPResponse
	Error         error
	Duration      time.Duration
	Timestamp     time.Time
}

FuzzResult represents the result of a fuzz request

type LogEntry

type LogEntry struct {
	Timestamp    time.Time       `json:"timestamp"`
	RequestNum   int             `json:"request_num"`
	Method       string          `json:"method"`
	URL          string          `json:"url"`
	Endpoint     string          `json:"endpoint"`
	Parameter    string          `json:"parameter,omitempty"`
	PayloadType  string          `json:"payload_type,omitempty"`
	PayloadValue string          `json:"payload_value,omitempty"`
	Request      *LoggedRequest  `json:"request,omitempty"`
	Response     *LoggedResponse `json:"response,omitempty"`
	Duration     string          `json:"duration"`
	Error        string          `json:"error,omitempty"`
}

LogEntry represents a logged request/response pair

type LoggedRequest

type LoggedRequest struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    string            `json:"body,omitempty"`
}

LoggedRequest contains request details for logging

type LoggedResponse

type LoggedResponse struct {
	StatusCode    int               `json:"status_code"`
	Status        string            `json:"status"`
	Headers       map[string]string `json:"headers,omitempty"`
	ContentLength int64             `json:"content_length"`
	ResponseTime  string            `json:"response_time"`
	BodyPreview   string            `json:"body_preview,omitempty"`
}

LoggedResponse contains response details for logging

type MultiAuthExecutor

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

MultiAuthExecutor executes requests with multiple auth contexts

func NewMultiAuthExecutor

func NewMultiAuthExecutor(engine *Engine, contexts []types.AuthContext) *MultiAuthExecutor

NewMultiAuthExecutor creates a new multi-auth executor

func (*MultiAuthExecutor) ExecuteWithContexts

func (mae *MultiAuthExecutor) ExecuteWithContexts(ctx context.Context, req payloads.FuzzRequest) *MultiAuthResult

ExecuteWithContexts executes a request with all auth contexts

func (*MultiAuthExecutor) FuzzWithContexts

func (mae *MultiAuthExecutor) FuzzWithContexts(ctx context.Context, requests []payloads.FuzzRequest) <-chan *MultiAuthResult

FuzzWithContexts fuzzes all endpoints with all auth contexts

func (*MultiAuthExecutor) GetContexts

func (mae *MultiAuthExecutor) GetContexts() []types.AuthContext

GetContexts returns the auth contexts

func (*MultiAuthExecutor) GetResults

func (mae *MultiAuthExecutor) GetResults() map[string]map[string]*FuzzResult

GetResults returns all stored results

type MultiAuthResult

type MultiAuthResult struct {
	Endpoint types.Endpoint
	Results  map[string]*FuzzResult // context name -> result
}

MultiAuthResult represents the result of multi-auth execution

type RateLimiter

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

RateLimiter controls request rate

func NewRateLimiter

func NewRateLimiter(requestsPerSecond float64) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (r *RateLimiter) Allow() bool

Allow checks if a request is allowed

func (*RateLimiter) SetRate

func (r *RateLimiter) SetRate(requestsPerSecond float64)

SetRate updates the rate limit

func (*RateLimiter) Wait

func (r *RateLimiter) Wait(ctx context.Context) error

Wait waits until a request can be made

type RequestCache

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

RequestCache provides caching and deduplication for fuzz requests

func NewRequestCache

func NewRequestCache(config *CacheConfig) *RequestCache

NewRequestCache creates a new request cache

func (*RequestCache) CacheResponse

func (c *RequestCache) CacheResponse(req payloads.FuzzRequest, response *types.HTTPResponse)

CacheResponse caches a response for a request

func (*RequestCache) Cleanup

func (c *RequestCache) Cleanup()

Cleanup removes expired entries

func (*RequestCache) GetBaseline

func (c *RequestCache) GetBaseline(endpoint types.Endpoint) (*types.HTTPResponse, bool)

GetBaseline retrieves a cached baseline for an endpoint

func (*RequestCache) GetCachedResponse

func (c *RequestCache) GetCachedResponse(req payloads.FuzzRequest) (*types.HTTPResponse, bool)

GetCachedResponse retrieves a cached response for a request

func (*RequestCache) IsDuplicate

func (c *RequestCache) IsDuplicate(req payloads.FuzzRequest) bool

IsDuplicate checks if a request has already been made

func (*RequestCache) MarkSeen

func (c *RequestCache) MarkSeen(req payloads.FuzzRequest)

MarkSeen marks a request as seen

func (*RequestCache) SetBaseline

func (c *RequestCache) SetBaseline(endpoint types.Endpoint, response *types.HTTPResponse)

SetBaseline caches a baseline response

func (*RequestCache) Stats

func (c *RequestCache) Stats() CacheStats

Stats returns cache statistics

type RequestDeduplicator

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

RequestDeduplicator deduplicates a list of fuzz requests

func NewRequestDeduplicator

func NewRequestDeduplicator() *RequestDeduplicator

NewRequestDeduplicator creates a new deduplicator

func (*RequestDeduplicator) Deduplicate

func (d *RequestDeduplicator) Deduplicate(requests []payloads.FuzzRequest) []payloads.FuzzRequest

Deduplicate removes duplicate requests from a list

func (*RequestDeduplicator) RemovedCount

func (d *RequestDeduplicator) RemovedCount(originalCount int) int

RemovedCount returns the number of duplicates removed

type RequestInterceptor

type RequestInterceptor func(*http.Request) error

RequestInterceptor can modify requests before they are sent

type RequestLogger

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

RequestLogger logs HTTP requests and responses to a file

func NewRequestLogger

func NewRequestLogger(filePath string) (*RequestLogger, error)

NewRequestLogger creates a new request logger

func (*RequestLogger) Close

func (l *RequestLogger) Close() error

Close closes the log file

func (*RequestLogger) Count

func (l *RequestLogger) Count() int

Count returns the number of logged entries

func (*RequestLogger) Log

func (l *RequestLogger) Log(result *FuzzResult) error

Log writes a request/response to the log file

type ResponseComparator

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

ResponseComparator compares responses to detect anomalies

func NewResponseComparator

func NewResponseComparator(threshold float64) *ResponseComparator

NewResponseComparator creates a new response comparator

func (*ResponseComparator) Compare

func (c *ResponseComparator) Compare(baseline, fuzzed *types.HTTPResponse) *ComparisonResult

Compare compares two responses and returns a similarity score

type ResponseInterceptor

type ResponseInterceptor func(*http.Response) error

ResponseInterceptor can process responses after they are received

type SessionManager

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

SessionManager manages authentication and session state

func NewSessionManager

func NewSessionManager(config types.HTTPSettings) *SessionManager

NewSessionManager creates a new session manager

func (*SessionManager) Apply

func (sm *SessionManager) Apply(req *http.Request)

Apply applies session state to an HTTP request

func (*SessionManager) Clear

func (sm *SessionManager) Clear()

Clear clears all session state

func (*SessionManager) Clone

func (sm *SessionManager) Clone() *SessionManager

Clone creates a copy of the session manager

func (*SessionManager) GetCookie

func (sm *SessionManager) GetCookie(name string) string

GetCookie gets a cookie value

func (*SessionManager) GetHeader

func (sm *SessionManager) GetHeader(name string) string

GetHeader gets a header value

func (*SessionManager) SetAuth

func (sm *SessionManager) SetAuth(authType, token string)

SetAuth sets authentication

func (*SessionManager) SetBasicAuth

func (sm *SessionManager) SetBasicAuth(username, password string)

SetBasicAuth sets basic authentication

func (*SessionManager) SetBearerToken

func (sm *SessionManager) SetBearerToken(token string)

SetBearerToken sets bearer token authentication

func (*SessionManager) SetCookie

func (sm *SessionManager) SetCookie(name, value string)

SetCookie sets a cookie

func (*SessionManager) SetHeader

func (sm *SessionManager) SetHeader(name, value string)

SetHeader sets a header

func (*SessionManager) UpdateFromResponse

func (sm *SessionManager) UpdateFromResponse(resp *http.Response)

UpdateFromResponse updates session state from a response

type SimulateResult

type SimulateResult struct {
	Endpoint    string
	Method      string
	Parameter   string
	Position    string
	PayloadType string
	Payload     string
	Description string
}

SimulateResult describes what would happen for a request

type StateChange

type StateChange struct {
	Action   string // "set", "delete", "extract"
	Key      string
	Value    string
	Source   string // Where it came from (e.g., "response_body", "header")
	Endpoint string
}

StateChange represents a change in state

type StateTracker

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

StateTracker manages stateful session data across requests

func NewStateTracker

func NewStateTracker() *StateTracker

NewStateTracker creates a new state tracker

func (*StateTracker) AddResource

func (st *StateTracker) AddResource(resourceType, id string)

AddResource adds a discovered resource ID

func (*StateTracker) Clear

func (st *StateTracker) Clear()

Clear clears all state

func (*StateTracker) Clone

func (st *StateTracker) Clone() *StateTracker

Clone creates a copy of the state tracker

func (*StateTracker) ExportToJSON

func (st *StateTracker) ExportToJSON() ([]byte, error)

ExportToJSON exports state to JSON

func (*StateTracker) GetAllCookies

func (st *StateTracker) GetAllCookies() map[string]string

GetAllCookies returns all cookies

func (*StateTracker) GetAllVariables

func (st *StateTracker) GetAllVariables() map[string]string

GetAllVariables returns all variables

func (*StateTracker) GetCookie

func (st *StateTracker) GetCookie(name string) (string, bool)

GetCookie gets a cookie

func (*StateTracker) GetHistory

func (st *StateTracker) GetHistory() []StateChange

GetHistory returns state change history

func (*StateTracker) GetLatestResource

func (st *StateTracker) GetLatestResource(resourceType string) (string, bool)

GetLatestResource gets the most recently discovered resource of a type

func (*StateTracker) GetResources

func (st *StateTracker) GetResources(resourceType string) []string

GetResources gets all discovered resources of a type

func (*StateTracker) GetToken

func (st *StateTracker) GetToken(tokenType string) (string, bool)

GetToken gets an authentication token

func (*StateTracker) GetVariable

func (st *StateTracker) GetVariable(name string) (string, bool)

GetVariable gets a state variable

func (*StateTracker) HasUnresolvedVariables

func (st *StateTracker) HasUnresolvedVariables(input string) bool

HasUnresolvedVariables checks if a string has unresolved variables

func (*StateTracker) ImportFromJSON

func (st *StateTracker) ImportFromJSON(data []byte) error

ImportFromJSON imports state from JSON

func (*StateTracker) SetCookie

func (st *StateTracker) SetCookie(name, value string)

SetCookie sets a cookie

func (*StateTracker) SetToken

func (st *StateTracker) SetToken(tokenType, value string)

SetToken sets an authentication token

func (*StateTracker) SetVariable

func (st *StateTracker) SetVariable(name, value string)

SetVariable sets a state variable

func (*StateTracker) SubstituteVariables

func (st *StateTracker) SubstituteVariables(input string) string

SubstituteVariables replaces {{varname}} placeholders in a string

type Stats

type Stats struct {
	TotalRequests  int
	SuccessCount   int
	ErrorCount     int
	AnomalyCount   int
	StartTime      time.Time
	EndTime        time.Time
	RequestsPerSec float64
	// contains filtered or unexported fields
}

Stats tracks fuzzing statistics

type TokenBucket

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

TokenBucket implements a simple token bucket rate limiter

func NewTokenBucket

func NewTokenBucket(maxTokens, refillRate float64) *TokenBucket

NewTokenBucket creates a new token bucket

func (*TokenBucket) Take

func (tb *TokenBucket) Take(n float64) bool

Take attempts to take n tokens, returns true if successful

func (*TokenBucket) TakeWait

func (tb *TokenBucket) TakeWait(ctx context.Context, n float64) error

TakeWait waits until n tokens are available

type WebSocketFuzzer added in v1.4.0

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

WebSocketFuzzer handles fuzzing of WebSocket endpoints

func NewWebSocketFuzzer added in v1.4.0

func NewWebSocketFuzzer(config types.Config) *WebSocketFuzzer

NewWebSocketFuzzer creates a new WebSocket fuzzer

func (*WebSocketFuzzer) Fuzz added in v1.4.0

func (f *WebSocketFuzzer) Fuzz(ctx context.Context, requests []payloads.FuzzRequest) <-chan *FuzzResult

Fuzz executes WebSocket fuzz requests and returns results on a channel

Jump to

Keyboard shortcuts

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