getName()} v{$mlWafLayer->getVersion()}\n\n"; // ======================================== // 2. Simulate Normal Traffic Pattern // ======================================== echo "2. Simulating normal traffic pattern...\n"; $normalIp = new IpAddress('203.0.113.10'); for ($i = 1; $i <= 10; $i++) { $request = createMockRequest($normalIp, "/page-{$i}", 'GET'); $historyTracker->track($request); sleep(1); // Normal timing } $normalSequence = $historyTracker->getSequence($normalIp); echo "✓ Tracked {$normalSequence->count()} normal requests\n"; $normalFeatures = $patternExtractor->extract($normalSequence); echo " Features extracted:\n"; echo " - Request Frequency: " . round($normalFeatures->requestFrequency, 2) . " req/s\n"; echo " - Endpoint Diversity: " . round($normalFeatures->endpointDiversity, 2) . "\n"; echo " - User-Agent Consistency: " . round($normalFeatures->userAgentConsistency, 2) . "\n\n"; $normalAnomalyResult = $anomalyDetector->detect($normalFeatures); echo " Anomaly Detection: " . ($normalAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n"; echo " Score: {$normalAnomalyResult->anomalyScore->toString()}\n"; echo " Indicator: {$normalAnomalyResult->primaryIndicator}\n\n"; // ======================================== // 3. Simulate DDoS Attack Pattern // ======================================== echo "3. Simulating DDoS attack pattern...\n"; $ddosIp = new IpAddress('198.51.100.42'); // High frequency, same endpoint for ($i = 1; $i <= 20; $i++) { $request = createMockRequest($ddosIp, "/api/search", 'GET'); $historyTracker->track($request); // No sleep - rapid fire } $ddosSequence = $historyTracker->getSequence($ddosIp); echo "✓ Tracked {$ddosSequence->count()} DDoS-like requests\n"; $ddosFeatures = $patternExtractor->extract($ddosSequence); echo " Features extracted:\n"; echo " - Request Frequency: " . round($ddosFeatures->requestFrequency, 2) . " req/s 🚨\n"; echo " - Endpoint Diversity: " . round($ddosFeatures->endpointDiversity, 2) . " 🚨\n"; echo " - User-Agent Consistency: " . round($ddosFeatures->userAgentConsistency, 2) . "\n\n"; $ddosAnomalyResult = $anomalyDetector->detect($ddosFeatures); echo " Anomaly Detection: " . ($ddosAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n"; echo " Score: {$ddosAnomalyResult->anomalyScore->toString()} 🚨\n"; echo " Severity: {$ddosAnomalyResult->getSeverity()}\n"; echo " Indicator: {$ddosAnomalyResult->primaryIndicator}\n"; echo " Recommended Action: {$ddosAnomalyResult->getRecommendedAction()}\n\n"; // ======================================== // 4. Simulate Bot Pattern // ======================================== echo "4. Simulating bot pattern...\n"; $botIp = new IpAddress('198.51.100.99'); // Perfect timing regularity with identical payloads for ($i = 1; $i <= 10; $i++) { $request = createMockRequest($botIp, "/api/data", 'POST', 'same_payload_data'); $historyTracker->track($request); usleep(500000); // Exactly 0.5 seconds between requests } $botSequence = $historyTracker->getSequence($botIp); echo "✓ Tracked {$botSequence->count()} bot-like requests\n"; $botFeatures = $patternExtractor->extract($botSequence); echo " Features extracted:\n"; echo " - Time Pattern Regularity: " . round($botFeatures->timePatternRegularity, 2) . " 🚨\n"; echo " - Payload Similarity: " . round($botFeatures->payloadSimilarity, 2) . " 🚨\n"; echo " - Request Frequency: " . round($botFeatures->requestFrequency, 2) . " req/s\n\n"; $botAnomalyResult = $anomalyDetector->detect($botFeatures); echo " Anomaly Detection: " . ($botAnomalyResult->isAnomalous ? '❌ ANOMALOUS' : '✓ NORMAL') . "\n"; echo " Score: {$botAnomalyResult->anomalyScore->toString()}\n"; echo " Severity: {$botAnomalyResult->getSeverity()}\n"; echo " Indicator: {$botAnomalyResult->primaryIndicator}\n"; if (!empty($botAnomalyResult->detectedPatterns)) { echo " Detected Patterns:\n"; foreach ($botAnomalyResult->detectedPatterns as $pattern) { echo " - {$pattern['type']}\n"; } } echo "\n"; // ======================================== // 5. Test MLEnhancedWafLayer Integration // ======================================== echo "5. Testing ML WAF Layer integration...\n\n"; // Analyze normal traffic echo " Analyzing normal traffic through ML WAF Layer:\n"; $normalRequest = createMockRequest($normalIp, "/dashboard", 'GET'); $normalResult = $mlWafLayer->analyze($normalRequest); echo " Status: " . ($normalResult->isThreat() ? 'THREAT' : 'CLEAN') . "\n"; echo " Message: {$normalResult->getMessage()}\n"; echo " Processing Time: {$normalResult->getProcessingTime()->toMilliseconds()}ms\n\n"; // Analyze DDoS traffic echo " Analyzing DDoS traffic through ML WAF Layer:\n"; $ddosRequest = createMockRequest($ddosIp, "/api/search", 'GET'); $ddosResult = $mlWafLayer->analyze($ddosRequest); echo " Status: " . ($ddosResult->isThreat() ? '🚨 THREAT' : 'CLEAN') . "\n"; echo " Message: {$ddosResult->getMessage()}\n"; echo " Processing Time: {$ddosResult->getProcessingTime()->toMilliseconds()}ms\n"; if ($ddosResult->isThreat()) { $detections = $ddosResult->getDetections(); echo " Detections: " . count($detections) . "\n"; foreach ($detections as $detection) { echo " - {$detection->category->value}: {$detection->description}\n"; echo " Severity: {$detection->severity->value}, Confidence: {$detection->confidence->getValue()}%\n"; } } echo "\n"; // ======================================== // 6. Layer Metrics and Health // ======================================== echo "6. ML WAF Layer metrics and health status:\n\n"; echo " Layer Name: {$mlWafLayer->getName()}\n"; echo " Version: {$mlWafLayer->getVersion()}\n"; echo " Priority: {$mlWafLayer->getPriority()}\n"; echo " Enabled: " . ($mlWafLayer->isEnabled() ? 'Yes' : 'No') . "\n"; echo " Healthy: " . ($mlWafLayer->isHealthy() ? '✓ Yes' : '❌ No') . "\n"; echo " Confidence Level: {$mlWafLayer->getConfidenceLevel()->getValue()}%\n"; echo " Timeout Threshold: {$mlWafLayer->getTimeoutThreshold()->toMilliseconds()}ms\n"; echo " Supports Parallel Processing: " . ($mlWafLayer->supportsParallelProcessing() ? 'Yes' : 'No') . "\n\n"; echo " Supported Categories:\n"; foreach ($mlWafLayer->getSupportedCategories() as $category) { echo " - {$category->value}\n"; } echo "\n"; // ======================================== // 7. Feature Vector Analysis // ======================================== echo "7. Complete feature vector comparison:\n\n"; echo " Normal Traffic Features:\n"; $normalVector = $normalFeatures->toArray(); foreach ($normalVector as $key => $value) { echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n"; } echo "\n"; echo " DDoS Attack Features:\n"; $ddosVector = $ddosFeatures->toArray(); foreach ($ddosVector as $key => $value) { echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n"; } echo "\n"; echo " Bot Pattern Features:\n"; $botVector = $botFeatures->toArray(); foreach ($botVector as $key => $value) { echo " - " . str_pad($key, 30) . ": " . round($value, 3) . "\n"; } echo "\n"; // ======================================== // 8. Request History Statistics // ======================================== echo "8. Request history statistics:\n\n"; $normalStats = $normalSequence->getStatistics(); echo " Normal Traffic Statistics:\n"; foreach ($normalStats as $key => $value) { echo " - " . str_pad($key, 30) . ": {$value}\n"; } echo "\n"; $ddosStats = $ddosSequence->getStatistics(); echo " DDoS Traffic Statistics:\n"; foreach ($ddosStats as $key => $value) { echo " - " . str_pad($key, 30) . ": {$value}\n"; } echo "\n"; echo "=== Demo Complete ===\n\n"; echo "Summary:\n"; echo "✓ ML WAF Layer successfully detects:\n"; echo " - DDoS attacks (high frequency + low diversity)\n"; echo " - Bot patterns (perfect regularity + high similarity)\n"; echo " - Normal traffic patterns (no anomalies)\n\n"; echo "✓ Uses Core Score value object for confidence levels\n"; echo "✓ Provides detailed feature extraction and analysis\n"; echo "✓ Integrates seamlessly with existing WAF system\n"; // ======================================== // Helper Functions // ======================================== function createMockRequest( IpAddress $ip, string $path, string $method, string $body = '' ): \App\Framework\Http\Request { return new class($ip, $path, $method, $body) implements \App\Framework\Http\Request { public function __construct( private readonly IpAddress $ip, private readonly string $path, private readonly string $method, private readonly string $body ) {} public string $path { get => $this->path; } public object $method { get => new class($this->method) { public function __construct(public readonly string $value) {} }; } public array $queryParams { get => []; } public string $body { get => $this->body; } public int $timestamp { get => time(); } public object $headers { get => new class { public function getFirst(string $name): ?string { return match($name) { 'User-Agent' => 'Mozilla/5.0 (compatible; Bot/1.0)', 'Content-Type' => 'application/json', 'Content-Length' => '0', default => null }; } }; } public object $server { get => new class($this->ip) { public function __construct(private readonly IpAddress $ip) {} public function getRemoteAddr(): IpAddress { return $this->ip; } }; } public object $parsedBody { get => new class { public array $data { get => []; } }; } }; }