/** * @fileoverview Obfuscation and Evasion Detection Rules * @module rules/malware/categories/obfuscation * * Comprehensive rules for detecting obfuscated code including: * - Base64 + eval patterns * - String splitting obfuscation * - Hex/Unicode encoding * - Packer detection * - Anti-debugging techniques * - Dead code insertion */ import { MalwareRule, MalwareThreatType, MalwareCategory, MalwareSeverity, ConfidenceLevel, SupportedLanguage, PatternType, MitreTactic, HeuristicPattern } from '../types'; // ============================================================================ // BASE64 OBFUSCATION RULES // ============================================================================ export const base64ObfuscationRules: MalwareRule[] = [ { id: 'MAL-OBF-001', name: 'Obfuscation - Base64 Encoded Eval', description: 'Detects base64-encoded strings passed to eval or similar execution functions.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [ SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON, SupportedLanguage.PHP ], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 80, patterns: [ { type: PatternType.REGEX, patternId: 'js-atob-eval', pattern: 'eval\\s*\\(\\s*atob\\s*\\([\'"][A-Za-z0-9+/=]{20,}[\'"]\\s*\\)', flags: 'gi', weight: 1.0, description: 'JavaScript atob + eval' }, { type: PatternType.REGEX, patternId: 'buffer-from-eval', pattern: 'eval\\s*\\(\\s*Buffer\\.from\\s*\\([\'"][A-Za-z0-9+/=]{20,}[\'"]\\s*,\\s*[\'"]base64[\'"]', flags: 'gi', weight: 1.0, description: 'Node.js Buffer.from base64 + eval' }, { type: PatternType.REGEX, patternId: 'php-base64-eval', pattern: 'eval\\s*\\(\\s*base64_decode\\s*\\([\'"][A-Za-z0-9+/=]{20,}[\'"]', flags: 'gi', weight: 1.0, description: 'PHP base64_decode + eval' }, { type: PatternType.REGEX, patternId: 'python-b64-exec', pattern: 'exec\\s*\\(\\s*base64\\.(?:b64decode|decodebytes)\\s*\\([\'"][A-Za-z0-9+/=]{20,}', flags: 'gi', weight: 1.0, description: 'Python base64 decode + exec' }, { type: PatternType.REGEX, patternId: 'function-constructor-b64', pattern: 'Function\\s*\\(\\s*atob\\s*\\([\'"][A-Za-z0-9+/=]{20,}', flags: 'gi', weight: 1.0, description: 'Function constructor with base64' } ], amplifyingPatterns: [ { type: PatternType.REGEX, patternId: 'long-b64-string', pattern: '[\'"][A-Za-z0-9+/=]{100,}[\'"]', flags: 'g', weight: 0.3, description: 'Long base64 string present' } ], maliciousExamples: [ { code: `eval(atob("dmFyIHg9ZG9jdW1lbnQuY29va2llOw=="));`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Base64 encoded eval payload' }, { code: ``, language: SupportedLanguage.PHP, isMalicious: true, description: 'PHP base64 web shell' } ], impact: { technical: 'Hides malicious code using base64 encoding.', business: 'Code obfuscation to evade detection.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on hidden payload'] }, remediation: { summary: 'Decode and analyze the base64 payload. Remove if malicious.', steps: [ 'Decode the base64 string (safely, without execution)', 'Analyze the decoded content for malicious patterns', 'Remove the obfuscated code', 'Implement code review processes' ] }, mitreAttack: [ { tacticId: MitreTactic.DEFENSE_EVASION, tacticName: 'Defense Evasion', techniqueId: 'T1027', techniqueName: 'Obfuscated Files or Information', url: 'https://attack.mitre.org/techniques/T1027/' }, { tacticId: MitreTactic.DEFENSE_EVASION, tacticName: 'Defense Evasion', techniqueId: 'T1140', techniqueName: 'Deobfuscate/Decode Files or Information', url: 'https://attack.mitre.org/techniques/T1140/' } ], tags: ['obfuscation', 'base64', 'eval', 'evasion'], enabled: true }, { id: 'MAL-OBF-002', name: 'Obfuscation - Multiple Encoding Layers', description: 'Detects multiple layers of encoding (base64, gzip, rot13, etc.).', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.PHP, SupportedLanguage.JAVASCRIPT, SupportedLanguage.PYTHON], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 85, patterns: [ { type: PatternType.REGEX, patternId: 'php-multi-decode', pattern: '(?:gzinflate|gzuncompress|str_rot13|base64_decode)\\s*\\(\\s*(?:gzinflate|gzuncompress|str_rot13|base64_decode)', flags: 'gi', weight: 1.0, description: 'PHP nested decoding functions' }, { type: PatternType.REGEX, patternId: 'js-multi-decode', pattern: 'atob\\s*\\([^)]*atob\\s*\\(', flags: 'gi', weight: 1.0, description: 'Nested atob calls' }, { type: PatternType.REGEX, patternId: 'eval-chain', pattern: 'eval\\s*\\([^)]*eval\\s*\\(', flags: 'gi', weight: 1.0, description: 'Nested eval calls' } ], maliciousExamples: [ { code: ``, language: SupportedLanguage.PHP, isMalicious: true, description: 'Triple-encoded PHP payload' } ], impact: { technical: 'Multiple encoding layers to evade static analysis.', business: 'Advanced evasion indicating sophisticated attack.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on payload'] }, remediation: { summary: 'Decode all layers and analyze the final payload.', steps: [ 'Recursively decode all layers', 'Analyze final payload', 'Remove malicious code', 'Investigate how it was introduced' ] }, tags: ['obfuscation', 'multi-layer', 'encoding', 'evasion'], enabled: true } ]; // ============================================================================ // STRING OBFUSCATION RULES // ============================================================================ export const stringObfuscationRules: MalwareRule[] = [ { id: 'MAL-OBF-010', name: 'Obfuscation - String Concatenation', description: 'Detects obfuscation using string concatenation to hide keywords.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.MEDIUM, confidence: ConfidenceLevel.MEDIUM, baseScore: 60, patterns: [ { type: PatternType.REGEX, patternId: 'char-concat', pattern: '([\'"]\\w[\'"]\\s*\\+\\s*){4,}[\'"]\\w[\'"]', flags: 'gi', weight: 0.8, description: 'Character-by-character concatenation' }, { type: PatternType.REGEX, patternId: 'eval-concat', pattern: '[\'"]e[\'"]\\s*\\+\\s*[\'"]v[\'"]\\s*\\+\\s*[\'"]a[\'"]\\s*\\+\\s*[\'"]l[\'"]', flags: 'gi', weight: 1.0, description: 'eval string concatenation' }, { type: PatternType.REGEX, patternId: 'window-concat', pattern: '[\'"]w[\'"]\\s*\\+\\s*[\'"]i[\'"]\\s*\\+\\s*[\'"]n[\'"]\\s*\\+\\s*[\'"]d[\'"]\\s*\\+\\s*[\'"]o[\'"]\\s*\\+\\s*[\'"]w[\'"]', flags: 'gi', weight: 0.9, description: 'window string concatenation' } ], maliciousExamples: [ { code: `var fn = 'e' + 'v' + 'a' + 'l'; window[fn]('malicious code');`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Eval obfuscation via string splitting' } ], impact: { technical: 'String splitting to hide dangerous function names.', business: 'Evasion technique to bypass static analysis.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on hidden functionality'] }, remediation: { summary: 'Normalize string concatenations and analyze the result.', steps: [ 'Reconstruct the concatenated strings', 'Identify the actual function being called', 'Remove if malicious' ] }, tags: ['obfuscation', 'string-splitting', 'concatenation'], enabled: true }, { id: 'MAL-OBF-011', name: 'Obfuscation - String.fromCharCode', description: 'Detects obfuscation using String.fromCharCode to construct strings.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 75, patterns: [ { type: PatternType.REGEX, patternId: 'fromcharcode-long', pattern: 'String\\.fromCharCode\\s*\\([^)]{50,}\\)', flags: 'gi', weight: 1.0, description: 'Long fromCharCode sequence' }, { type: PatternType.REGEX, patternId: 'fromcharcode-eval', pattern: 'eval\\s*\\([^)]*String\\.fromCharCode', flags: 'gis', weight: 1.0, description: 'fromCharCode + eval' }, { type: PatternType.REGEX, patternId: 'charcodeat-reverse', pattern: '\\.charCodeAt\\s*\\([^)]*\\)[\\s\\S]*?String\\.fromCharCode', flags: 'gis', weight: 0.8, description: 'charCodeAt encoding pattern' } ], maliciousExamples: [ { code: `eval(String.fromCharCode(100,111,99,117,109,101,110,116,46,99,111,111,107,105,101));`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'CharCode obfuscated eval' } ], impact: { technical: 'Character code encoding to hide string literals.', business: 'Advanced obfuscation indicating malicious intent.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on decoded content'] }, remediation: { summary: 'Decode character codes and analyze the resulting string.', steps: [ 'Convert character codes back to strings', 'Analyze the decoded content', 'Remove if malicious' ] }, tags: ['obfuscation', 'fromcharcode', 'encoding'], enabled: true } ]; // ============================================================================ // HEX/UNICODE OBFUSCATION RULES // ============================================================================ export const hexUnicodeRules: MalwareRule[] = [ { id: 'MAL-OBF-020', name: 'Obfuscation - Heavy Hex/Unicode Encoding', description: 'Detects excessive use of hex or unicode escape sequences indicating obfuscation.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 78, patterns: [ { type: PatternType.REGEX, patternId: 'heavy-hex-escapes', pattern: '(?:\\\\x[0-9a-fA-F]{2}){20,}', flags: 'g', weight: 1.0, description: 'Long sequence of hex escapes' }, { type: PatternType.REGEX, patternId: 'heavy-unicode-escapes', pattern: '(?:\\\\u[0-9a-fA-F]{4}){15,}', flags: 'g', weight: 1.0, description: 'Long sequence of unicode escapes' }, { type: PatternType.REGEX, patternId: 'hex-eval', pattern: 'eval\\s*\\([^)]*\\\\x', flags: 'gi', weight: 1.0, description: 'Hex escapes with eval' } ], amplifyingPatterns: [ { type: PatternType.HEURISTIC, patternId: 'high-entropy', heuristicName: 'calculateEntropy', threshold: 6.5, weight: 0.5, description: 'High entropy content' } ], maliciousExamples: [ { code: `eval("\\x64\\x6f\\x63\\x75\\x6d\\x65\\x6e\\x74\\x2e\\x63\\x6f\\x6f\\x6b\\x69\\x65");`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Hex-encoded eval payload' } ], impact: { technical: 'Hex/Unicode encoding to evade pattern matching.', business: 'Obfuscation technique for malware delivery.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on decoded payload'] }, remediation: { summary: 'Decode escape sequences and analyze the result.', steps: [ 'Decode all escape sequences', 'Analyze decoded content', 'Remove if malicious' ] }, tags: ['obfuscation', 'hex', 'unicode', 'encoding'], enabled: true } ]; // ============================================================================ // PACKER DETECTION RULES // ============================================================================ export const packerDetectionRules: MalwareRule[] = [ { id: 'MAL-OBF-030', name: 'Obfuscation - JavaScript Packer', description: 'Detects code packed with common JavaScript packers (Dean Edwards, etc.).', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.CONFIRMED, baseScore: 82, patterns: [ { type: PatternType.REGEX, patternId: 'dean-edwards-packer', pattern: 'eval\\s*\\(\\s*function\\s*\\(\\s*p\\s*,\\s*a\\s*,\\s*c\\s*,\\s*k\\s*,\\s*e\\s*,\\s*[dr]\\s*\\)', flags: 'gi', weight: 1.0, description: 'Dean Edwards packer signature' }, { type: PatternType.REGEX, patternId: 'packed-split', pattern: '\\.split\\s*\\([\'"]\\|[\'"]\\)\\s*,\\s*0\\s*,\\s*\\{\\s*\\}', flags: 'gi', weight: 0.9, description: 'Packer split pattern' }, { type: PatternType.REGEX, patternId: 'base62-dictionary', pattern: 'while\\s*\\([^)]*--\\s*\\)[^{]*\\{[^}]*\\[[^\\]]*\\]\\s*=', flags: 'gis', weight: 0.7, description: 'Base62 dictionary unpacking' } ], maliciousExamples: [ { code: `eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\\\b'+e(c)+'\\\\b','g'),k[c])}}return p}('0.1(2.3)',4,4,'document|write|alert|cookie'.split('|'),0,{}))`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Packed JavaScript code' } ], impact: { technical: 'Code compression and obfuscation using packer tools.', business: 'Hides malicious functionality from analysis.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on unpacked payload'] }, remediation: { summary: 'Unpack the code and analyze the original source.', steps: [ 'Use unpacking tools to restore original code', 'Analyze unpacked content for malicious patterns', 'Remove packed code', 'Investigate source of packed file' ] }, tags: ['obfuscation', 'packer', 'compression', 'evasion'], enabled: true }, { id: 'MAL-OBF-031', name: 'Obfuscation - Obfuscator.io Patterns', description: 'Detects code obfuscated with obfuscator.io or similar tools.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.MEDIUM, confidence: ConfidenceLevel.HIGH, baseScore: 65, patterns: [ { type: PatternType.REGEX, patternId: 'obfuscator-vars', pattern: '_0x[a-f0-9]{4,}', flags: 'gi', weight: 0.8, description: 'Obfuscator.io variable naming' }, { type: PatternType.REGEX, patternId: 'obfuscator-array', pattern: 'var\\s+_0x[a-f0-9]+\\s*=\\s*\\[[^\\]]{100,}\\];', flags: 'gi', weight: 0.9, description: 'Obfuscator.io string array' }, { type: PatternType.REGEX, patternId: 'obfuscator-shift', pattern: '_0x[a-f0-9]+\\s*=\\s*_0x[a-f0-9]+\\s*>>\\s*0x', flags: 'gi', weight: 0.7, description: 'Obfuscator bit shifting' } ], maliciousExamples: [ { code: `var _0x4f2e=['cookie','write'];(function(_0x5b0c3e,_0x4f2e75){var _0x3d7d6e=function(_0x3f8b4d){while(--_0x3f8b4d){_0x5b0c3e['push'](_0x5b0c3e['shift']());}};_0x3d7d6e(++_0x4f2e75);}(_0x4f2e,0x1f4));`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Obfuscator.io pattern' } ], falsePositivePatterns: [ { type: PatternType.REGEX, patternId: 'webpack-chunk', pattern: 'webpackChunk|__webpack_require__', flags: 'gi', weight: 0.3, description: 'Webpack bundled code (not obfuscation)' } ], impact: { technical: 'Professional obfuscation tool usage.', business: 'Intentional code hiding, requires investigation.', affectedAssets: ['Application code'], dataAtRisk: ['Depends on hidden functionality'] }, remediation: { summary: 'Deobfuscate and analyze the original code.', steps: [ 'Use deobfuscation tools', 'Analyze original functionality', 'Remove if unauthorized or malicious' ] }, tags: ['obfuscation', 'obfuscator-io', 'evasion'], enabled: true } ]; // ============================================================================ // ANTI-DEBUGGING RULES // ============================================================================ export const antiDebuggingRules: MalwareRule[] = [ { id: 'MAL-OBF-040', name: 'Anti-Debugging - DevTools Detection', description: 'Detects code that checks for browser developer tools.', version: '2.0.0', threatType: MalwareThreatType.ANTI_DEBUGGING, category: MalwareCategory.EVASION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.MEDIUM, confidence: ConfidenceLevel.MEDIUM, baseScore: 55, patterns: [ { type: PatternType.REGEX, patternId: 'debugger-statement', pattern: '\\bdebugger\\b\\s*;', flags: 'gi', weight: 0.6, description: 'Debugger statement' }, { type: PatternType.REGEX, patternId: 'console-detect', pattern: 'console\\s*\\.\\s*(?:log|warn|error)\\s*\\.\\s*toString\\s*\\(\\s*\\)', flags: 'gi', weight: 0.8, description: 'Console object manipulation' }, { type: PatternType.REGEX, patternId: 'devtools-detect', pattern: '(?:devtools|firebug)\\s*\\.|/devtools/detect', flags: 'gi', weight: 0.9, description: 'DevTools detection library' }, { type: PatternType.REGEX, patternId: 'performance-timing', pattern: 'performance\\.now\\s*\\(\\s*\\)[\\s\\S]{0,50}performance\\.now\\s*\\(\\s*\\)', flags: 'gis', weight: 0.7, description: 'Timing check (debugger detection)' } ], maliciousExamples: [ { code: `setInterval(() => { const before = performance.now(); debugger; const after = performance.now(); if (after - before > 100) { // Debugger detected window.location = 'about:blank'; } }, 1000);`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'DevTools timing detection' } ], falsePositivePatterns: [ { type: PatternType.REGEX, patternId: 'dev-environment', pattern: 'NODE_ENV.*development|process\\.env\\.NODE_ENV', flags: 'gi', weight: 0.3, description: 'Development environment check' } ], impact: { technical: 'Attempts to detect and prevent debugging.', business: 'Anti-analysis technique indicating malicious intent.', affectedAssets: ['Application behavior'], dataAtRisk: ['Analysis prevention'] }, remediation: { summary: 'Remove anti-debugging code and analyze hidden functionality.', steps: [ 'Remove debugger detection code', 'Analyze what the code is trying to hide', 'Investigate the source' ] }, tags: ['anti-debugging', 'evasion', 'devtools'], enabled: true }, { id: 'MAL-OBF-041', name: 'Anti-Debugging - Function Integrity Check', description: 'Detects checks for modified or hooked functions.', version: '2.0.0', threatType: MalwareThreatType.ANTI_DEBUGGING, category: MalwareCategory.EVASION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.MEDIUM, confidence: ConfidenceLevel.MEDIUM, baseScore: 58, patterns: [ { type: PatternType.REGEX, patternId: 'tostring-check', pattern: '\\.toString\\s*\\(\\s*\\)\\s*\\.(?:indexOf|includes|match)\\s*\\([^)]*(?:native|function)', flags: 'gis', weight: 0.8, description: 'Function.toString integrity check' }, { type: PatternType.REGEX, patternId: 'constructor-check', pattern: '\\.constructor\\s*\\.\\s*constructor\\s*===', flags: 'gi', weight: 0.7, description: 'Constructor integrity check' } ], maliciousExamples: [ { code: `if (!/native code/.test(XMLHttpRequest.toString())) { throw new Error('Function hook detected'); }`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Native function integrity check' } ], impact: { technical: 'Detects function hooking and instrumentation.', business: 'Anti-analysis technique.', affectedAssets: ['Runtime environment'], dataAtRisk: ['Analysis prevention'] }, remediation: { summary: 'Remove function integrity checks.', steps: [ 'Remove anti-hook code', 'Investigate purpose' ] }, tags: ['anti-debugging', 'integrity-check', 'evasion'], enabled: true } ]; // ============================================================================ // DEAD CODE INSERTION RULES // ============================================================================ export const deadCodeRules: MalwareRule[] = [ { id: 'MAL-OBF-050', name: 'Obfuscation - Excessive Dead Code', description: 'Detects unusual amounts of unreachable or meaningless code.', version: '2.0.0', threatType: MalwareThreatType.OBFUSCATED_CODE, category: MalwareCategory.OBFUSCATION, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.LOW, confidence: ConfidenceLevel.MEDIUM, baseScore: 40, patterns: [ { type: PatternType.REGEX, patternId: 'return-dead-code', pattern: 'return[^;]+;[\\s\\S]{100,}\\}', flags: 'gis', weight: 0.5, description: 'Code after return statement' }, { type: PatternType.REGEX, patternId: 'false-condition', pattern: 'if\\s*\\(\\s*(?:false|0)\\s*\\)\\s*\\{[^}]{50,}\\}', flags: 'gis', weight: 0.6, description: 'Always-false condition with code' }, { type: PatternType.HEURISTIC, patternId: 'code-complexity', heuristicName: 'detectObfuscationLevel', threshold: 0.7, weight: 0.7, description: 'High code complexity' } ], impact: { technical: 'Dead code insertion to confuse analysis.', business: 'Code bloat and potential hidden functionality.', affectedAssets: ['Code quality'], dataAtRisk: ['Low risk'] }, remediation: { summary: 'Remove dead code and analyze remaining functionality.', steps: [ 'Identify and remove unreachable code', 'Analyze remaining code for malicious patterns' ] }, tags: ['obfuscation', 'dead-code', 'code-quality'], enabled: true } ]; // ============================================================================ // EXPORT ALL OBFUSCATION RULES // ============================================================================ export const obfuscationRules: MalwareRule[] = [ ...base64ObfuscationRules, ...stringObfuscationRules, ...hexUnicodeRules, ...packerDetectionRules, ...antiDebuggingRules, ...deadCodeRules ]; export default obfuscationRules;