PHP code example of ados-labs / enterprise-security-shield

1. Go to this page and download the library: Download ados-labs/enterprise-security-shield library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ados-labs / enterprise-security-shield example snippets



use AdosLabs\EnterpriseSecurityShield\Core\SecurityShield;
use AdosLabs\EnterpriseSecurityShield\Storage\NullStorage;

// In-memory storage - for testing only
$shield = new SecurityShield(new NullStorage());

$result = $shield->analyze([
    'ip' => $_SERVER['REMOTE_ADDR'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
    'path' => $_SERVER['REQUEST_URI'] ?? '/',
    'method' => $_SERVER['REQUEST_METHOD'] ?? 'GET',
]);

if ($result['blocked']) {
    http_response_code(403);
    exit('Access Denied: ' . $result['reason']);
}


use AdosLabs\EnterpriseSecurityShield\Core\SecurityShield;
use AdosLabs\EnterpriseSecurityShield\Storage\RedisStorage;

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$shield = new SecurityShield(new RedisStorage($redis));

// Configure thresholds
$shield->setThresholds(
    monitor: 15,
    challenge: 35,
    rateLimit: 50,
    block: 70,
    ban: 90
);

$result = $shield->analyze([
    'ip' => $_SERVER['REMOTE_ADDR'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
    'path' => $_SERVER['REQUEST_URI'] ?? '/',
    'method' => $_SERVER['REQUEST_METHOD'] ?? 'GET',
    'request_count' => $requestCount,  // From your rate limiter
    'error_count' => $errorCount,      // 404s for this IP
]);

match ($result['decision']) {
    'ALLOW' => null,  // Continue
    'MONITOR' => $logger->info('Suspicious activity', $result),
    'CHALLENGE' => showCaptcha(),
    'RATE_LIMIT' => respondWith429($result['retry_after']),
    'BLOCK' => respondWith403($result['reason']),
    'BAN' => respondWith403AndBan($result['ip']),
};


use AdosLabs\EnterpriseSecurityShield\Config\SecurityConfig;
use AdosLabs\EnterpriseSecurityShield\Middleware\SecurityMiddleware;
use AdosLabs\EnterpriseSecurityShield\Storage\RedisStorage;

// Configure the WAF
$config = new SecurityConfig();
$config->setStorage(new RedisStorage($redis))
       ->setLogger($logger)
       ->setScoreThreshold(50)
       ->setBanDuration(86400);

// Create middleware - ML is enabled by default
$middleware = new SecurityMiddleware($config);

// Optionally disable ML (pattern-based only)
// $middleware->setMLEnabled(false);

// In your request handler
if (!$middleware->handle($_SERVER, $_GET, $_POST)) {
    http_response_code(403);
    exit('Access Denied');
}

use AdosLabs\EnterpriseSecurityShield\ML\OnlineLearningClassifier;

$classifier = new OnlineLearningClassifier($storage);

// Classify a request
$result = $classifier->classify([
    'user_agent' => 'curl/8.7.1',
    'path' => '/admin/phpinfo.php',
    'request_count' => 50,
    'rate_limited' => true,
]);

// Result structure
[
    'classification' => 'SCANNER',
    'confidence' => 0.87,
    'is_threat' => true,
    'learning_status' => 'mature',
    'total_samples_learned' => 1247,
    'features_used' => ['ua:curl', 'path:phpinfo', 'behavior:rapid_requests'],
    'probabilities' => [...],
]

// Manual learning (for confirmed threats)
$classifier->learn(
    features: ['user_agent' => 'malicious-bot', 'path' => '/exploit'],
    trueClass: OnlineLearningClassifier::CLASS_SCANNER,
    weight: 1.0  // Confidence in label
);

// Train from historical events
$learned = $classifier->autoLearnFromEvents(limit: 1000);

// Get model statistics
$stats = $classifier->getStats();
// ['total_samples' => 1247, 'learning_status' => 'mature', ...]

// Export/Import for backup
$backup = $classifier->exportModel();
$classifier->importModel($backup);

// In SecurityMiddleware, when an IP is banned:
$this->learnFromSecurityEvent('auto_ban', $ip, [
    'user_agent' => $userAgent,
    'path' => $path,
    'reasons' => ['critical_path', 'scanner_ua'],
]);
// The model updates incrementally - no manual training needed

// User-Agent signatures
'curl/', 'wget/', 'python-requests/', 'CensysInspect/', 'Nmap Scripting Engine'

// Path patterns
'/wp-admin/', '/.env', '/.git/', '/phpmyadmin/', '/GponForm/'

// Behavioral signals
'high_404_rate', 'rapid_requests', 'login_failure_burst', 'path_scanning'

use AdosLabs\EnterpriseSecurityShield\ML\ThreatClassifier;

$classifier = new ThreatClassifier();

$result = $classifier->classify(
    ip: '185.177.72.51',
    userAgent: 'curl/8.7.1',
    path: '/admin/phpinfo.php'
);

// Result structure
[
    'classification' => 'SCANNER',       // SCANNER, IOT_EXPLOIT, CREDENTIAL_THEFT, etc.
    'confidence' => 0.87,                // 0.0 to 1.0
    'is_threat' => true,
    'reasoning' => 'Known scanner UA (curl) + sensitive path',
    'features_detected' => ['ua_curl', 'path_phpinfo'],
    'probabilities' => [
        'SCANNER' => 0.87,
        'LEGITIMATE' => 0.13,
    ],
]

use AdosLabs\EnterpriseSecurityShield\Bot\BotVerificationService;

$verifier = new BotVerificationService();

$result = $verifier->verify(
    ip: '66.249.66.1',
    userAgent: 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
);

// Result structure
[
    'is_bot' => true,
    'is_verified' => true,              // DNS verification passed
    'bot_id' => 'googlebot',
    'bot_name' => 'Googlebot',
    'category' => 'search_engine',
    'verification_method' => 'dns',     // 'dns', 'ip_range', 'ua_only'
    'respect_robots' => true,           // Does this bot respect robots.txt?
    'confidence' => 0.99,
]

use AdosLabs\EnterpriseSecurityShield\ML\AnomalyDetector;

$detector = new AnomalyDetector();

$result = $detector->analyze(
    ip: '192.168.1.1',
    path: '/a/b/c/d/e/f/g/h',  // Deep path
    requestCount: 500,
    errorCount404: 80
);

// Result structure
[
    'is_anomaly' => true,
    'anomaly_score' => 67,
    'anomalies' => [
        ['metric' => 'path_depth', 'value' => 8, 'threshold' => 5],
        ['metric' => 'requests_per_minute', 'value' => 500, 'zscore' => 4.2],
    ],
    'risk_factors' => ['high_request_rate', 'deep_path'],
    'recommendation' => 'Rate limit this IP',
]

use AdosLabs\EnterpriseSecurityShield\Detection\XSSDetector;

$detector = new XSSDetector();

$result = $detector->detect('<script>alert(1)</script>');

// Result structure
[
    'is_xss' => true,
    'confidence' => 0.95,
    'patterns_matched' => ['script_tag', 'alert_function'],
    'sanitized' => '&lt;script&gt;alert(1)&lt;/script&gt;',
]

use AdosLabs\EnterpriseSecurityShield\Detection\SQLiDetector;

$detector = new SQLiDetector();

$result = $detector->detect("1' OR '1'='1");

// Result structure
[
    'is_sqli' => true,
    'confidence' => 0.92,
    'patterns_matched' => ['boolean_injection', 'quote_escape'],
    'risk_level' => 'high',
]

use AdosLabs\EnterpriseSecurityShield\RateLimiting\RateLimiter;

// Token bucket: 100 tokens, refills 10/second
$limiter = RateLimiter::tokenBucket($storage, capacity: 100, refillRate: 10);

$result = $limiter->attempt('user:123');

if (!$result->allowed) {
    header('Retry-After: ' . $result->retryAfter);
    http_response_code(429);
    exit('Too Many Requests');
}

use AdosLabs\EnterpriseSecurityShield\Middleware\HoneypotMiddleware;

$honeypot = new HoneypotMiddleware($storage);

if ($honeypot->isHoneypot($_SERVER['REQUEST_URI'])) {
    // Log attacker IP, ban immediately
    $storage->banIP($_SERVER['REMOTE_ADDR'], 86400, 'Honeypot access');
    http_response_code(404);
    exit;
}

use AdosLabs\EnterpriseSecurityShield\Resilience\CircuitBreaker;

$breaker = new CircuitBreaker('redis', $storage, [
    'failure_threshold' => 5,    // Open after 5 failures
    'recovery_timeout' => 30,    // Try again after 30s
    'half_open_max_calls' => 3,  // Allow 3 test calls
]);

$result = $breaker->call(
    fn() => $redis->get('key'),           // Primary
    fn() => $localCache->get('key')       // Fallback
);

use AdosLabs\EnterpriseSecurityShield\Resilience\RetryPolicy;

$policy = RetryPolicy::exponentialBackoffWithJitter(
    maxAttempts: 5,
    baseDelay: 1.0,
    maxDelay: 30.0
);

// Delays: ~1s, ~2s, ~4s, ~8s (with jitter)
$result = $policy->execute(fn() => $api->call());

class FailClosedRedisStorage extends RedisStorage
{
    public function isBanned(string $ip): bool
    {
        try {
            return parent::isBanned($ip);
        } catch (\RedisException $e) {
            error_log("Redis down - fail-closed active");
            return true;  // Block all traffic on failure
        }
    }
}

use AdosLabs\EnterpriseSecurityShield\Notifications\NotificationManager;
use AdosLabs\EnterpriseSecurityShield\Notifications\TelegramNotifier;
use AdosLabs\EnterpriseSecurityShield\Notifications\SlackNotifier;

$manager = new NotificationManager();
$manager->addChannel(new TelegramNotifier($botToken, $chatId));
$manager->addChannel(new SlackNotifier($webhookUrl));

$manager->broadcast('Security Alert', 'IP banned: 1.2.3.4', [
    'reason' => 'Honeypot access',
    'path' => '/.env',
]);

use AdosLabs\EnterpriseSecurityShield\Health\HealthCheck;
use AdosLabs\EnterpriseSecurityShield\Health\Checks\RedisHealthCheck;

$health = new HealthCheck();
$health->addCheck('redis', new RedisHealthCheck($redis));

// Kubernetes liveness/readiness
header('Content-Type: application/json');
$result = $health->readiness();
http_response_code($result->getHttpStatusCode());
echo $result->toJson();

use AdosLabs\EnterpriseSecurityShield\Detection\RequestSmugglingDetector;

$detector = new RequestSmugglingDetector();

// Check request headers
$result = $detector->detect($headers, $rawRequest);

if ($result['detected']) {
    // Attack type: CL_TE_CONFLICT, DUPLICATE_CL, TE_OBFUSCATION, etc.
    error_log("Smuggling detected: " . $result['attack_type']);
    http_response_code(400);
    exit('Bad Request');
}

// Sanitize headers (removes dangerous combinations)
$safeHeaders = $detector->sanitize($headers);

use AdosLabs\EnterpriseSecurityShield\Detection\WebSocketProtector;

$protector = new WebSocketProtector([
    'allowed_origins' => ['example.com', '*.example.com'],
    'max_connections_per_ip' => 10,
]);

// Validate upgrade request
$result = $protector->validateUpgrade($headers, $origin, $clientIp, $connectionCount);

if (!$result['valid']) {
    // Reject WebSocket connection
    http_response_code(403);
    exit(json_encode(['errors' => $result['errors']]));
}

// Generate accept key for handshake
$acceptKey = $protector->generateAcceptKey($headers['sec-websocket-key']);

// Check for CSWSH attack
$cswsh = $protector->detectCSWSH($origin, $referer, $host);
if ($cswsh['detected']) {
    error_log("CSWSH attack: " . $cswsh['reason']);
}

use AdosLabs\EnterpriseSecurityShield\Security\JWTValidator;

$validator = new JWTValidator([
    'allowed_algorithms' => ['RS256', 'ES256'],  // Whitelist only!
    'ult['attacks_detected'])) {
        error_log("CRITICAL: alg:none attack attempted!");
    }
    if (in_array('ALG_CONFUSION', $result['attacks_detected'])) {
        error_log("WARNING: Possible RS256->HS256 confusion attack");
    }

    http_response_code(401);
    exit('Invalid token');
}

// Token structure is safe, now verify signature with your JWT library
$payload = $result['payload'];

use AdosLabs\EnterpriseSecurityShield\Detection\GraphQLProtector;

$protector = new GraphQLProtector([
    'max_depth' => 10,           // Prevent deeply nested queries
    'max_complexity' => 1000,    // Prevent expensive queries
    'max_batch_size' => 10,      // Prevent batching abuse
    'allow_introspection' => false,  // Disable in production!
]);

// Analyze single query
$result = $protector->analyze($query, $variables);

// Analyze batch (array of operations)
$result = $protector->analyze($batchOperations);

if (!$result['allowed']) {
    http_response_code(400);
    exit(json_encode([
        'errors' => $result['errors'],
        'attacks' => $result['attacks_detected'],
    ]));
}

// Query is safe to execute
$metrics = $result['metrics'];  // depth, complexity, aliases, operations

use AdosLabs\EnterpriseSecurityShield\Detection\DDoSProtector;

$protector = new DDoSProtector($storage, [
    'max_requests_per_window' => 1000,
    'window_size' => 60,
    'max_concurrent_connections' => 50,
    'expensive_endpoints' => [
        '/api/search' => 5,     // Costs 5 requests
        '/api/export' => 20,    // Costs 20 requests
    ],
]);

// Basic check (flood detection)
$result = $protector->analyze($clientIp, $path, $method);

// Advanced check with server metrics
$result = $protector->analyze($clientIp, $path, $method, [
    'header_receive_time' => 5.2,      // Slowloris detection
    'header_count' => 10,
    'body_receive_time' => 30.0,       // RUDY detection
    'content_length' => 1000,
    'concurrent_connections' => 45,
]);

if (!$result['allowed']) {
    // $result['attack_type']: HTTP_FLOOD, SLOWLORIS, RUDY, etc.
    http_response_code(429);
    exit('Too Many Requests');
}

use AdosLabs\EnterpriseSecurityShield\Detection\HTTP2Protector;

$protector = new HTTP2Protector([
    'max_header_list_size' => 16384,
    'max_concurrent_streams' => 100,
    'max_resets_per_minute' => 100,
]);

// Analyze request (ec) {
        error_log("HTTP/2 Security: " . $rec);
    }
}

