<?php
/**
 * Bearmor Malware Pattern Library
 *
 * @package Bearmor_Security
 */

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

/**
 * Malware detection patterns
 * Balanced for SMBs - catches real threats, minimizes false positives
 */
class Bearmor_Malware_Patterns {

	/**
	 * Get all malware detection patterns
	 *
	 * @return array Array of pattern definitions
	 */
	public static function get_patterns() {
		return array(
			// CRITICAL - Code Execution
			array(
				'id'          => 'eval_function',
				'pattern'     => '/\beval\s*\(/i',
				'name'        => 'Code Execution - eval()',
				'severity'    => 'high',
				'description' => 'Executes arbitrary PHP code - check context for legitimacy',
				'category'    => 'code_execution',
			),
			array(
				'id'          => 'assert_function',
				'pattern'     => '/\bassert\s*\(/i',
				'name'        => 'Code Execution - assert()',
				'severity'    => 'high',
				'description' => 'Used in math libs and SCSS compilers - usually safe',
				'category'    => 'code_execution',
			),
			array(
				'id'          => 'create_function',
				'pattern'     => '/\bcreate_function\s*\(/i',
				'name'        => 'Code Execution - create_function()',
				'severity'    => 'high',
				'description' => 'Deprecated but harmless in older libraries',
				'category'    => 'code_execution',
			),
			array(
				'id'          => 'preg_replace_eval',
				'pattern'     => '/preg_replace\s*\([^)]*["\']\/[^"\']*e["\']/',
				'name'        => 'Code Execution - preg_replace /e modifier',
				'severity'    => 'critical',
				'description' => 'Executes code in replacement - deprecated and dangerous',
				'category'    => 'code_execution',
			),

			// Shell Execution - Whitelisted for safe plugins
			array(
				'id'          => 'system_function',
				'pattern'     => '/\bsystem\s*\(/i',
				'name'        => 'Shell Execution - system()',
				'severity'    => 'critical',
				'description' => 'Executes shell commands - whitelisted for backup plugins',
				'category'    => 'shell_execution',
			),
			array(
				'id'          => 'exec_function',
				'pattern'     => '/\bexec\s*\(/i',
				'name'        => 'Shell Execution - exec()',
				'severity'    => 'critical',
				'description' => 'Executes shell commands - whitelisted for backup plugins',
				'category'    => 'shell_execution',
			),
			array(
				'id'          => 'shell_exec_function',
				'pattern'     => '/\bshell_exec\s*\(/i',
				'name'        => 'Shell Execution - shell_exec()',
				'severity'    => 'critical',
				'description' => 'Executes shell commands - whitelisted for backup plugins',
				'category'    => 'shell_execution',
			),
			array(
				'id'          => 'passthru_function',
				'pattern'     => '/\bpassthru\s*\(/i',
				'name'        => 'Shell Execution - passthru()',
				'severity'    => 'critical',
				'description' => 'Executes shell commands - whitelisted for backup plugins',
				'category'    => 'shell_execution',
			),
			array(
				'id'          => 'proc_open',
				'pattern'     => '/\bproc_open\s*\(/i',
				'name'        => 'Shell Execution - proc_open()',
				'severity'    => 'high',
				'description' => 'Opens process with full control',
				'category'    => 'shell_execution',
			),
			array(
				'id'          => 'popen_function',
				'pattern'     => '/\bpopen\s*\(/i',
				'name'        => 'Shell Execution - popen()',
				'severity'    => 'high',
				'description' => 'Opens pipe to process',
				'category'    => 'shell_execution',
			),

			// Obfuscation - Safe alone, dangerous in combinations
			array(
				'id'          => 'base64_decode',
				'pattern'     => '/base64_decode\s*\(/i',
				'name'        => 'Obfuscation - base64_decode()',
				'severity'    => 'high',
				'description' => 'Safe for JWT, encryption, configs - dangerous with eval()',
				'category'    => 'obfuscation',
			),
			array(
				'id'          => 'gzinflate',
				'pattern'     => '/\bgzinflate\s*\(/i',
				'name'        => 'Obfuscation - gzinflate()',
				'severity'    => 'high',
				'description' => 'Normal compression - dangerous with eval()',
				'category'    => 'obfuscation',
			),
			array(
				'id'          => 'gzuncompress',
				'pattern'     => '/\bgzuncompress\s*\(/i',
				'name'        => 'Obfuscation - gzuncompress()',
				'severity'    => 'high',
				'description' => 'Normal compression - dangerous with eval()',
				'category'    => 'obfuscation',
			),
			array(
				'id'          => 'str_rot13',
				'pattern'     => '/\bstr_rot13\s*\(/i',
				'name'        => 'Obfuscation - str_rot13()',
				'severity'    => 'medium',
				'description' => 'ROT13 encoding - sometimes used to obfuscate',
				'category'    => 'obfuscation',
			),
			array(
				'id'          => 'gzdecode',
				'pattern'     => '/\bgzdecode\s*\(/i',
				'name'        => 'Obfuscation - gzdecode()',
				'severity'    => 'medium',
				'description' => 'Decodes gzip data - can hide malicious code',
				'category'    => 'obfuscation',
			),

			// HIGH - Suspicious Patterns
			array(
				'id'          => 'error_suppression',
				'pattern'     => '/<\?php\s*@/i',
				'name'        => 'Error Suppression - @',
				'severity'    => 'high',
				'description' => 'Suppresses errors at file start - hides malicious activity',
				'category'    => 'suspicious',
			),
			array(
				'id'          => 'variable_variables',
				'pattern'     => '/\$\$[a-zA-Z_]/i',
				'name'        => 'Variable Variables - $$',
				'severity'    => 'medium',
				'description' => 'Dynamic variable names - can obfuscate malicious code',
				'category'    => 'suspicious',
			),
			array(
				'id'          => 'globals_access',
				'pattern'     => '/\$\{["\']GLOBALS["\']\}/i',
				'name'        => 'Dynamic GLOBALS Access',
				'severity'    => 'high',
				'description' => 'Obfuscated access to global variables',
				'category'    => 'suspicious',
			),

			// HIGH - File Operations
			array(
				'id'          => 'file_put_contents_post',
				'pattern'     => '/file_put_contents\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
				'name'        => 'File Writing from User Input',
				'severity'    => 'critical',
				'description' => 'Writes user-controlled data to files - file upload backdoor',
				'category'    => 'file_operations',
			),
			array(
				'id'          => 'fwrite_post',
				'pattern'     => '/fwrite\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
				'name'        => 'File Writing from User Input - fwrite()',
				'severity'    => 'critical',
				'description' => 'Writes user-controlled data to files',
				'category'    => 'file_operations',
			),
			array(
				'id'          => 'move_uploaded_file',
				'pattern'     => '/move_uploaded_file\s*\(/i',
				'name'        => 'File Upload - move_uploaded_file()',
				'severity'    => 'low',
				'description' => 'Handles file uploads - check for proper validation',
				'category'    => 'file_operations',
			),

			// LOW - Network Operations
			array(
				'id'          => 'curl_exec',
				'pattern'     => '/curl_exec\s*\(/i',
				'name'        => 'Network Request - curl_exec()',
				'severity'    => 'low',
				'description' => 'Makes external HTTP requests - check destination',
				'category'    => 'network',
			),
			array(
				'id'          => 'file_get_contents_http',
				'pattern'     => '/file_get_contents\s*\([^)]*http/i',
				'name'        => 'Remote File Access - file_get_contents()',
				'severity'    => 'medium',
				'description' => 'Fetches remote content - potential backdoor communication',
				'category'    => 'network',
			),
			array(
				'id'          => 'fsockopen',
				'pattern'     => '/\bfsockopen\s*\(/i',
				'name'        => 'Socket Connection - fsockopen()',
				'severity'    => 'high',
				'description' => 'Used for remote APIs - legitimate in many plugins',
				'category'    => 'network',
			),

			// CRITICAL - Dangerous Combinations with User Input
			array(
				'id'          => 'exec_with_user_input',
				'pattern'     => '/(exec|system|shell_exec|passthru)\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
				'name'        => 'Shell Execution with User Input',
				'severity'    => 'critical',
				'description' => 'Executes shell commands with user-controlled data - RCE vulnerability',
				'category'    => 'malware_signature',
			),
			array(
				'id'          => 'eval_with_user_input',
				'pattern'     => '/eval\s*\([^)]*\$_(POST|GET|REQUEST|COOKIE)/i',
				'name'        => 'eval() with User Input',
				'severity'    => 'critical',
				'description' => 'Executes user-controlled code - backdoor',
				'category'    => 'malware_signature',
			),
			array(
				'id'          => 'base64_gzinflate_combo',
				'pattern'     => '/base64_decode\s*\([^)]*gzinflate|gzinflate\s*\([^)]*base64_decode/i',
				'name'        => 'base64_decode + gzinflate Combo',
				'severity'    => 'critical',
				'description' => 'Double obfuscation - classic malware pattern',
				'category'    => 'malware_signature',
			),

			// CRITICAL - Known Malware Signatures
			array(
				'id'          => 'long_base64',
				'pattern'     => '/["\'][A-Za-z0-9+\/]{200,}={0,2}["\']/i',
				'name'        => 'Long Base64 String',
				'severity'    => 'high',
				'description' => 'Very long base64 encoded string - likely obfuscated malware',
				'category'    => 'malware_signature',
			),
			array(
				'id'          => 'eval_base64',
				'pattern'     => '/eval\s*\(\s*base64_decode/i',
				'name'        => 'eval(base64_decode()) Pattern',
				'severity'    => 'critical',
				'description' => 'Classic malware pattern - executes decoded payload',
				'category'    => 'malware_signature',
			),
			array(
				'id'          => 'eval_gzinflate',
				'pattern'     => '/eval\s*\(\s*gzinflate/i',
				'name'        => 'eval(gzinflate()) Pattern',
				'severity'    => 'critical',
				'description' => 'Classic malware pattern - executes decompressed payload',
				'category'    => 'malware_signature',
			),
			array(
				'id'          => 'assert_base64',
				'pattern'     => '/assert\s*\(\s*base64_decode/i',
				'name'        => 'assert(base64_decode()) Pattern',
				'severity'    => 'critical',
				'description' => 'Malware pattern using assert instead of eval',
				'category'    => 'malware_signature',
			),

			// MEDIUM - Backdoor Indicators
			array(
				'id'          => 'password_compare',
				'pattern'     => '/md5\s*\(\s*\$_(POST|GET|REQUEST)\[["\']pass/i',
				'name'        => 'Password Check Pattern',
				'severity'    => 'high',
				'description' => 'Checks password from user input - potential backdoor',
				'category'    => 'backdoor',
			),
			array(
				'id'          => 'auth_bypass',
				'pattern'     => '/\$_(POST|GET|REQUEST)\[["\']auth["\']\]/i',
				'name'        => 'Authentication Parameter',
				'severity'    => 'medium',
				'description' => 'Custom authentication - check for backdoor access',
				'category'    => 'backdoor',
			),

			// MEDIUM - Database Operations
			array(
				'id'          => 'mysql_query_post',
				'pattern'     => '/mysql_query\s*\([^)]*\$_(POST|GET|REQUEST)/i',
				'name'        => 'SQL Query from User Input',
				'severity'    => 'high',
				'description' => 'Direct SQL query with user input - SQL injection risk',
				'category'    => 'database',
			),
			array(
				'id'          => 'wpdb_query_post',
				'pattern'     => '/\$wpdb->query\s*\([^)]*\$_(POST|GET|REQUEST)/i',
				'name'        => 'WordPress SQL Query from User Input',
				'severity'    => 'high',
				'description' => 'Direct wpdb query with user input - SQL injection risk',
				'category'    => 'database',
			),
		);
	}

