/** * @fileoverview Malware Detection Module - Type Definitions * @module rules/malware/types * * Comprehensive type definitions for the malware detection engine. * Supports multi-language analysis, AST-aware detection, and enterprise-level reporting. */ // ============================================================================ // ENUMERATIONS // ============================================================================ /** * Supported programming languages for malware detection */ export enum SupportedLanguage { JAVASCRIPT = 'javascript', TYPESCRIPT = 'typescript', PYTHON = 'python', PHP = 'php', C = 'c', CPP = 'cpp', CSHARP = 'csharp', JAVA = 'java', RUBY = 'ruby', GO = 'go', RUST = 'rust', SHELL = 'shell', POWERSHELL = 'powershell' } /** * Malware threat categories based on behavior and intent */ export enum MalwareThreatType { // Backdoors & Remote Access REVERSE_SHELL = 'reverse_shell', WEB_SHELL = 'web_shell', BACKDOOR = 'backdoor', RAT = 'remote_access_trojan', // Resource Abuse CRYPTOMINER = 'cryptominer', RESOURCE_HIJACKER = 'resource_hijacker', // Data Theft KEYLOGGER = 'keylogger', CREDENTIAL_STEALER = 'credential_stealer', TOKEN_STEALER = 'token_stealer', DATA_EXFILTRATION = 'data_exfiltration', COOKIE_STEALER = 'cookie_stealer', // Loaders & Droppers DROPPER = 'dropper', LOADER = 'loader', DOWNLOADER = 'downloader', MULTI_STAGE = 'multi_stage', // Evasion & Obfuscation OBFUSCATED_CODE = 'obfuscated_code', ANTI_DEBUGGING = 'anti_debugging', SANDBOX_EVASION = 'sandbox_evasion', // Network BOTNET = 'botnet', C2_COMMUNICATION = 'c2_communication', DNS_TUNNELING = 'dns_tunneling', // Persistence PERSISTENCE = 'persistence', FILELESS = 'fileless', LIVING_OFF_THE_LAND = 'lotl', // Supply Chain SUPPLY_CHAIN = 'supply_chain', DEPENDENCY_CONFUSION = 'dependency_confusion', TYPOSQUATTING = 'typosquatting', // Other EMBEDDED_PAYLOAD = 'embedded_payload', SUSPICIOUS_NETWORK = 'suspicious_network', TIME_BOMB = 'time_bomb', LOGIC_BOMB = 'logic_bomb' } /** * Severity levels for malware findings */ export enum MalwareSeverity { CRITICAL = 'critical', // Immediate threat, active malware HIGH = 'high', // Dangerous patterns, likely malicious MEDIUM = 'medium', // Suspicious behavior, needs review LOW = 'low', // Minor concern, potential FP INFO = 'info' // Informational, context-dependent } /** * Confidence level of the detection */ export enum ConfidenceLevel { CONFIRMED = 'confirmed', // 95%+ certainty HIGH = 'high', // 80-95% certainty MEDIUM = 'medium', // 60-80% certainty LOW = 'low', // 40-60% certainty TENTATIVE = 'tentative' // <40% certainty } /** * Pattern matching strategies */ export enum PatternType { REGEX = 'regex', LITERAL = 'literal', AST = 'ast', SEMANTIC = 'semantic', HEURISTIC = 'heuristic', BEHAVIORAL = 'behavioral' } /** * MITRE ATT&CK Tactics */ export enum MitreTactic { INITIAL_ACCESS = 'TA0001', EXECUTION = 'TA0002', PERSISTENCE = 'TA0003', PRIVILEGE_ESCALATION = 'TA0004', DEFENSE_EVASION = 'TA0005', CREDENTIAL_ACCESS = 'TA0006', DISCOVERY = 'TA0007', LATERAL_MOVEMENT = 'TA0008', COLLECTION = 'TA0009', COMMAND_AND_CONTROL = 'TA0011', EXFILTRATION = 'TA0010', IMPACT = 'TA0040' } // ============================================================================ // PATTERN INTERFACES // ============================================================================ /** * Base pattern definition */ export interface MalwarePatternBase { /** Pattern type */ type: PatternType; /** Pattern identifier for reference */ patternId?: string; /** Languages this pattern applies to (empty = all) */ languages?: SupportedLanguage[]; /** Weight for scoring (0.0 - 1.0) */ weight?: number; /** Description of what this pattern detects */ description?: string; } /** * Regex-based pattern */ export interface RegexPattern extends MalwarePatternBase { type: PatternType.REGEX; /** The regex pattern string */ pattern: string; /** Regex flags (g, i, m, s, u) */ flags?: string; /** Maximum execution time in ms (ReDoS protection) */ timeout?: number; /** Maximum matches before stopping */ maxMatches?: number; } /** * Literal string pattern */ export interface LiteralPattern extends MalwarePatternBase { type: PatternType.LITERAL; /** The literal string to match */ value: string; /** Case sensitive matching */ caseSensitive?: boolean; } /** * AST-based pattern for structural matching */ export interface AstPattern extends MalwarePatternBase { type: PatternType.AST; /** AST node type to match */ nodeType: string; /** Properties to match on the node */ properties?: Record; /** Child patterns to match */ children?: AstPattern[]; /** Parent context requirements */ parentContext?: string[]; } /** * Semantic pattern for meaning-based matching */ export interface SemanticPattern extends MalwarePatternBase { type: PatternType.SEMANTIC; /** Semantic concept to detect */ concept: string; /** Required data flows */ dataFlows?: string[]; /** Taint sources */ taintSources?: string[]; /** Taint sinks */ taintSinks?: string[]; } /** * Heuristic pattern for behavior-based detection */ export interface HeuristicPattern extends MalwarePatternBase { type: PatternType.HEURISTIC; /** Heuristic function name */ heuristicName: string; /** Threshold for triggering */ threshold?: number; /** Custom parameters */ params?: Record; } /** * Union type for all pattern types */ export type MalwarePattern = | RegexPattern | LiteralPattern | AstPattern | SemanticPattern | HeuristicPattern; // ============================================================================ // MITRE ATT&CK MAPPING // ============================================================================ /** * MITRE ATT&CK technique reference */ export interface MitreReference { /** Tactic ID (e.g., TA0002) */ tacticId: MitreTactic; /** Tactic name */ tacticName: string; /** Technique ID (e.g., T1059) */ techniqueId: string; /** Technique name */ techniqueName: string; /** Sub-technique ID if applicable */ subTechniqueId?: string; /** Sub-technique name */ subTechniqueName?: string; /** URL to MITRE documentation */ url?: string; } /** * CVE reference */ export interface CveReference { /** CVE ID (e.g., CVE-2021-44228) */ cveId: string; /** Brief description */ description: string; /** CVSS score if available */ cvssScore?: number; /** URL to CVE details */ url?: string; } // ============================================================================ // RULE DEFINITION // ============================================================================ /** * Example code for documentation */ export interface CodeExample { /** The example code */ code: string; /** Language of the example */ language: SupportedLanguage; /** Whether this is a malicious example */ isMalicious: boolean; /** Description of the example */ description: string; } /** * Impact assessment */ export interface ImpactAssessment { /** Technical impact description */ technical: string; /** Business impact description */ business: string; /** Affected assets */ affectedAssets?: string[]; /** Potential data at risk */ dataAtRisk?: string[]; } /** * Remediation guidance */ export interface RemediationGuidance { /** Short remediation summary */ summary: string; /** Detailed steps */ steps?: string[]; /** Code fix example if applicable */ codeExample?: string; /** References for more information */ references?: string[]; } /** * Rule correlation configuration */ export interface RuleCorrelation { /** Rules that increase severity when both match */ amplifyWith?: string[]; /** Rules that must also match for this rule to trigger */ requiresAlso?: string[]; /** Rules that suppress this rule when matched */ suppressedBy?: string[]; /** Severity boost when correlated rules match */ severityBoost?: number; } /** * Comprehensive malware detection rule */ export interface MalwareRule { // === Identification === /** Unique rule identifier (e.g., MAL-BACK-001) */ id: string; /** Human-readable rule name */ name: string; /** Detailed technical description */ description: string; /** Version of the rule */ version?: string; // === Classification === /** Type of malware this rule detects */ threatType: MalwareThreatType; /** Threat category */ category: MalwareCategory; /** Languages this rule applies to */ languages: SupportedLanguage[]; // === Severity & Confidence === /** Base severity level */ severity: MalwareSeverity; /** Detection confidence */ confidence: ConfidenceLevel; // === Detection Patterns === /** Primary detection patterns */ patterns: MalwarePattern[]; /** Secondary patterns that increase severity */ amplifyingPatterns?: MalwarePattern[]; /** Patterns that indicate false positive */ falsePositivePatterns?: MalwarePattern[]; // === Correlation === /** Rule correlation configuration */ correlation?: RuleCorrelation; // === Scoring === /** Base score contribution (0-100) */ baseScore?: number; /** Scoring factors */ scoringFactors?: ScoringFactors; // === Documentation === /** Example malicious code */ maliciousExamples?: CodeExample[]; /** Known false positive examples */ falsePositiveExamples?: CodeExample[]; /** Impact assessment */ impact?: ImpactAssessment; /** Remediation guidance */ remediation: RemediationGuidance; // === References === /** MITRE ATT&CK mappings */ mitreAttack?: MitreReference[]; /** Related CVEs */ cves?: CveReference[]; /** Additional reference URLs */ references?: string[]; // === Metadata === /** Tags for categorization */ tags: string[]; /** Whether the rule is enabled */ enabled: boolean; /** Author of the rule */ author?: string; /** Creation date */ createdAt?: string; /** Last update date */ updatedAt?: string; } // ============================================================================ // SCORING SYSTEM // ============================================================================ /** * Scoring factors for dynamic severity calculation */ export interface ScoringFactors { /** Patterns detected count weight */ patternCountWeight?: number; /** Obfuscation level weight */ obfuscationWeight?: number; /** Network access weight */ networkAccessWeight?: number; /** Command execution weight */ commandExecutionWeight?: number; /** Persistence mechanism weight */ persistenceWeight?: number; /** Data access weight */ dataAccessWeight?: number; } /** * Malware score breakdown */ export interface MalwareScoreBreakdown { /** Base score from rule */ baseScore: number; /** Score from pattern matches */ patternScore: number; /** Score from obfuscation detection */ obfuscationScore: number; /** Score from network indicators */ networkScore: number; /** Score from execution indicators */ executionScore: number; /** Score from persistence indicators */ persistenceScore: number; /** Score from correlation with other rules */ correlationScore: number; /** Penalty for false positive indicators */ falsePositivePenalty: number; /** Final calculated score */ totalScore: number; } /** * Complete malware score result */ export interface MalwareScore { /** Numeric score (0-100) */ score: number; /** Score breakdown */ breakdown: MalwareScoreBreakdown; /** Calculated severity from score */ calculatedSeverity: MalwareSeverity; /** Risk level description */ riskLevel: 'critical' | 'high' | 'medium' | 'low' | 'minimal'; /** Explanation of the score */ explanation: string; } // ============================================================================ // FINDINGS // ============================================================================ /** * Location of a finding in source code */ export interface SourceLocation { /** File path */ filePath: string; /** Starting line number (1-based) */ startLine: number; /** Ending line number (1-based) */ endLine: number; /** Starting column (0-based) */ startColumn?: number; /** Ending column (0-based) */ endColumn?: number; } /** * Pattern match details */ export interface PatternMatch { /** Pattern that matched */ pattern: MalwarePattern; /** Matched text */ matchedText: string; /** Location of the match */ location: SourceLocation; /** Capture groups if regex */ captures?: string[]; } /** * Complete malware finding */ export interface MalwareFinding { // === Identification === /** Unique finding ID */ id: string; /** Rule that triggered this finding */ ruleId: string; /** Rule name */ ruleName: string; // === Location === /** Source code location */ location: SourceLocation; /** Code snippet */ codeSnippet: string; /** Highlighted portion */ highlightedCode?: string; // === Classification === /** Threat type */ threatType: MalwareThreatType; /** Category */ category: MalwareCategory; /** Final severity */ severity: MalwareSeverity; /** Confidence level */ confidence: ConfidenceLevel; // === Scoring === /** Malware score */ malwareScore: MalwareScore; // === Detection Details === /** Patterns that matched */ patternMatches: PatternMatch[]; /** Correlated findings */ correlatedFindings?: string[]; // === Reporting === /** Human-readable message */ message: string; /** Detailed analysis */ analysis: string; /** Remediation guidance */ remediation: RemediationGuidance; // === References === /** MITRE ATT&CK references */ mitreAttack?: MitreReference[]; /** CVE references */ cves?: CveReference[]; // === Metadata === /** Detection timestamp */ detectedAt: string; /** Language of the code */ language: SupportedLanguage; /** Additional context */ context?: Record; } // ============================================================================ // ANALYSIS CONTEXT // ============================================================================ /** * Analysis context for rule evaluation */ export interface AnalysisContext { /** File being analyzed */ filePath: string; /** File content */ content: string; /** Detected language */ language: SupportedLanguage; /** AST if available */ ast?: unknown; /** Call graph if available */ callGraph?: unknown; /** Dependencies if available */ dependencies?: string[]; /** Is this in node_modules or vendor */ isVendorCode?: boolean; /** Is this a test file */ isTestFile?: boolean; /** Previous findings in this file */ previousFindings?: MalwareFinding[]; /** Findings from related files */ relatedFindings?: MalwareFinding[]; } /** * Analysis options */ export interface AnalysisOptions { /** Maximum findings per file */ maxFindingsPerFile?: number; /** Maximum time per rule in ms */ ruleTimeout?: number; /** Maximum time per file in ms */ fileTimeout?: number; /** Include disabled rules */ includeDisabled?: boolean; /** Minimum severity to report */ minSeverity?: MalwareSeverity; /** Minimum confidence to report */ minConfidence?: ConfidenceLevel; /** Enable AST-based detection */ enableAst?: boolean; /** Enable heuristic detection */ enableHeuristics?: boolean; /** Enable correlation analysis */ enableCorrelation?: boolean; /** Ignore vendor/node_modules */ ignoreVendor?: boolean; /** Ignore test files */ ignoreTests?: boolean; } /** * Analysis result summary */ export interface AnalysisResult { /** All findings */ findings: MalwareFinding[]; /** Summary statistics */ summary: { totalFindings: number; bySeverity: Record; byThreatType: Record; byConfidence: Record; highestScore: number; averageScore: number; }; /** Files analyzed */ filesAnalyzed: string[]; /** Analysis duration in ms */ duration: number; /** Any errors during analysis */ errors?: Array<{ file: string; rule?: string; error: string; }>; } // ============================================================================ // CATEGORIES // ============================================================================ /** * Malware finding categories */ export enum MalwareCategory { BACKDOOR = 'backdoor', CRYPTOMINER = 'cryptominer', SPYWARE = 'spyware', TROJAN = 'trojan', WORM = 'worm', RANSOMWARE = 'ransomware', ADWARE = 'adware', ROOTKIT = 'rootkit', BOTNET = 'botnet', EXPLOIT = 'exploit', DROPPER = 'dropper', OBFUSCATION = 'obfuscation', EVASION = 'evasion', SUPPLY_CHAIN = 'supply_chain', SUSPICIOUS = 'suspicious' } // ============================================================================ // ENGINE INTERFACES // ============================================================================ /** * Rule engine interface */ export interface IMalwareRuleEngine { /** Analyze a file */ analyze(context: AnalysisContext, options?: AnalysisOptions): Promise; /** Get all available rules */ getRules(): MalwareRule[]; /** Get rules by category */ getRulesByCategory(category: MalwareCategory): MalwareRule[]; /** Get rules by threat type */ getRulesByThreatType(type: MalwareThreatType): MalwareRule[]; /** Enable/disable a rule */ setRuleEnabled(ruleId: string, enabled: boolean): void; /** Add a custom rule */ addRule(rule: MalwareRule): void; /** Remove a rule */ removeRule(ruleId: string): void; } /** * Pattern matcher interface */ export interface IPatternMatcher { /** Match patterns against content */ match( content: string, patterns: MalwarePattern[], language: SupportedLanguage ): PatternMatch[]; /** Match with timeout protection */ matchWithTimeout( content: string, patterns: MalwarePattern[], language: SupportedLanguage, timeout: number ): Promise; } /** * Score calculator interface */ export interface IScoreCalculator { /** Calculate malware score for a finding */ calculateScore( rule: MalwareRule, matches: PatternMatch[], context: AnalysisContext ): MalwareScore; /** Calculate combined score for multiple findings */ calculateCombinedScore(findings: MalwareFinding[]): MalwareScore; } /** * Heuristic analyzer interface */ export interface IHeuristicAnalyzer { /** Calculate entropy of content */ calculateEntropy(content: string): number; /** Detect obfuscation level */ detectObfuscationLevel(content: string, language: SupportedLanguage): number; /** Normalize code for analysis */ normalizeCode(content: string, language: SupportedLanguage): string; /** Check for anti-debugging patterns */ hasAntiDebugging(content: string, language: SupportedLanguage): boolean; /** Check for environment-dependent activation */ hasEnvironmentChecks(content: string): boolean; }