// Get recommended nginx/apache config
echo $protector->getNginxConfig();
echo $protector->getApacheConfig();

use AdosLabs\EnterpriseSecurityShield\RateLimiting\APIRateLimiter;

$limiter = new APIRateLimiter($storage, [
    'default_limit' => 60,
    'default_window' => 60,
    'algorithm' => 'token_bucket',  // or 'sliding_window', 'fixed_window'
]);

// Define tiers
$limiter->defineTier('free', ['limit' => 60, 'burst' => 10]);
$limiter->defineTier('pro', ['limit' => 1000, 'burst' => 200]);
$limiter->defineTier('enterprise', ['limit' => 10000, 'burst' => 2000]);

// Set endpoint-specific limits
$limiter->setEndpointLimit('/api/search', ['limit' => 10, 'cost' => 5]);
$limiter->setEndpointLimit('/api/export/*', ['limit' => 5, 'cost' => 20]);

// Register API keys
$limiter->registerApiKey('sk_live_xxx', 'pro');

// Check rate limit
$result = $limiter->check(
    identifier: $clientIp,
    endpoint: '/api/users',
    apiKey: $request->header('X-API-Key'),
    cost: 1
);

if (!$result['allowed']) {
    header('X-RateLimit-Limit: ' . $result['limit']);
    header('X-RateLimit-Remaining: ' . $result['remaining']);
    header('X-RateLimit-Reset: ' . $result['reset']);
    header('Retry-After: ' . $result['retry_after']);
    http_response_code(429);
    exit('Rate limit exceeded');
}