	/**
	 * Get patterns by severity
	 *
	 * @param string $severity Severity level (critical, high, medium, low).
	 * @return array Filtered patterns
	 */
	public static function get_patterns_by_severity( $severity ) {
		$all_patterns = self::get_patterns();
		return array_filter(
			$all_patterns,
			function( $pattern ) use ( $severity ) {
				return $pattern['severity'] === $severity;
			}
		);
	}

	/**
	 * Get patterns by category
	 *
	 * @param string $category Category name.
	 * @return array Filtered patterns
	 */
	public static function get_patterns_by_category( $category ) {
		$all_patterns = self::get_patterns();
		return array_filter(
			$all_patterns,
			function( $pattern ) use ( $category ) {
				return $pattern['category'] === $category;
			}
		);
	}

	/**
	 * Get severity color for UI
	 *
	 * @param string $severity Severity level.
	 * @return string CSS color class
	 */
	public static function get_severity_color( $severity ) {
		$colors = array(
			'high'     => '#d63638',  // Red (was critical)
			'medium'   => '#f56e28',  // Orange (was high)
			'low'      => '#00a32a',  // Green
			'critical' => '#d63638',  // Legacy support
		);

		return isset( $colors[ $severity ] ) ? $colors[ $severity ] : '#666';
	}

	/**
	 * Get severity label
	 *
	 * @param string $severity Severity level.
	 * @return string Human-readable label
	 */
	public static function get_severity_label( $severity ) {
		$labels = array(
			'critical' => '🔴 CRITICAL',
			'high'     => '🟠 HIGH',
			'medium'   => '🟡 MEDIUM',
			'low'      => '🟢 LOW',
		);

		return isset( $labels[ $severity ] ) ? $labels[ $severity ] : $severity;
	}
}
