<?php
/**
 * VMPFence Threat Intelligence System
 * 
 * 
 * 
 * 
 * 
 * @package VMPFence
 * @version 1.0.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class VMPFence_Threat_Intelligence {
    
    /**
     * Malware signatures database
     */
    private $malware_signatures = [];
    
    /**
     * IP reputation cache
     */
    private $ip_reputation_cache = [];
    
    /**
     * Debug log
     */
    private $debug_log = [];
    
    /**
     * Threat intelligence statistics
     */
    private $threat_stats = [
        'signatures_loaded' => 0,
        'pattern_matches' => 0,
        'high_risk_patterns' => 0,
        'ip_checks' => 0,
        'malware_detected' => 0
    ];
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Threat Intelligence system initialized';
        
        // Load malware signatures
        $this->load_malware_signatures();
        
        // Initialize IP reputation system
        $this->initialize_ip_reputation();
    }
    
    /**
     * Load malware signature database
     */
    private function load_malware_signatures() {
        $this->debug_log[] = '[Threat Intelligence] Loading malware signature database';
        
        // Known malware patterns (based on real-world threats)
        $this->malware_signatures = [
            // PHP Webshells and Backdoors
            'php_webshells' => [
                '/\$_(?:GET|POST|REQUEST)\s*\[\s*[\'"][^\'\"]*[\'"]\s*\]\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Dynamic function execution via HTTP parameters',
                '/eval\s*\(\s*\$_(?:GET|POST|REQUEST|COOKIE)/i' => 'Direct eval() with user input',
                '/system\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Direct system() execution with user input',
                '/exec\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Direct exec() with user input',
                '/shell_exec\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Direct shell execution with user input',
                '/passthru\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Direct passthru() with user input',
                '/file_get_contents\s*\(\s*[\'"]https?:\/\//i' => 'Remote file inclusion attempt',
                '/base64_decode\s*\(\s*[\'"][A-Za-z0-9+\/=]{100,}/i' => 'Large base64 encoded payload',
                '/\$[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*[\'"][A-Za-z0-9+\/=]{200,}[\'"]/i' => 'Encoded malware payload'
            ],
            
            // Obfuscated Code Patterns
            'obfuscation' => [
                '/str_rot13\s*\(\s*[\'"][^\'\"]{50,}/i' => 'ROT13 obfuscated code',
                '/gzinflate\s*\(\s*base64_decode/i' => 'Compressed and encoded payload',
                '/create_function\s*\(\s*[\'"][^\'\"]*[\'"]\s*,\s*[\'"][^\'\"]*eval/i' => 'Dynamic function with eval',
                '/preg_replace\s*\(\s*[\'"][^\'\"]*e[\'"][^\'\"]*eval/i' => 'PREG_REPLACE with eval modifier',
                '/assert\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Assert() with user input',
                '/\$\{[^}]*\}\s*\(/i' => 'Variable function execution',
                '/\$[a-zA-Z_][a-zA-Z0-9_]*\s*\(\s*\$[a-zA-Z_][a-zA-Z0-9_]*\s*\(\s*\$/i' => 'Nested variable functions'
            ],
            
            // File Upload Exploits
            'file_exploits' => [
                '/move_uploaded_file\s*\([^)]*\.(?:php|phtml|php5|php7)/i' => 'PHP file upload without validation',
                '/\$_FILES\[.*?\]\[.*?\].*?\.php/i' => 'Direct PHP file processing from upload',
                '/file_put_contents\s*\([^)]*\.php/i' => 'Dynamic PHP file creation',
                '/fwrite\s*\([^)]*<\?php/i' => 'Writing PHP code to file',
                '/chmod\s*\([^)]*0?777/i' => 'Setting dangerous file permissions'
            ],
            
            // Database Exploits
            'sql_injection' => [
                '/\$_(?:GET|POST|REQUEST)\[.*?\].*?(?:SELECT|INSERT|UPDATE|DELETE)/i' => 'SQL injection pattern',
                '/mysql_query\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'Direct SQL execution with user input',
                '/mysqli_query\s*\([^)]*\$_(?:GET|POST|REQUEST)/i' => 'MySQLi injection pattern',
                '/UNION\s+SELECT.*?FROM/i' => 'SQL UNION attack pattern'
            ],
            
            // Network Exploitation
            'network_exploits' => [
                '/curl_exec\s*\(\s*\$[^)]*\$_(?:GET|POST)/i' => 'CURL exploitation with user input',
                '/fsockopen\s*\(\s*\$_(?:GET|POST)/i' => 'Socket connection with user input',
                '/file_get_contents\s*\(\s*[\'"]php:\/\/input/i' => 'Reading raw POST data',
                '/(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):(?:[0-9]{1,5})/i' => 'Hardcoded IP address with port'
            ],
            
            // WordPress Specific Exploits
            'wordpress_exploits' => [
                '/wp_remote_(?:get|post)\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'WordPress HTTP request with user input',
                '/add_action\s*\(\s*[\'"]wp_ajax_[^\'\"]*[\'"]\s*,\s*[\'"]eval/i' => 'WordPress AJAX with eval',
                '/do_action\s*\(\s*\$_(?:GET|POST|REQUEST)/i' => 'WordPress action with user input',
                '/wp_mail\s*\([^)]*\$_(?:GET|POST|REQUEST)/i' => 'WordPress mail with user input'
            ]
        ];
        
        // Count total signatures
        $total_signatures = 0;
        foreach ($this->malware_signatures as $category => $patterns) {
            $total_signatures += count($patterns);
        }
        
        $this->threat_stats['signatures_loaded'] = $total_signatures;
        $this->debug_log[] = '[Threat Intelligence] Loaded ' . $total_signatures . ' malware signatures across ' . count($this->malware_signatures) . ' categories';
    }
    
    /**
     * Initialize IP reputation system
     */
    private function initialize_ip_reputation() {
        $this->debug_log[] = '[Threat Intelligence] Initializing IP reputation system';
        
        // Load known bad IP ranges (simplified for demo)
        $this->ip_reputation_cache = [
            'known_bad_ips' => [
                '127.0.0.1' => 'localhost', // Example - normally wouldn't be flagged
                // Real bad IPs would be loaded from threat feeds
            ],
            'last_updated' => current_time('mysql')
        ];
        
        $this->debug_log[] = '[Threat Intelligence] IP reputation system initialized';
    }
    
    /**
     * Analyze file content for malware signatures
     * 
     * @param string $file_path File path to analyze
     * @param string $content File content (optional, will read if not provided)
     * @return array Analysis results
     */
    public function analyze_file_content($file_path, $content = null) {
        // WHITELIST: Skip legitimate security tools and libraries
        if ($this->is_whitelisted_file($file_path)) {
            return [
                'file_path' => $file_path,
                'whitelisted' => true,
                'reason' => 'Legitimate security tool or library',
                'threats_detected' => [],
                'risk_level' => 'low',
                'pattern_count' => 0
            ];
        }
        
        if ($content === null) {
            if (!file_exists($file_path) || !is_readable($file_path)) {
                return ['error' => 'File not accessible'];
            }
            
            $file_size = filesize($file_path);
            if ($file_size > 5 * 1024 * 1024) { // Skip files > 5MB
                return ['skipped' => 'File too large for content analysis'];
            }
            
            $content = file_get_contents($file_path);
            if ($content === false) {
                return ['error' => 'Failed to read file content'];
            }
        }
        
        $analysis = [
            'file_path' => $file_path,
            'file_size' => strlen($content),
            'threats_detected' => [],
            'risk_level' => 'low',
            'categories_matched' => [],
            'pattern_count' => 0
        ];
        
        $start_time = microtime(true);
        
        // Analyze content against all signature categories
        foreach ($this->malware_signatures as $category => $patterns) {
            $category_matches = [];
            
            foreach ($patterns as $pattern => $description) {
                if (preg_match($pattern, $content, $matches)) {
                    $category_matches[] = [
                        'pattern' => $pattern,
                        'description' => $description,
                        'match' => isset($matches[0]) ? substr($matches[0], 0, 100) : 'Match found',
                        'severity' => $this->calculate_pattern_severity($category, $description)
                    ];
                    
                    $this->threat_stats['pattern_matches']++;
                    
                    // Log significant threats
                    if (strpos($description, 'eval') !== false || strpos($description, 'user input') !== false) {
                        $this->threat_stats['high_risk_patterns']++;
                        $this->debug_log[] = '[Threat Intelligence] HIGH RISK: ' . $description . ' in ' . basename($file_path);
                    }
                }
            }
            
            if (!empty($category_matches)) {
                $analysis['categories_matched'][] = $category;
                $analysis['threats_detected'][$category] = $category_matches;
                $analysis['pattern_count'] += count($category_matches);
            }
        }
        
        // Calculate overall risk level
        $analysis['risk_level'] = $this->calculate_overall_risk($analysis);
        
        // Track malware detection
        if ($analysis['risk_level'] === 'critical' || $analysis['risk_level'] === 'high') {
            $this->threat_stats['malware_detected']++;
        }
        
        $analysis['analysis_time'] = round((microtime(true) - $start_time) * 1000, 2) . 'ms';
        
        return $analysis;
    }
    
    /**
     * Calculate pattern severity
     */
    private function calculate_pattern_severity($category, $description) {
        // Critical patterns
        if (strpos($description, 'eval() with user input') !== false ||
            strpos($description, 'system() execution with user input') !== false ||
            strpos($description, 'shell execution with user input') !== false) {
            return 'critical';
        }
        
        // High risk patterns
        if (strpos($description, 'user input') !== false ||
            strpos($description, 'Dynamic function') !== false ||
            strpos($description, 'SQL injection') !== false) {
            return 'high';
        }
        
        // Medium risk patterns
        if ($category === 'obfuscation' || $category === 'file_exploits') {
            return 'medium';
        }
        
        return 'low';
    }
    
    /**
     * Calculate overall file risk level
     */
    private function calculate_overall_risk($analysis) {
        $critical_count = 0;
        $high_count = 0;
        $medium_count = 0;
        
        foreach ($analysis['threats_detected'] as $category => $threats) {
            foreach ($threats as $threat) {
                switch ($threat['severity']) {
                    case 'critical':
                        $critical_count++;
                        break;
                    case 'high':
                        $high_count++;
                        break;
                    case 'medium':
                        $medium_count++;
                        break;
                }
            }
        }
        
        // Risk level logic
        if ($critical_count > 0) {
            return 'critical';
        } elseif ($high_count >= 2) {
            return 'critical';
        } elseif ($high_count >= 1) {
            return 'high';
        } elseif ($medium_count >= 3) {
            return 'high';
        } elseif ($medium_count >= 1 || $analysis['pattern_count'] >= 5) {
            return 'medium';
        }
        
        return 'low';
    }
    
    /**
     * Check IP reputation
     * 
     * @param string $ip IP address to check
     * @return array Reputation information
     */
    public function check_ip_reputation($ip) {
        $this->threat_stats['ip_checks']++;
        
        // Basic IP validation
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            return ['error' => 'Invalid IP address'];
        }
        
        $reputation = [
            'ip' => $ip,
            'status' => 'unknown',
            'risk_level' => 'low',
            'details' => []
        ];
        
        // Check against known bad IPs
        if (isset($this->ip_reputation_cache['known_bad_ips'][$ip])) {
            $reputation['status'] = 'malicious';
            $reputation['risk_level'] = 'high';
            $reputation['details'][] = 'IP found in threat intelligence database';
            
            $this->debug_log[] = '[Threat Intelligence] Malicious IP detected: ' . $ip;
        }
        
        // Check for private/local IPs
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
            $reputation['status'] = 'private';
            $reputation['risk_level'] = 'low';
            $reputation['details'][] = 'Private or reserved IP address';
        }
        
        return $reputation;
    }
    
    /**
     * Get threat intelligence statistics
     */
    public function get_threat_statistics() {
        return array_merge($this->threat_stats, [
            'last_updated' => current_time('mysql'),
            'debug_entries' => count($this->debug_log)
        ]);
    }
    
    /**
     * Get debug log
     */
    public function get_debug_log() {
        return $this->debug_log;
    }
    
    /**
     * Update malware signatures from external sources
     * (Placeholder for real-time threat feed integration)
     */
    public function update_threat_feeds() {
        $this->debug_log[] = '[Threat Intelligence] Checking for threat feed updates...';
        
        // Placeholder for real-time threat intelligence updates
        // In production, this would connect to:
        // - VirusTotal API
        // - Malware information sharing platforms
        // - Security vendor threat feeds
        // - Government threat intelligence feeds
        
        $this->debug_log[] = '[Threat Intelligence] Threat feeds are up to date';
        
        return [
            'status' => 'success',
            'signatures_updated' => 0,
            'last_update' => current_time('mysql')
        ];
    }
    
    /**
     * Generate threat intelligence report
     */
    public function generate_threat_report($scan_results = []) {
        $report = [
            'summary' => [
                'total_signatures' => $this->threat_stats['signatures_loaded'],
                'pattern_matches' => $this->threat_stats['pattern_matches'],
                'high_risk_patterns' => $this->threat_stats['high_risk_patterns'],
                'malware_detected' => $this->threat_stats['malware_detected'],
                'ip_checks' => $this->threat_stats['ip_checks']
            ],
            'risk_assessment' => $this->assess_overall_threat_level(),
            'recommendations' => $this->generate_security_recommendations(),
            'generated_at' => current_time('mysql')
        ];
        
        return $report;
    }
    
    /**
     * Assess overall threat level
     */
    private function assess_overall_threat_level() {
        $malware_count = $this->threat_stats['malware_detected'];
        $high_risk_count = $this->threat_stats['high_risk_patterns'];
        
        if ($malware_count > 0) {
            return 'critical';
        } elseif ($high_risk_count > 5) {
            return 'high';
        } elseif ($high_risk_count > 0) {
            return 'medium';
        }
        
        return 'low';
    }
    
    /**
     * Generate security recommendations
     */
    private function generate_security_recommendations() {
        $recommendations = [];
        
        if ($this->threat_stats['malware_detected'] > 0) {
            $recommendations[] = 'CRITICAL: Malware detected. Quarantine affected files immediately.';
        }
        
        if ($this->threat_stats['high_risk_patterns'] > 5) {
            $recommendations[] = 'HIGH: Multiple high-risk patterns detected. Review file integrity.';
        }
        
        if ($this->threat_stats['pattern_matches'] > 50) {
            $recommendations[] = 'MEDIUM: High number of suspicious patterns. Consider security audit.';
        }
        
        if (empty($recommendations)) {
            $recommendations[] = 'LOW: No critical threats detected. Continue monitoring.';
        }
        
        return $recommendations;
    }
    
    /**
     * Check if file should be whitelisted (legitimate security tools)
     * 
     * @param string $file_path File path to check
     * @return bool True if whitelisted
     */
    private function is_whitelisted_file($file_path) {
        // Normalize path for comparison
        $normalized_path = str_replace(['\\', ABSPATH], ['/', ''], $file_path);
        
        // Whitelist patterns for legitimate security tools and libraries
        $whitelist_patterns = [
            // Security Plugins
            '/wp-content\/plugins\/wordfence\//i',           // Wordfence Security
            '/wp-content\/plugins\/all-in-one-wp-security/i', // All In One WP Security
            '/wp-content\/plugins\/sucuri-scanner/i',        // Sucuri Security
            '/wp-content\/plugins\/better-wp-security/i',    // iThemes Security
            '/wp-content\/plugins\/wp-security-audit-log/i', // WP Security Audit Log
            '/wp-content\/plugins\/bulletproof-security/i',  // BulletProof Security
            
            // Legitimate Libraries
            '/vendor\/maxmind/i',                            // MaxMind GeoIP
            '/vendor\/geoip2/i',                             // GeoIP2 Library
            '/vendor\/composer/i',                           // Composer dependencies
            '/vendor\/symfony/i',                            // Symfony components
            '/vendor\/psr\//i',                              // PSR Standards
            '/vendor\/monolog/i',                            // Logging library
            '/vendor\/guzzlehttp/i',                         // HTTP client
            
            // Development Tools
            '/node_modules\//i',                             // Node.js modules
            '/\.git\//i',                                    // Git repository files
            '/webpack/i',                                    // Webpack build tool
            '/babel/i',                                      // Babel transpiler
            
            // WordPress Core Security
            '/wp-admin\/includes\/class-wp-upgrader/i',      // WordPress upgrader
            '/wp-includes\/rest-api\//i',                    // REST API files
            '/wp-includes\/blocks\//i',                      // Gutenberg blocks
            
            // Backup Plugins (often trigger false positives)
            '/wp-content\/plugins\/.*backup/i',             // Backup plugins
            '/wp-content\/plugins\/.*migrate/i',            // Migration plugins
            '/wp-content\/plugins\/updraftplus/i',          // UpdraftPlus
            '/wp-content\/plugins\/duplicator/i',           // Duplicator
        ];
        
        // Check against whitelist patterns
        foreach ($whitelist_patterns as $pattern) {
            if (preg_match($pattern, $normalized_path)) {
                return true;
            }
        }
        
        // Whitelist files by extension (legitimate compressed/encoded files)
        $whitelisted_extensions = [
            '.mo',    // Translation files
            '.po',    // Translation source files
            '.woff',  // Web fonts
            '.woff2', // Web fonts
            '.ttf',   // True Type fonts
            '.eot',   // Embedded fonts
            '.svg',   // SVG files (can contain encoded data)
            '.min.js', // Minified JavaScript (often looks obfuscated)
            '.min.css', // Minified CSS
        ];
        
        foreach ($whitelisted_extensions as $ext) {
            if (substr($normalized_path, -strlen($ext)) === $ext) {
                return true;
            }
        }
        
        return false;
    }
}
