Exploit database

GH-85611a99005868f0176f5dbf39aa5f38

0xsj/cve-2025-55182

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-55182

257 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files6
0xsj/cve-2025-55182Revision 5bf32583b448

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

internal/stress/stress.go

Go · 8,580 bytes
package stress

import (
	"context"
	"errors"
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/0xsj/CVE-2025-55182/internal/types"
)

// DefaultConfig returns sensible defaults for stress testing
func DefaultConfig() types.StressConfig {
	return types.StressConfig{
		Pattern:     types.PatternNextAction,
		Duration:    30 * time.Second,
		Concurrency: 10,
		RampUp:      0,
		RateLimit:   0, // Unlimited
		Timeout:     10 * time.Second,
	}
}

// Tester orchestrates stress testing
type Tester struct {
	config   types.StressConfig
	pattern  Pattern
	metrics  *Metrics
	pool     *WorkerPool
	callback ProgressCallback

	// State
	running bool
	ctx     context.Context
	cancel  context.CancelFunc
}

// ProgressCallback is called periodically with current metrics
type ProgressCallback func(metrics types.StressMetrics, elapsed time.Duration)

// Option configures the Tester
type Option func(*Tester)

// WithCallback sets a progress callback function
func WithCallback(cb ProgressCallback) Option {
	return func(t *Tester) {
		t.callback = cb
	}
}

// WithPattern overrides the pattern from config
func WithPattern(p Pattern) Option {
	return func(t *Tester) {
		t.pattern = p
	}
}

// NewTester creates a new stress tester
func NewTester(config types.StressConfig, opts ...Option) (*Tester, error) {
	// Validate config
	if err := validateConfig(config); err != nil {
		return nil, fmt.Errorf("invalid config: %w", err)
	}

	// Normalize target URL
	target, err := normalizeTarget(config.Target)
	if err != nil {
		return nil, fmt.Errorf("invalid target: %w", err)
	}
	config.Target = target

	t := &Tester{
		config:  config,
		pattern: NewPattern(config.Pattern),
		metrics: NewMetrics(),
	}

	// Apply options
	for _, opt := range opts {
		opt(t)
	}

	return t, nil
}

// validateConfig checks if the configuration is valid
func validateConfig(config types.StressConfig) error {
	if config.Target == "" {
		return errors.New("target is required")
	}

	if config.Duration <= 0 {
		return errors.New("duration must be positive")
	}

	if config.Concurrency <= 0 {
		return errors.New("concurrency must be positive")
	}

	if config.Concurrency > 1000 {
		return errors.New("concurrency exceeds maximum (1000)")
	}

	if config.Timeout <= 0 {
		return errors.New("timeout must be positive")
	}

	if config.RampUp < 0 {
		return errors.New("ramp-up cannot be negative")
	}

	if config.RampUp > config.Duration {
		return errors.New("ramp-up cannot exceed duration")
	}

	if config.RateLimit < 0 {
		return errors.New("rate limit cannot be negative")
	}

	return nil
}

// normalizeTarget ensures the target URL is properly formatted
func normalizeTarget(target string) (string, error) {
	target = strings.TrimSpace(target)

	if target == "" {
		return "", errors.New("empty target")
	}

	// Add scheme if missing
	if !strings.HasPrefix(target, "http://") && !strings.HasPrefix(target, "https://") {
		target = "https://" + target
	}

	// Parse and validate
	parsed, err := url.Parse(target)
	if err != nil {
		return "", err
	}

	if parsed.Host == "" {
		return "", errors.New("missing host")
	}

	// Remove trailing slash for consistency (we add paths later)
	target = strings.TrimSuffix(target, "/")

	return target, nil
}

// Run starts the stress test and blocks until complete
func (t *Tester) Run() (types.StressSummary, error) {
	if t.running {
		return types.StressSummary{}, errors.New("stress test already running")
	}

	t.running = true
	defer func() { t.running = false }()

	// Create cancellable context
	t.ctx, t.cancel = context.WithTimeout(context.Background(), t.config.Duration+time.Minute)
	defer t.cancel()

	// Reset metrics
	t.metrics.Reset()

	// Create worker pool
	t.pool = NewWorkerPool(t.config, t.pattern, t.metrics)

	// Start progress reporter if callback is set
	var progressDone chan struct{}
	if t.callback != nil {
		progressDone = make(chan struct{})
		go t.reportProgress(progressDone)
	}

	// Run the stress test
	err := t.pool.Run()

	// Stop progress reporter
	if progressDone != nil {
		close(progressDone)
	}

	// Generate summary
	summary := t.metrics.Summary()
	summary.Config = t.config

	return summary, err
}