use AdosLabs\EnterpriseSecurityShield\ThreatIntel\ThreatFeedClient;
use AdosLabs\EnterpriseSecurityShield\ThreatIntel\ThreatMatcher;

// Initialize feed client
$feedClient = new ThreatFeedClient($storage, [
    'cache_ttl' => 21600,  // 6 hours
]);

// Update feeds (call via cron every 6 hours)
$result = $feedClient->fetchAllFeeds();
echo "Updated: " . implode(', ', $result['success']);
echo "Failed: " . implode(', ', array_keys($result['failed']));
echo "Total entries: " . $result['total_entries'];

// Check IP against feeds
$matcher = new ThreatMatcher($storage);
$matcher->loadFromStorage();

$result = $matcher->matchIp('1.2.3.4');
if ($result['match']) {
    echo "Blocked by feed: " . $result['feed'];
    // $result['type']: 'exact_ip', 'cidr', etc.
}

// Batch check
$results = $matcher->matchIpBatch(['1.2.3.4', '5.6.7.8', '9.10.11.12']);

use AdosLabs\EnterpriseSecurityShield\Core\SecurityShield;

$shield = new SecurityShield($storage, $config, $logger);

// Request smuggling
$result = $shield->analyzeRequestSmuggling($headers, $rawRequest);

// WebSocket validation
$result = $shield->validateWebSocketUpgrade($headers, $origin, $clientIp);

// JWT validation
$result = $shield->validateJWT($token);

// GraphQL protection
$result = $shield->analyzeGraphQL($query, $variables);

// DDoS detection
$result = $shield->analyzeDDoS($clientIp, $path, $method, $serverMetrics);

// API rate limiting
$result = $shield->checkAPIRateLimit($identifier, $endpoint, $apiKey);

// Threat intelligence
$result = $shield->checkThreatIntel($ip);

// Update threat feeds (cron job)
$result = $shield->updateThreatFeeds();

// HTTP/2 protection
$result = $shield->analyzeHTTP2($headers, $serverMetrics);

/.env, /.git/config, /.aws/credentials, /wp-admin/, /wp-login.php,
/phpmyadmin/, /phpinfo.php, /admin/, /administrator/, /GponForm/,
/HNAP1/, /cgi-bin/, /actuator/health, /api/v1/users, etc.