/** * @fileoverview Malware Detection Module - Main Entry Point * @module rules/malware * * Enterprise-grade malware detection system with: * - Multi-pattern detection (Regex, AST, Heuristic, Semantic) * - Dynamic scoring with MITRE ATT&CK integration * - 60+ comprehensive rules across 7 categories * - Support for 13 programming languages * - ReDoS protection and timeout safeguards * - Obfuscation detection and entropy analysis * * @example * ```typescript * import { MalwareRuleEngine, createMalwareEngine } from './rules/malware'; * * // Create engine with all rules * const engine = createMalwareEngine(); * * // Analyze code * const findings = await engine.analyze(code, { * filePath: 'suspicious.js', * language: 'javascript' * }); * * // Check results * findings.forEach(finding => { * console.log(`${finding.severity}: ${finding.ruleName}`); * console.log(`Score: ${finding.score.totalScore}/100`); * }); * ``` */ // ============================================================================ // LEGACY TYPE COMPATIBILITY // ============================================================================ import { Rule, Severity, ThreatType, FindingCategory } from '../../types'; import { getStandardsForThreat } from '../standards'; // ============================================================================ // NEW TYPE EXPORTS // ============================================================================ export * from './types'; // ============================================================================ // UTILITY EXPORTS // ============================================================================ export { calculateEntropy, analyzeEntropyByLine, normalizeCode, detectObfuscationLevel, detectAntiDebugging, detectEnvironmentChecks, safeRegexMatch, extractSnippet, analyzeBase64Content, extractSuspiciousStrings } from './utils'; // ============================================================================ // CONSTANTS EXPORTS // ============================================================================ export { SCORE_THRESHOLDS, ENTROPY_THRESHOLDS, LIMITS, OBFUSCATION_INDICATORS, SUSPICIOUS_HOSTS, CRYPTO_INDICATORS, DANGEROUS_FUNCTIONS, MITRE_TECHNIQUES } from './constants'; // ============================================================================ // SCORING EXPORTS // ============================================================================ export { MalwareScoreCalculator } from './scoring'; // ============================================================================ // ENGINE EXPORTS // ============================================================================ export { MalwareRuleEngine, PatternMatcher, createDefaultEngine, quickScan, EngineOptions } from './engine'; // ============================================================================ // RULE CATEGORY EXPORTS // ============================================================================ import { backdoorRules as newBackdoorRules } from './categories/backdoors'; import { cryptominerRules as newCryptominerRules } from './categories/cryptominers'; import { keyloggerRules as newKeyloggerRules } from './categories/keyloggers'; import { exfiltrationRules as newExfiltrationRules } from './categories/exfiltration'; import { obfuscationRules as newObfuscationRules } from './categories/obfuscation'; import { loaderRules as newLoaderRules } from './categories/loaders'; import { networkRules as newNetworkRules } from './categories/network'; export { newBackdoorRules as backdoorRulesV2, newCryptominerRules as cryptominerRulesV2, newKeyloggerRules as keyloggerRulesV2, newExfiltrationRules as exfiltrationRulesV2, newObfuscationRules as obfuscationRulesV2, newLoaderRules as loaderRulesV2, newNetworkRules as networkRulesV2 }; // ============================================================================ // AGGREGATED RULE SETS // ============================================================================ import { MalwareRule } from './types'; /** * All malware detection rules (60+ rules) */ export const allMalwareRules: MalwareRule[] = [ ...newBackdoorRules, // 10 rules ...newCryptominerRules, // 11 rules ...newKeyloggerRules, // 12 rules ...newExfiltrationRules, // 15 rules ...newObfuscationRules, // 14 rules ...newLoaderRules, // 9 rules ...newNetworkRules // 10 rules ]; /** * Critical severity rules only */ export const criticalRules: MalwareRule[] = allMalwareRules.filter( rule => rule.severity === 'critical' ); /** * High confidence rules only */ export const highConfidenceRules: MalwareRule[] = allMalwareRules.filter( rule => rule.confidence === 'high' ); // ============================================================================ // ENGINE FACTORY FUNCTIONS // ============================================================================ import { MalwareRuleEngine, EngineOptions } from './engine'; import { AnalysisOptions } from './types'; /** * Create a fully configured malware detection engine with all rules * * @param options - Optional analysis configuration * @returns Configured MalwareRuleEngine instance * * @example * ```typescript * const engine = createMalwareEngine({ * enableHeuristics: true, * enableAstAnalysis: true, * minConfidence: 0.5 * }); * ``` */ export function createMalwareEngine( options?: Partial ): MalwareRuleEngine { return new MalwareRuleEngine(allMalwareRules, options); } /** * Create an engine with only critical severity rules * * @param options - Optional analysis configuration * @returns MalwareRuleEngine with critical rules only */ export function createCriticalOnlyEngine( options?: Partial ): MalwareRuleEngine { return new MalwareRuleEngine(criticalRules, options); } /** * Create an engine with custom rule subset * * @param rules - Array of rules to include * @param options - Optional analysis configuration * @returns MalwareRuleEngine with specified rules */ export function createCustomEngine( rules: MalwareRule[], options?: Partial ): MalwareRuleEngine { return new MalwareRuleEngine(rules, options); } // ============================================================================ // CONVENIENCE FUNCTIONS // ============================================================================ import { MalwareFinding, AnalysisContext, SupportedLanguage } from './types'; /** * Quick malware scan with default settings * * @param code - Code to analyze * @param language - Programming language * @returns Scan results with malicious status * * @example * ```typescript * const result = await scanForMalware(suspiciousCode, 'javascript'); * if (result.isMalicious) { * console.log(`Malware detected! Score: ${result.score}`); * result.findings.forEach(f => console.log(f.ruleName)); * } * ``` */ export async function scanForMalware( code: string, language?: string ): Promise<{ isMalicious: boolean; score: number; severity: 'critical' | 'high' | 'medium' | 'low' | 'clean'; findings: MalwareFinding[]; summary: { totalFindings: number; criticalCount: number; highCount: number; }; }> { const engine = createMalwareEngine(); const context: AnalysisContext = { filePath: 'scan', content: code, language: (language as SupportedLanguage) ?? SupportedLanguage.JAVASCRIPT }; const findings = await engine.analyze(context); const maxScore = findings.length > 0 ? Math.max(...findings.map(f => f.malwareScore.score)) : 0; const criticalCount = findings.filter(f => f.severity === 'critical').length; const highCount = findings.filter(f => f.severity === 'high').length; let severity: 'critical' | 'high' | 'medium' | 'low' | 'clean'; if (maxScore >= 85) severity = 'critical'; else if (maxScore >= 65) severity = 'high'; else if (maxScore >= 40) severity = 'medium'; else if (maxScore >= 20) severity = 'low'; else severity = 'clean'; return { isMalicious: maxScore >= 40, // Medium threshold score: maxScore, severity, findings, summary: { totalFindings: findings.length, criticalCount, highCount } }; } /** * Check if code contains specific malware category * * @param code - Code to analyze * @param category - Malware category to check * @param language - Programming language * @returns True if category detected * * @example * ```typescript * const hasBackdoor = await hasMalwareCategory(code, 'backdoor', 'javascript'); * ``` */ export async function hasMalwareCategory( code: string, category: 'backdoor' | 'cryptominer' | 'keylogger' | 'exfiltration' | 'obfuscation' | 'loader' | 'network', language?: string ): Promise { let rules: MalwareRule[]; switch (category) { case 'backdoor': rules = newBackdoorRules; break; case 'cryptominer': rules = newCryptominerRules; break; case 'keylogger': rules = newKeyloggerRules; break; case 'exfiltration': rules = newExfiltrationRules; break; case 'obfuscation': rules = newObfuscationRules; break; case 'loader': rules = newLoaderRules; break; case 'network': rules = newNetworkRules; break; } const engine = new MalwareRuleEngine(rules); const context: AnalysisContext = { filePath: 'scan', content: code, language: (language as SupportedLanguage) ?? SupportedLanguage.JAVASCRIPT }; const findings = await engine.analyze(context); return findings.length > 0; } /** * Analyze code and generate detailed report * * @param code - Code to analyze * @param filePath - File path for context * @param language - Programming language * @returns Detailed analysis report */ export async function generateMalwareReport( code: string, filePath: string, language?: string ): Promise<{ filePath: string; language?: string; timestamp: Date; findings: MalwareFinding[]; summary: { totalFindings: number; bySeverity: Record; byCategory: Record; highestScore: number; isMalicious: boolean; }; mitreAttack: Array<{ tactic: string; technique: string; count: number; }>; recommendations: string[]; }> { const engine = createMalwareEngine(); const context: AnalysisContext = { filePath, content: code, language: (language as SupportedLanguage) ?? SupportedLanguage.JAVASCRIPT }; const findings = await engine.analyze(context); const summary = engine.generateSummary(findings); // Aggregate MITRE ATT&CK techniques const mitreTechniques = new Map(); for (const finding of findings) { if (finding.mitreAttack) { for (const mitre of finding.mitreAttack) { const key = `${mitre.tacticId}-${mitre.techniqueId}`; const existing = mitreTechniques.get(key); if (existing) { existing.count++; } else { mitreTechniques.set(key, { tactic: mitre.tacticName, technique: mitre.techniqueName, count: 1 }); } } } } // Generate recommendations const recommendations: string[] = []; if (summary.criticalCount > 0) { recommendations.push('URGENT: Critical malware detected. Isolate and analyze immediately.'); } if (summary.bySeverity['high'] > 0) { recommendations.push('High severity threats found. Review and remove malicious code.'); } if (findings.some(f => String(f.threatType).includes('backdoor'))) { recommendations.push('Backdoor detected. Check for unauthorized access and reset credentials.'); } if (findings.some(f => String(f.threatType).includes('exfiltration'))) { recommendations.push('Data exfiltration detected. Investigate what data may have been stolen.'); } if (findings.some(f => String(f.category) === 'obfuscation')) { recommendations.push('Obfuscation detected. Use deobfuscation tools to analyze intent.'); } // Calculate by category const byCategory: Record = {}; for (const finding of findings) { byCategory[finding.category] = (byCategory[finding.category] || 0) + 1; } return { filePath, language, timestamp: new Date(), findings, summary: { ...summary, byCategory, isMalicious: summary.highestScore >= 40 }, mitreAttack: Array.from(mitreTechniques.values()), recommendations }; } // ============================================================================ // MODULE METADATA // ============================================================================ export const MALWARE_MODULE_INFO = { version: '2.0.0', totalRules: allMalwareRules.length, categories: [ 'backdoors', 'cryptominers', 'keyloggers', 'exfiltration', 'obfuscation', 'loaders', 'network' ], supportedLanguages: [ 'javascript', 'typescript', 'python', 'php', 'c', 'cpp', 'csharp', 'java', 'ruby', 'go', 'rust', 'shell', 'powershell' ], features: [ 'Multi-pattern detection (Regex, AST, Heuristic, Semantic)', 'Dynamic malware scoring (0-100)', 'MITRE ATT&CK framework integration', 'Obfuscation and entropy analysis', 'ReDoS protection', 'Concurrent file analysis', 'Detailed remediation steps', 'False positive reduction' ] }; /** * Get module information */ export function getModuleInfo(): typeof MALWARE_MODULE_INFO { return MALWARE_MODULE_INFO; } // ============================================================================ // LEGACY COMPATIBILITY - ORIGINAL RULES // ============================================================================ /** * Backdoor Detection Rules */ const backdoorRules: Rule[] = [ { id: 'MAL-BACK-001', name: 'Potential Backdoor - Reverse Shell', description: 'Code pattern consistent with a reverse shell detected. This allows remote attackers to gain shell access to the system.', languages: ['javascript', 'typescript', 'python', 'php', 'c', 'cpp', 'csharp'], threatType: ThreatType.REVERSE_SHELL, category: FindingCategory.MALWARE, severity: Severity.CRITICAL, standards: getStandardsForThreat(ThreatType.REVERSE_SHELL), patterns: [ { type: 'regex', pattern: 'socket\\.(?:connect|create_connection)\\s*\\([^)]*\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', flags: 'gi' }, { type: 'regex', pattern: '\\/bin\\/(?:bash|sh)\\s+-i', flags: 'gi' }, { type: 'regex', pattern: 'nc\\s+-e\\s+\\/bin\\/(?:bash|sh)', flags: 'gi' }, { type: 'regex', pattern: 'subprocess\\.(?:Popen|call).*(?:bash|sh|cmd)', flags: 'gi' }, { type: 'regex', pattern: 'dup2\\s*\\(.*(?:STDIN|STDOUT|STDERR)', flags: 'gi' }, { type: 'regex', pattern: 'CreateProcess.*cmd\\.exe', flags: 'gi' } ], remediation: 'This code appears to implement a reverse shell backdoor. Remove immediately and investigate how this code was introduced. Audit all recent commits and contributor access.', enabled: true, tags: ['backdoor', 'reverse-shell', 'malware', 'critical'] }, { id: 'MAL-BACK-002', name: 'Web Shell Pattern', description: 'Code pattern consistent with a web shell detected. Web shells provide attackers with remote command execution via web interface.', languages: ['php', 'python', 'javascript', 'typescript'], threatType: ThreatType.BACKDOOR, category: FindingCategory.MALWARE, severity: Severity.CRITICAL, standards: getStandardsForThreat(ThreatType.BACKDOOR), patterns: [ { type: 'regex', pattern: '\\$_(?:GET|POST|REQUEST)\\s*\\[[\'"][^\'"]+[\'"]\\s*\\].*(?:exec|system|passthru|shell_exec|eval)', flags: 'gi' }, { type: 'regex', pattern: 'eval\\s*\\(\\s*(?:base64_decode|gzinflate|str_rot13)', flags: 'gi' }, { type: 'regex', pattern: 'assert\\s*\\(\\s*\\$_', flags: 'gi' }, { type: 'regex', pattern: 'preg_replace\\s*\\([^)]*\\/e[\'"]', flags: 'gi' } ], remediation: 'This appears to be a web shell. Remove immediately. Investigate system for other compromises. Check web server logs for unauthorized access.', enabled: true, tags: ['webshell', 'backdoor', 'rce', 'critical'] } ]; /** * Cryptominer Detection Rules */ const cryptominerRules: Rule[] = [ { id: 'MAL-CRYPT-001', name: 'Cryptocurrency Mining Code', description: 'Code patterns associated with cryptocurrency mining detected. This may indicate unauthorized use of computing resources.', languages: ['javascript', 'typescript', 'python', 'php'], threatType: ThreatType.CRYPTOMINER, category: FindingCategory.MALWARE, severity: Severity.HIGH, standards: getStandardsForThreat(ThreatType.CRYPTOMINER), patterns: [ { type: 'regex', pattern: 'coinhive|cryptoloot|coin-hive|coinimp|cryptonight', flags: 'gi' }, { type: 'regex', pattern: 'stratum\\+tcp:\\/\\/', flags: 'gi' }, { type: 'regex', pattern: 'xmrig|xmr-stak|minerd|cgminer', flags: 'gi' }, { type: 'regex', pattern: 'CryptoNight|RandomX|Ethash', flags: 'g' }, { type: 'regex', pattern: 'miner\\.(?:start|stop|mine)', flags: 'gi' }, { type: 'regex', pattern: 'hashrate|nonce.*difficulty', flags: 'gi' } ], remediation: 'Remove cryptocurrency mining code immediately. This is resource theft. Investigate how this code was introduced and review access controls.', enabled: true, tags: ['cryptominer', 'resource-abuse', 'malware'] } ]; /** * Keylogger Detection Rules */ const keyloggerRules: Rule[] = [ { id: 'MAL-KEY-001', name: 'Potential Keylogger', description: 'Code pattern consistent with keylogging behavior detected. Keyloggers capture and potentially exfiltrate user keystrokes.', languages: ['javascript', 'typescript', 'python', 'csharp', 'c', 'cpp'], threatType: ThreatType.KEYLOGGER, category: FindingCategory.MALWARE, severity: Severity.CRITICAL, standards: getStandardsForThreat(ThreatType.KEYLOGGER), patterns: [ { type: 'regex', pattern: 'addEventListener\\s*\\([\'"]key(?:down|up|press)[\'"]', flags: 'gi' }, { type: 'regex', pattern: 'onkey(?:down|up|press)\\s*=', flags: 'gi' }, { type: 'regex', pattern: 'pynput\\.keyboard\\.Listener', flags: 'gi' }, { type: 'regex', pattern: 'GetAsyncKeyState|SetWindowsHookEx.*WH_KEYBOARD', flags: 'gi' }, { type: 'regex', pattern: 'keyboard\\.on_(?:press|release)', flags: 'gi' } ], remediation: 'This code captures keyboard input. If not intentional for legitimate purposes (like accessibility), remove immediately and investigate.', enabled: true, tags: ['keylogger', 'spyware', 'malware', 'critical'] } ]; /** * Data Exfiltration Detection Rules */ const exfiltrationRules: Rule[] = [ { id: 'MAL-EXFIL-001', name: 'Suspicious Data Exfiltration', description: 'Code pattern suggests collection and transmission of sensitive data to external endpoints.', languages: ['javascript', 'typescript', 'python', 'php'], threatType: ThreatType.DATA_EXFILTRATION, category: FindingCategory.MALWARE, severity: Severity.CRITICAL, standards: getStandardsForThreat(ThreatType.DATA_EXFILTRATION), patterns: [ { type: 'regex', pattern: 'document\\.cookie.*(?:fetch|XMLHttpRequest|ajax|axios)', flags: 'gis' }, { type: 'regex', pattern: 'localStorage.*(?:fetch|XMLHttpRequest|ajax)', flags: 'gis' }, { type: 'regex', pattern: '(?:password|credit|ssn|secret).*(?:http|fetch|post)', flags: 'gis' }, { type: 'regex', pattern: 'navigator\\.(?:credentials|clipboard).*fetch', flags: 'gis' } ], remediation: 'This code appears to collect and transmit sensitive data. Verify this is intentional and authorized. If not, remove immediately and audit data flows.', enabled: true, tags: ['exfiltration', 'data-theft', 'malware'] } ]; /** * Obfuscated Code Detection Rules */ const obfuscationRules: Rule[] = [ { id: 'MAL-OBF-001', name: 'Heavily Obfuscated Code', description: 'Code appears to be heavily obfuscated, potentially hiding malicious functionality. Legitimate code rarely requires this level of obfuscation.', languages: ['javascript', 'typescript', 'python', 'php'], threatType: ThreatType.OBFUSCATED_CODE, category: FindingCategory.MALWARE, severity: Severity.HIGH, standards: getStandardsForThreat(ThreatType.OBFUSCATED_CODE), patterns: [ { type: 'regex', pattern: '\\\\x[0-9a-f]{2}(?:\\\\x[0-9a-f]{2}){10,}', flags: 'gi' }, { type: 'regex', pattern: '\\\\u[0-9a-f]{4}(?:\\\\u[0-9a-f]{4}){10,}', flags: 'gi' }, { type: 'regex', pattern: 'String\\.fromCharCode\\s*\\([^)]{50,}\\)', flags: 'gi' }, { type: 'regex', pattern: 'atob\\s*\\([\'"][A-Za-z0-9+/=]{100,}[\'"]\\)', flags: 'g' }, { type: 'regex', pattern: 'eval\\s*\\(\\s*(?:atob|Buffer\\.from|unescape)', flags: 'gi' }, { type: 'regex', pattern: '_0x[a-f0-9]{4,}', flags: 'gi' } ], remediation: 'Heavily obfuscated code should be investigated. Deobfuscate and review the actual functionality. Consider removing if source cannot be verified.', enabled: true, tags: ['obfuscation', 'suspicious', 'malware'] } ]; /** * Embedded Payload Detection Rules */ const payloadRules: Rule[] = [ { id: 'MAL-PAYLOAD-001', name: 'Embedded Binary Payload', description: 'Large base64-encoded or hex-encoded data detected that may contain embedded malware or executable payloads.', languages: ['javascript', 'typescript', 'python', 'php', 'java', 'csharp'], threatType: ThreatType.EMBEDDED_PAYLOAD, category: FindingCategory.MALWARE, severity: Severity.HIGH, standards: getStandardsForThreat(ThreatType.EMBEDDED_PAYLOAD), patterns: [ { type: 'regex', pattern: '[\'"][A-Za-z0-9+/]{500,}={0,2}[\'"]', flags: 'g' }, { type: 'regex', pattern: '(?:4d5a|7f454c46|cafebabe)[0-9a-f]{100,}', flags: 'gi' }, { type: 'regex', pattern: 'base64\\.b64decode\\s*\\([\'"][A-Za-z0-9+/]{200,}', flags: 'g' } ], remediation: 'Large embedded binary data should be investigated. Extract and analyze the payload. If legitimate, document its purpose; otherwise, remove.', enabled: true, tags: ['payload', 'binary', 'embedded', 'malware'] } ]; /** * Suspicious Network Activity Rules */ const networkRules: Rule[] = [ { id: 'MAL-NET-001', name: 'Suspicious External Connection', description: 'Code makes connections to external IP addresses or suspicious domains. This may indicate C2 communication or data exfiltration.', languages: ['javascript', 'typescript', 'python', 'php', 'java', 'csharp'], threatType: ThreatType.SUSPICIOUS_NETWORK, category: FindingCategory.MALWARE, severity: Severity.MEDIUM, standards: getStandardsForThreat(ThreatType.SUSPICIOUS_NETWORK), patterns: [ { type: 'regex', pattern: '(?:fetch|axios|request|http).*(?:pastebin|hastebin|ghostbin)', flags: 'gi' }, { type: 'regex', pattern: '(?:fetch|axios|request).*\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}', flags: 'gi' }, { type: 'regex', pattern: '\\.(?:onion|bit|i2p)[\\/\\s\\\'\\"]', flags: 'gi' }, { type: 'regex', pattern: 'ngrok\\.io|serveo\\.net|localhost\\.run', flags: 'gi' } ], remediation: 'Review all external network connections. Verify destinations are legitimate and authorized. Block unauthorized external communications.', enabled: true, tags: ['network', 'c2', 'suspicious', 'malware'] } ]; /** * Malicious Loader Detection Rules */ const loaderRules: Rule[] = [ { id: 'MAL-LOAD-001', name: 'Dynamic Code Loading', description: 'Code dynamically loads and executes external content. This is a common technique for loading malware payloads.', languages: ['javascript', 'typescript', 'python', 'php'], threatType: ThreatType.MALICIOUS_LOADER, category: FindingCategory.MALWARE, severity: Severity.HIGH, standards: getStandardsForThreat(ThreatType.MALICIOUS_LOADER), patterns: [ { type: 'regex', pattern: 'eval\\s*\\(\\s*(?:fetch|axios|request|http\\.get)', flags: 'gis' }, { type: 'regex', pattern: 'document\\.write\\s*\\([\'"]]*src=', flags: 'gi' }, { type: 'regex', pattern: 'exec\\s*\\(\\s*(?:urllib|requests)\\.get', flags: 'gis' }, { type: 'regex', pattern: '\\.createElement\\s*\\([\'"]script[\'"]\\)[\\s\\S]*\\.src\\s*=', flags: 'gim' } ], remediation: 'Dynamic code loading from external sources is dangerous. Use Content Security Policy. Verify all external code sources and use integrity checks.', enabled: true, tags: ['loader', 'dynamic', 'remote-code', 'malware'] } ]; /** * Export all malware rules (LEGACY COMPATIBILITY) * For backward compatibility with existing codebase */ export const malwareRules: Rule[] = [ ...backdoorRules, ...cryptominerRules, ...keyloggerRules, ...exfiltrationRules, ...obfuscationRules, ...payloadRules, ...networkRules, ...loaderRules ]; // ============================================================================ // DEFAULT EXPORT // ============================================================================ export default { // New Engine API MalwareRuleEngine, createMalwareEngine, createCriticalOnlyEngine, createCustomEngine, // New Rules (v2) allMalwareRules, backdoorRulesV2: newBackdoorRules, cryptominerRules, keyloggerRules, exfiltrationRules, obfuscationRules, loaderRules, networkRules, // Convenience functions scanForMalware, hasMalwareCategory, generateMalwareReport, getModuleInfo, // Legacy compatibility malwareRules, backdoorRules, // Metadata MALWARE_MODULE_INFO };