// reportProgress periodically calls the progress callback
func (t *Tester) reportProgress(done chan struct{}) {
	ticker := time.NewTicker(500 * time.Millisecond)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			snapshot := t.metrics.Snapshot()
			elapsed := t.metrics.ElapsedTime()
			t.callback(snapshot, elapsed)
		case <-done:
			return
		case <-t.ctx.Done():
			return
		}
	}
}

// Stop stops the stress test early
func (t *Tester) Stop() {
	if t.cancel != nil {
		t.cancel()
	}
	if t.pool != nil {
		t.pool.Stop()
	}
}

// IsRunning returns whether a stress test is in progress
func (t *Tester) IsRunning() bool {
	return t.running
}

// Metrics returns the current metrics collector
func (t *Tester) Metrics() *Metrics {
	return t.metrics
}

// Config returns the current configuration
func (t *Tester) Config() types.StressConfig {
	return t.config
}

// =============================================================================
// Quick Functions for Simple Usage
// =============================================================================

// QuickTest runs a quick stress test with minimal configuration
func QuickTest(target string, duration time.Duration, concurrency int) (types.StressSummary, error) {
	config := DefaultConfig()
	config.Target = target
	config.Duration = duration
	config.Concurrency = concurrency

	tester, err := NewTester(config)
	if err != nil {
		return types.StressSummary{}, err
	}

	return tester.Run()
}

// SimulateScanner simulates the next-action scanner attack
func SimulateScanner(target string, duration time.Duration, concurrency int, progressCb ProgressCallback) (types.StressSummary, error) {
	config := types.StressConfig{
		Target:      target,
		Pattern:     types.PatternNextAction,
		Duration:    duration,
		Concurrency: concurrency,
		RampUp:      5 * time.Second, // Gradual ramp-up like real scanner
		RateLimit:   0,               // Unlimited
		Timeout:     10 * time.Second,
	}

	opts := []Option{}
	if progressCb != nil {
		opts = append(opts, WithCallback(progressCb))
	}

	tester, err := NewTester(config, opts...)
	if err != nil {
		return types.StressSummary{}, err
	}

	return tester.Run()
}

// HeavyLoad runs an aggressive stress test
func HeavyLoad(target string, duration time.Duration, concurrency int, rps int, progressCb ProgressCallback) (types.StressSummary, error) {
	config := types.StressConfig{
		Target:      target,
		Pattern:     types.PatternMixed,
		Duration:    duration,
		Concurrency: concurrency,
		RampUp:      10 * time.Second,
		RateLimit:   rps,
		Timeout:     30 * time.Second,
	}

	opts := []Option{}
	if progressCb != nil {
		opts = append(opts, WithCallback(progressCb))
	}

	tester, err := NewTester(config, opts...)
	if err != nil {
		return types.StressSummary{}, err
	}

	return tester.Run()
}

// =============================================================================
// Utility Functions
// =============================================================================

// EstimateRequests estimates the number of requests for given config
func EstimateRequests(config types.StressConfig) int64 {
	// Rough estimate: assume ~100 requests/second per worker without rate limit
	perWorkerRPS := 100.0

	if config.RateLimit > 0 {
		// Rate limited: total RPS is the limit
		return int64(float64(config.RateLimit) * config.Duration.Seconds())
	}

	// Unlimited: estimate based on concurrency
	totalRPS := perWorkerRPS * float64(config.Concurrency)
	return int64(totalRPS * config.Duration.Seconds())
}

// FormatDuration formats a duration for display
func FormatDuration(d time.Duration) string {
	if d < time.Millisecond {
		return fmt.Sprintf("%.2fµs", float64(d.Microseconds()))
	}
	if d < time.Second {
		return fmt.Sprintf("%.2fms", float64(d.Milliseconds()))
	}
	return fmt.Sprintf("%.2fs", d.Seconds())
}

// FormatBytes formats bytes for display
func FormatBytes(b int64) string {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
	)

	switch {
	case b >= GB:
		return fmt.Sprintf("%.2f GB", float64(b)/GB)
	case b >= MB:
		return fmt.Sprintf("%.2f MB", float64(b)/MB)
	case b >= KB:
		return fmt.Sprintf("%.2f KB", float64(b)/KB)
	default:
		return fmt.Sprintf("%d B", b)
	}
}

// FormatRate formats requests per second for display
func FormatRate(rps float64) string {
	if rps >= 1000 {
		return fmt.Sprintf("%.2fk req/s", rps/1000)
	}
	return fmt.Sprintf("%.2f req/s", rps)
}