- Add comprehensive health check system with multiple endpoints - Add Prometheus metrics endpoint - Add production logging configurations (5 strategies) - Add complete deployment documentation suite: * QUICKSTART.md - 30-minute deployment guide * DEPLOYMENT_CHECKLIST.md - Printable verification checklist * DEPLOYMENT_WORKFLOW.md - Complete deployment lifecycle * PRODUCTION_DEPLOYMENT.md - Comprehensive technical reference * production-logging.md - Logging configuration guide * ANSIBLE_DEPLOYMENT.md - Infrastructure as Code automation * README.md - Navigation hub * DEPLOYMENT_SUMMARY.md - Executive summary - Add deployment scripts and automation - Add DEPLOYMENT_PLAN.md - Concrete plan for immediate deployment - Update README with production-ready features All production infrastructure is now complete and ready for deployment.
379 lines
13 KiB
PHP
379 lines
13 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* ML-Enhanced WAF Behavioral Analysis - Usage Example
|
|
*
|
|
* Demonstrates the complete integration of ML-based behavioral analysis
|
|
* into the WAF system for advanced threat detection.
|
|
*
|
|
* Features Demonstrated:
|
|
* - RequestHistoryTracker for sequence storage
|
|
* - BehaviorPatternExtractor with 8 features
|
|
* - BehaviorAnomalyDetector using Core Score value object
|
|
* - MLEnhancedWafLayer integration with WafEngine
|
|
* - Advanced threat detection scenarios
|
|
*/
|
|
|
|
require_once __DIR__ . '/../vendor/autoload.php';
|
|
|
|
use App\Framework\Waf\WafEngine;
|
|
use App\Framework\Waf\Layers\MLEnhancedWafLayer;
|
|
use App\Framework\Waf\MachineLearning\BehaviorPatternExtractor;
|
|
use App\Framework\Waf\MachineLearning\BehaviorAnomalyDetector;
|
|
use App\Framework\Waf\MachineLearning\RequestHistoryTracker;
|
|
use App\Framework\Waf\MachineLearning\ValueObjects\BehaviorFeatures;
|
|
use App\Framework\Waf\MachineLearning\ValueObjects\RequestSequence;
|
|
use App\Framework\Cache\SmartCache;
|
|
use App\Framework\Core\ValueObjects\Score;
|
|
use App\Framework\Core\ValueObjects\Duration;
|
|
use App\Framework\Http\IpAddress;
|
|
use App\Infrastructure\GeoIp\GeoIp;
|
|
|
|
echo "=== ML-Enhanced WAF Behavioral Analysis Demo ===\n\n";
|
|
|
|
// ========================================
|
|
// 1. Setup Components
|
|
// ========================================
|
|
|
|
echo "1. Initializing ML WAF components...\n";
|
|
|
|
// Mock cache for demonstration
|
|
$cache = new SmartCache(new \App\Framework\Cache\Driver\InMemoryCache());
|
|
|
|
// Mock GeoIp service
|
|
$geoIp = new class {
|
|
public function getCountryCode(\App\Framework\Http\IpAddress $ip) {
|
|
return new class {
|
|
public function toString(): string {
|
|
return 'US';
|
|
}
|
|
};
|
|
}
|
|
};
|
|
|
|
// Mock logger
|
|
$logger = new class implements \Psr\Log\LoggerInterface {
|
|
use \Psr\Log\LoggerTrait;
|
|
public function log($level, $message, array $context = []): void {
|
|
echo "[{$level}] {$message}\n";
|
|
if (!empty($context)) {
|
|
echo " Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
|
|
}
|
|
}
|
|
};
|
|
|
|
// Create components
|
|
$historyTracker = new RequestHistoryTracker(
|
|
cache: $cache,
|
|
maxRequestsPerIp: 50,
|
|
timeWindowSeconds: 300
|
|
);
|
|
|
|
$patternExtractor = new BehaviorPatternExtractor(
|
|
geoIp: $geoIp,
|
|
minConfidence: 0.6
|
|
);
|
|
|
|
$anomalyDetector = new BehaviorAnomalyDetector(
|
|
anomalyThreshold: Score::medium(),
|
|
zScoreThreshold: 3.0,
|
|
iqrMultiplier: 1.5
|
|
);
|
|
|
|
$mlWafLayer = new MLEnhancedWafLayer(
|
|
historyTracker: $historyTracker,
|
|
patternExtractor: $patternExtractor,
|
|
anomalyDetector: $anomalyDetector,
|
|
logger: $logger,
|
|
confidenceThreshold: Score::medium(),
|
|
minHistorySize: 5
|
|
);
|
|
|
|
echo "✓ ML WAF Layer initialized: {$mlWafLayer->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 => [];
|
|
}
|
|
};
|
|
}
|
|
};
|
|
}
|