### Computing File Hashes (MD5, SHA1, SHA256, ImpHash) with PeNet Source: https://context7.com/secana/penet/llms.txt Illustrates how to compute various cryptographic hashes and the Import Hash (ImpHash) for PE files using the PeNet library. It covers MD5, SHA1, SHA256, ImpHash, and TypeRefHash for .NET assemblies, and provides an example of comparing two files by their ImpHash for malware analysis. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Cryptographic hashes Console.WriteLine($"MD5: {peFile.Md5}"); Console.WriteLine($"SHA-1: {peFile.Sha1}"); Console.WriteLine($"SHA-256: {peFile.Sha256}"); // Import Hash (ImpHash) - used for malware family identification // Computes MD5 over normalized list of imported functions Console.WriteLine($"ImpHash: {peFile.ImpHash}"); // TypeRefHash for .NET assemblies if (peFile.IsDotNet) { Console.WriteLine($"TypeRefHash: {peFile.TypeRefHash}"); } // Example: Compare two files by ImpHash var file1 = new PeFile("sample1.exe"); var file2 = new PeFile("sample2.exe"); if (file1.ImpHash == file2.ImpHash) { Console.WriteLine("Files likely belong to the same malware family!"); } ``` -------------------------------- ### Convert PE Header Modules to String in C# Source: https://github.com/secana/penet/wiki/Home Shows how to obtain string representations of different parts of the PE header using the PeNet library. The ToString() method can be called on individual modules, such as the MSDOSHeader, or on the entire PeFile object to get a comprehensive string output of all header information. ```csharp var s = peHeader.MSDOSHeader.ToString(); ``` ```csharp var pe = peHeader.ToString() ``` -------------------------------- ### Access PE Header Information in C# Source: https://github.com/secana/penet/wiki/Home Illustrates how to access specific fields within a parsed PE header object using the PeNet library. Examples include retrieving the FileAlignment, ImageImportDescriptors, and ExportFunctions. These properties provide detailed insights into the PE file's structure and contents. ```csharp var fileAlignment = peHeader.WindowsSpecificFields.FileAlignment; ``` ```csharp var if = peHeader.peHeader.DataDirectories.ImageImportDescriptors; ``` ```csharp var ef = peHeader.DataDirectories.ExportFunctions; ``` -------------------------------- ### Get MD5 Hash of PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/filehash.md Retrieves the MD5 hash of a PE file using the PeNet library. It requires the path to the PE file as input and outputs the MD5 hash as a string. Ensure the PeNet library is installed and the file path is valid. ```csharp var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); Console.WriteLine($"MD5: {pe.Md5}"); ``` -------------------------------- ### Get SHA-256 Hash of PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/filehash.md Calculates and retrieves the SHA-256 hash of a PE file using the PeNet library. The function accepts a file path and outputs the SHA-256 hash. This is commonly used for security and verification purposes. Requires the PeNet library. ```csharp var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); Console.WriteLine($"SHA256: {pe.Sha256}"); ``` -------------------------------- ### Get SHA-1 Hash of PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/filehash.md Retrieves the SHA-1 hash of a PE file using the PeNet library. It takes the PE file path as input and returns the SHA-1 hash as a string. This functionality is useful for file integrity checks. The PeNet library must be referenced. ```csharp var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); Console.WriteLine($"SHA-1: {pe.Sha1}"); ``` -------------------------------- ### Open PE Files using PeNet Source: https://github.com/secana/penet/blob/main/docfx/articles/parseroptions.md Demonstrates how to initialize a PeFile object using different input sources such as file paths, byte arrays, streams, and memory-mapped files to optimize for memory usage and performance. ```csharp var peHeader = new PeNet.PeFile(@"C:\Windows\System32\kernel32.dll"); ``` ```csharp var bin = File.ReadAllBytes(@"C:\Windows\System32\kernel32.dll"); var peHeader = new PeNet.PeFile(bin); ``` ```csharp using var fileStream = File.OpenRead(@"C:\Windows\System32\kernel32.dll"); var peHeader = new PeNet.PeFile(fileStream); ``` ```csharp using var mmf = new PeNet.FileParser.MMFile(@"C:\Windows\System32\kernel32.dll"); var peHeader = new PeNet.PeFile(mmf); ``` -------------------------------- ### Open PE File from Disk or Byte Array Source: https://github.com/secana/penet/blob/main/docfx/index.md Demonstrates how to initialize a PeFile object by loading a PE file directly from a file path or from a byte array. This is the entry point for performing analysis on executable files. ```csharp var peHeader1 = new PeNet.PeFile(@"C:\Windows\System32\kernel32.dll"); ``` ```csharp var bin = File.ReadAllBytes(@"C:\Windows\System32\kernel32.dll"); var peHeader2 = new PeNet.PeFile(bin); ``` -------------------------------- ### Opening and Parsing PE Files in C# Source: https://context7.com/secana/penet/llms.txt Demonstrates various methods to open and parse PE files using PeNet, catering to different file sizes and memory usage requirements. It shows how to instantiate `PeFile` from file paths, byte arrays, `FileStream`, and memory-mapped files, and how to access basic file properties. ```csharp using PeNet; using PeNet.FileParser; // Option 1: From file path (entire file loaded into memory) var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Option 2: From byte array (when you already have the bytes) byte[] fileBytes = File.ReadAllBytes(@"C:\Windows\System32\kernel32.dll"); var peFromBytes = new PeFile(fileBytes); // Option 3: From FileStream (low memory, but slower access) using var fileStream = File.OpenRead(@"C:\Windows\System32\kernel32.dll"); var peFromStream = new PeFile(fileStream); // Option 4: From memory-mapped file (best for large files) using var mmf = new MMFile(@"C:\Windows\System32\kernel32.dll"); var peFromMmf = new PeFile(mmf); // Check file properties Console.WriteLine($"Is 64-bit: {peFile.Is64Bit}"); Console.WriteLine($"Is DLL: {peFile.IsDll}"); Console.WriteLine($"Is EXE: {peFile.IsExe}"); Console.WriteLine($"Is .NET: {peFile.IsDotNet}"); Console.WriteLine($"Is Driver: {peFile.IsDriver}"); Console.WriteLine($"File Size: {peFile.FileSize} bytes"); ``` -------------------------------- ### Access and Parse Base Relocation Information in C# Source: https://context7.com/secana/penet/llms.txt This snippet demonstrates how to load a PE file using PeNet and iterate through the ImageRelocationDirectory. It extracts block virtual addresses and interprets individual relocation entries by decoding their type and offset values. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Access Base Relocation Directory var relocations = peFile.ImageRelocationDirectory; if (relocations != null) { Console.WriteLine($"Base Relocations ({relocations.Length} blocks):"); foreach (var reloc in relocations.Take(5)) // First 5 blocks { Console.WriteLine($"\nBlock at VA: 0x{reloc.VirtualAddress:X}"); Console.WriteLine($" Size of Block: {reloc.SizeOfBlock}"); var entries = reloc.TypeOffsets; if (entries != null) { Console.WriteLine($" Entries ({entries.Length}):"); foreach (var entry in entries.Take(10)) // First 10 entries { var type = (entry >> 12) & 0xF; var offset = entry & 0xFFF; string typeName = type switch { 0 => "ABSOLUTE", 1 => "HIGH", 2 => "LOW", 3 => "HIGHLOW", 4 => "HIGHADJ", 10 => "DIR64", _ => $"UNKNOWN({type})" }; Console.WriteLine($" Type: {typeName}, Offset: 0x{offset:X}"); } } } } ``` -------------------------------- ### Access TLS, Load Config, and Exception Directories Source: https://context7.com/secana/penet/llms.txt Shows how to extract advanced metadata from a PE file, including Thread Local Storage (TLS) settings, Load Configuration data (like CFG and security cookies), and x64 Exception directory information. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Access TLS Directory var tlsDirectory = peFile.ImageTlsDirectory; if (tlsDirectory != null) { Console.WriteLine($"TLS Start Address: 0x{tlsDirectory.StartAddressOfRawData:X}"); } // Access Load Config Directory var loadConfig = peFile.ImageLoadConfigDirectory; if (loadConfig != null) { Console.WriteLine($"Security Cookie: 0x{loadConfig.SecurityCookie:X}"); } // Access Exception Directory (x64) var exceptionDir = peFile.ExceptionDirectory; if (exceptionDir != null && peFile.Is64Bit) { foreach (var runtimeFunc in exceptionDir.Take(5)) { Console.WriteLine($"Begin: 0x{runtimeFunc.BeginAddress:X}"); } } ``` -------------------------------- ### Add Imports to PE Files with PeNet Source: https://context7.com/secana/penet/llms.txt Demonstrates how to load a PE file, inject single or multiple API imports from various DLLs, and save the modified binary. Note that this process will invalidate existing Authenticode signatures. ```csharp using PeNet; // Load the PE file var peFile = new PeFile("application.exe"); Console.WriteLine("Original imports:"); foreach (var import in peFile.ImportedFunctions ?? Array.Empty()) { Console.WriteLine($" {import.DLL} - {import.Name}"); } // Add a single import peFile.AddImport("user32.dll", "MessageBoxA"); // Add multiple imports from different DLLs var additionalImports = new List { new AdditionalImport("kernel32.dll", new List { "VirtualAlloc", "VirtualFree", "GetProcAddress" }), new AdditionalImport("advapi32.dll", new List { "RegOpenKeyExA", "RegCloseKey" }), new AdditionalImport("ws2_32.dll", new List { "WSAStartup", "socket", "connect" }) }; peFile.AddImports(additionalImports); // Save the modified file File.WriteAllBytes("patched_application.exe", peFile.RawFile.ToArray()); ``` -------------------------------- ### Extract Resources and Icons using PeNet Source: https://context7.com/secana/penet/llms.txt Shows how to access embedded version information and extract icon resources from a PE file. It demonstrates saving icons as individual ICO files and handling icon groups. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\notepad.exe"); // Access Resources var resources = peFile.Resources; if (resources != null) { // Version Information var versionInfo = resources.VsVersionInfo; if (versionInfo != null) { Console.WriteLine("Version Information:"); Console.WriteLine($" File Version: {versionInfo.VsFixedFileInfo?.FileVersion}"); Console.WriteLine($" Product Version: {versionInfo.VsFixedFileInfo?.ProductVersion}"); // Access string tables for additional info var stringFileInfo = versionInfo.StringFileInfo; if (stringFileInfo != null) { foreach (var stringTable in stringFileInfo.StringTable ?? Array.Empty()) { foreach (var entry in stringTable.Strings ?? Array.Empty()) { Console.WriteLine($" {entry.SzKey}: {entry.Value}"); } } } } // Icons var icons = resources.Icons; if (icons != null) { Console.WriteLine($"\nFound {icons.Length} icons"); } } // Extract all icons as ICO files var iconBytes = peFile.Icons(); int iconIndex = 0; foreach (var ico in iconBytes) { File.WriteAllBytes($"icon_{iconIndex++}.ico", ico); Console.WriteLine($"Saved icon_{iconIndex - 1}.ico ({ico.Length} bytes)"); } // Extract grouped icons (maintains icon groups) var groupIcons = peFile.GroupIcons(); int groupIndex = 0; foreach (var group in groupIcons) { int subIndex = 0; foreach (var ico in group) { File.WriteAllBytes($"group{groupIndex}_icon{subIndex++}.ico", ico); } groupIndex++; } ``` -------------------------------- ### Authenticode Signature Verification and Certificate Info with PeNet Source: https://context7.com/secana/penet/llms.txt Shows how to verify Authenticode digital signatures on PE files and access associated certificate information using the PeNet library. It covers checking signature validity, trust status, and retrieving details of the signing certificate, including its subject, issuer, serial number, validity period, and thumbprint. It also demonstrates certificate chain validation and retrieving CRL distribution points. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Check if file is signed Console.WriteLine($"Is Authenticode Signed: {peFile.IsAuthenticodeSigned}"); Console.WriteLine($"Has Valid Signature: {peFile.HasValidAuthenticodeSignature}"); Console.WriteLine($"Is Trusted Signature: {peFile.IsTrustedAuthenticodeSignature}"); // Access Authenticode information var authInfo = peFile.AuthenticodeInfo; if (authInfo != null) { Console.WriteLine($"Is Valid: {authInfo.IsAuthenticodeValid}"); Console.WriteLine($"Signer Serial: {authInfo.SignerSerialNumber}"); // Access signing certificate var cert = authInfo.SigningCertificate; if (cert != null) { Console.WriteLine($"\nSigning Certificate:"); Console.WriteLine($" Subject: {cert.Subject}"); Console.WriteLine($" Issuer: {cert.Issuer}"); Console.WriteLine($" Serial Number: {cert.SerialNumber}"); Console.WriteLine($" Valid From: {cert.NotBefore}"); Console.WriteLine($" Valid To: {cert.NotAfter}"); Console.WriteLine($" Thumbprint: {cert.Thumbprint}"); } } // Validate certificate chain (with online CRL check) bool isValidChain = peFile.HasValidAuthenticodeCertChain(useOnlineCrl: true); Console.WriteLine($"Certificate Chain Valid: {isValidChain}"); // Get Certificate Revocation List URLs var crlList = peFile.GetCrlUrlList(); if (crlList != null) { Console.WriteLine("\nCRL Distribution Points:"); foreach (var url in crlList.Urls ?? Array.Empty()) { Console.WriteLine($" {url}"); } } ``` -------------------------------- ### Testing and Safe Parsing of PE Files in C# Source: https://context7.com/secana/penet/llms.txt Illustrates how to safely check if a file is a valid PE file using `IsPeFile` and `TryParse` methods in PeNet. These methods prevent exceptions when dealing with non-PE files and can be used with various input types like file paths, byte arrays, streams, and memory-mapped files. ```csharp using PeNet; using PeNet.FileParser; var filePath = @"C:\Windows\System32\kernel32.dll"; // Quick check if file is a PE file bool isPeFile = PeFile.IsPeFile(filePath); Console.WriteLine($"Is PE file: {isPeFile}"); // Check from byte array byte[] bytes = File.ReadAllBytes(filePath); bool isPeFromBytes = PeFile.IsPeFile(bytes); // Check from stream using var stream = File.OpenRead(filePath); bool isPeFromStream = PeFile.IsPeFile(stream); // Check from memory-mapped file using var mmf = new MMFile(filePath); bool isPeFromMmf = PeFile.IsPeFile(mmf); // Safe parsing with TryParse - returns false if not a PE file if (PeFile.TryParse(filePath, out var peFile)) { Console.WriteLine($"Successfully parsed: {peFile!.Is64Bit}"); } else { Console.WriteLine("File is not a valid PE file"); } // TryParse also works with byte arrays, streams, and MMFile if (PeFile.TryParse(bytes, out var peFromBytes)) { Console.WriteLine($"Parsed from bytes: {peFromBytes!.IsDll}"); } ``` -------------------------------- ### Accessing Exported Functions in PE Files using PeNet Source: https://context7.com/secana/penet/llms.txt Demonstrates how to access the Export Directory and parsed exported functions of a PE file using the PeNet library. It shows how to retrieve information like the DLL name, number of functions, and details for each exported function, including its name, ordinal, address, and whether it's forwarded. ```csharp using PeNet; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Access Export Directory var exportDir = peFile.ImageExportDirectory; if (exportDir != null) { Console.WriteLine($"Export DLL Name: {exportDir.Name}"); Console.WriteLine($"Number of Functions: {exportDir.NumberOfFunctions}"); Console.WriteLine($"Number of Names: {exportDir.NumberOfNames}"); Console.WriteLine($"Ordinal Base: {exportDir.Base}"); } // Access parsed exported functions var exportedFunctions = peFile.ExportedFunctions; if (exportedFunctions != null) { Console.WriteLine($"\nExported Functions ({exportedFunctions.Length} total):"); foreach (var func in exportedFunctions.Take(20)) // First 20 functions { if (func.HasName) { Console.WriteLine($" {func.Name} (Ordinal: {func.Ordinal}, Address: 0x{func.Address:X})"); } else { Console.WriteLine($" [Ordinal {func.Ordinal}] (Address: 0x{func.Address:X})"); } // Check if function is forwarded if (func.HasForward) { Console.WriteLine($" -> Forwarded to: {func.ForwardName}"); } } } ``` -------------------------------- ### Calculate Import Hash (ImpHash) in C# Source: https://github.com/secana/penet/wiki/Home Demonstrates how to compute the Import Hash (ImpHash) for a PE file using the PeNet library. The ImpHash is a valuable tool in malware analysis. The library provides both a GetImpHash() method and an ImpHash property for accessing this value. ```csharp var ih = peHeader.GetImpHash(); ``` ```csharp var ih = peHeader.ImpHash ``` -------------------------------- ### TryParse PE Files Source: https://github.com/secana/penet/blob/main/docfx/articles/parseroptions.md Demonstrates the TryParse pattern to safely validate and parse a PE file in a single operation, returning a boolean status and the parsed object via an out parameter. ```csharp using PeNet; var file = @"C:\Windows\System32\kernel32.dll"; var isPe1 = PeFile.TryParse(file, out var peFile); var buff = File.ReadAllBytes(file); var isPe2 = PeFile.TryParse(buff, out var peFile); using var fs = File.OpenRead(file); var isPe3 = PeFile.TryParse(fs, out var peFile); using var mmf = new MMFile(file); var isPe4 = PeFile.TryParse(mmf, out var peFile); ``` -------------------------------- ### Access PE Header Information Source: https://github.com/secana/penet/blob/main/docfx/index.md Shows how to extract specific metadata from a parsed PE file, including file alignment, import descriptors, and lists of imported or exported functions. ```csharp var fileAlignment = peHeader.WindowsSpecificFields.FileAlignment; var importDescriptors = peHeader.DataDirectories.ImageImportDescriptors; var importedFunctions = peHeader.ImportedFunctions; var exportedFunctions = peHeader.ExportedFunctions; ``` -------------------------------- ### Add Multiple Imports to PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/imports.md Demonstrates adding multiple imports to a PE file, which can be from the same or different modules. This method is useful for bulk import additions. If the PE file is signed, the signature will be invalidated. Requires a PeFile object and a list of AdditionalImport objects. ```csharp var peFile = new PeFile("myapp.exe"); var ai1 = new AdditionalImport("gdi32.dll", new List { "StartPage" }); var ai2 = new AdditionalImport("ADVAPI32.dll", new List { "RegCloseKey" }); var importList = new List {ai1, ai2}; peFile.AddImports(importList); ``` -------------------------------- ### Access PE File Import Descriptors (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/imports.md Demonstrates how to retrieve IMAGE_IMPORT_DESCRIPTOR, IMAGE_BOUND_IMPORT_DESCRIPTOR, and IMAGE_DELAY_IMPORT_DESCRIPTOR arrays from a PE file. Requires a PeFile object initialized with the path to the executable. ```csharp var peFile = new PeFile("myapp.exe"); var idescs = peFile.ImageImportDescriptors; var bdescs = peFile.ImageBoundImportDescriptor; var ddescs = peFile.ImageDelayImportDescriptor; ``` -------------------------------- ### Extract Debug and PDB Information using PeNet Source: https://context7.com/secana/penet/llms.txt Demonstrates how to access the ImageDebugDirectory of a PE file to retrieve PDB metadata. It includes logic to parse CodeView PDB v7.0 information and construct a Microsoft Symbol Server URL. ```csharp using PeNet; using System.Linq; var peFile = new PeFile(@"C:\Windows\System32\kernel32.dll"); // Access Debug Directory entries var debugDirectories = peFile.ImageDebugDirectory; if (debugDirectories != null) { foreach (var debugDir in debugDirectories) { Console.WriteLine($"Debug Type: {debugDir.Type}"); Console.WriteLine($" Timestamp: {debugDir.TimeDateStamp}"); Console.WriteLine($" Major Version: {debugDir.MajorVersion}"); Console.WriteLine($" Minor Version: {debugDir.MinorVersion}"); Console.WriteLine($" Size of Data: {debugDir.SizeOfData}"); Console.WriteLine($" Address of Raw Data: 0x{debugDir.AddressOfRawData:X}"); // Access Code View PDB v7.0 information var pdbInfo = debugDir.CvInfoPdb70; if (pdbInfo != null) { Console.WriteLine($"\n PDB Information:"); Console.WriteLine($" CV Signature: {pdbInfo.CvSignature}"); Console.WriteLine($" Signature (GUID): {pdbInfo.Signature}"); Console.WriteLine($" Age: {pdbInfo.Age}"); Console.WriteLine($" PDB File Name: {pdbInfo.PdbFileName}"); // Build Microsoft Symbol Server URL var guid = pdbInfo.Signature.ToString("N").ToUpper(); var symbolUrl = $"https://msdl.microsoft.com/download/symbols/{pdbInfo.PdbFileName}/{guid}{pdbInfo.Age}/{pdbInfo.PdbFileName}"; Console.WriteLine($" Symbol Server URL: {symbolUrl}"); } } } ``` -------------------------------- ### Accessing ImpHash in C# with PeNet Source: https://github.com/secana/penet/blob/main/docfx/articles/imphash.md Demonstrates how to access the Import Hash (ImpHash) property from a PE header object using the PeNet library. This property provides a hash value derived from the imported functions of a Portable Executable file. ```csharp var ih = peHeader.ImpHash ``` -------------------------------- ### Match patterns in PE files using Aho-Corasick Source: https://github.com/secana/penet/wiki/Pattern-Matching Demonstrates building a Trie structure to store patterns and executing a scan against a PE file buffer. This approach allows for efficient multi-pattern matching across multiple binary files. ```C# var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); var trie = new PeNet.PatternMatching.Trie(); // Add string patterns which should match on ASCII encoded strings in the PE file. trie.Add("MicrosoftCalculator", Encoding.ASCII, "pattern1"); trie.Add(" idb.CvInfoPdb70 != null) .CvInfoPdb70; // Print content of the Code View PDB v7 structure Console.WriteLine(pdbInfo); } } } ``` -------------------------------- ### Modify PE File Sections with PeNet (C#) Source: https://context7.com/secana/penet/llms.txt This C# code snippet illustrates how to modify Portable Executable (PE) files using the PeNet library. It covers adding new sections with or without initial content, and removing existing sections while optionally preserving their content. This is useful for tasks like instrumentation or analysis. Dependencies include the PeNet library and System.IO. ```csharp using PeNet; using PeNet.Header.Pe; // Load the PE file (must use byte array or file path for modifications) var peFile = new PeFile("application.exe"); Console.WriteLine($"Original sections: {peFile.ImageSectionHeaders?.Length}"); foreach (var section in peFile.ImageSectionHeaders ?? Array.Empty()) { Console.WriteLine($" {section.Name}"); } // Add a new section // Section characteristics: 0x40000040 = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA var characteristics = (ScnCharacteristicsType)0x40000040; peFile.AddSection(".mydata", 4096, characteristics); Console.WriteLine($"\nAfter adding section: {peFile.ImageSectionHeaders?.Length}"); // Add section with initial content byte[] sectionContent = new byte[512]; // Fill with your data... Array.Fill(sectionContent, (byte)0x90); // NOP instructions peFile.AddSection(".code", sectionContent, (ScnCharacteristicsType)0x60000020); // RWX // Remove a section (removes from section table and optionally removes content) peFile.RemoveSection(".mydata", removeContent: true); // Remove section but keep content in file peFile.RemoveSection(".rsrc", removeContent: false); Console.WriteLine($"\nAfter removing sections: {peFile.ImageSectionHeaders?.Length}"); // Save modified PE file File.WriteAllBytes("modified_application.exe", peFile.RawFile.ToArray()); ``` -------------------------------- ### Retrieve Cryptographic Hashes using PeNet Source: https://github.com/secana/penet/wiki/File-Information Retrieves various file hashes including MD5, SHA-1, SHA-256, and the Import Hash (ImpHash). These properties provide integrity verification and identification for the loaded PE file. ```C# var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); Console.WriteLine($"MD5: {pe.MD5}"); Console.WriteLine($"SHA-1: {pe.SHA1}"); Console.WriteLine($"SHA-256: {pe.SHA256}"); Console.WriteLine($"ImpHash: {pe.ImpHash}"); ``` -------------------------------- ### Access Imported Functions in PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/imports.md Provides a shortcut to access imported functions, sorted by their module/DLL. It iterates through all imported functions and prints details like DLL name, function name, hint, and IAT offset. Requires a PeFile object. ```csharp var peFile = new PeFile("myapp.exe"); // Print all imported modules with their corresponding functions. foreach(var imp in peFile.ImportedFunctions) { Console.WriteLine($"{imp.DLL} - {imp.Name} - {imp.Hint} - {imp.IATOffset}"); } ``` -------------------------------- ### Inspect .NET Assembly Metadata with PeNet (C#) Source: https://context7.com/secana/penet/llms.txt This C# code snippet demonstrates how to use the PeNet library to access and display metadata for CLR assemblies. It checks if a file is a .NET assembly and retrieves information such as the CLR header, metadata streams, module version IDs, and COM TypeLib ID. Dependencies include the PeNet library. ```csharp using PeNet; var peFile = new PeFile("ManagedAssembly.dll"); // Check if it's a .NET assembly if (!peFile.IsDotNet) { Console.WriteLine("Not a .NET assembly"); return; } Console.WriteLine(".NET Assembly Information:"); // Access CLR Header (IMAGE_COR20_HEADER) var clrHeader = peFile.ImageComDescriptor; if (clrHeader != null) { Console.WriteLine($"CLR Runtime Version: {clrHeader.MajorRuntimeVersion}.{clrHeader.MinorRuntimeVersion}"); Console.WriteLine($"Flags: {clrHeader.Flags}"); Console.WriteLine($"Entry Point Token: 0x{clrHeader.EntryPointTokenOrRva:X}"); } // Access Metadata Header var metaDataHdr = peFile.MetaDataHdr; if (metaDataHdr != null) { Console.WriteLine($"\nMetadata Version: {metaDataHdr.Version}"); } // Access Metadata Streams var stringStream = peFile.MetaDataStreamString; Console.WriteLine($"String Stream available: {stringStream != null}"); var usStream = peFile.MetaDataStreamUs; // User strings Console.WriteLine($"User String Stream available: {usStream != null}"); var guidStream = peFile.MetaDataStreamGuid; Console.WriteLine($"GUID Stream available: {guidStream != null}"); var blobStream = peFile.MetaDataStreamBlob; Console.WriteLine($"Blob Stream available: {blobStream != null}"); // Access Tables Header var tablesHeader = peFile.MetaDataStreamTablesHeader; Console.WriteLine($"Tables Header available: {tablesHeader != null}"); // CLR Module Version IDs var moduleVersionIds = peFile.ClrModuleVersionIds; if (moduleVersionIds != null) { Console.WriteLine("\nModule Version IDs:"); foreach (var mvid in moduleVersionIds) { Console.WriteLine($" {mvid}"); } } // TypeLib ID (if COM interop) var typeLibId = peFile.ClrComTypeLibId; if (typeLibId.HasValue) { Console.WriteLine($"COM TypeLib ID: {typeLibId.Value}"); } // TypeRefHash for .NET malware analysis var typeRefHash = peFile.TypeRefHash; Console.WriteLine($"\nTypeRefHash: {typeRefHash}"); ``` -------------------------------- ### Add Single Import to PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/imports.md Shows how to add a single import to a PE file. Note that if the PE file is signed, adding imports will invalidate the signature. Requires a PeFile object and the DLL name and function name to add. ```csharp var peFile = new PeFile("myapp.exe"); peFile.AddImport("gdi32.dll", "StartPage"); ``` -------------------------------- ### Retrieve File Size using PeNet Source: https://github.com/secana/penet/wiki/File-Information Accesses the total size of the binary file in bytes. This property is part of the PeFile class and requires a valid file path to initialize. ```C# var pe = new PeNet.PeFile(@"c:\windows\system32\calc.exe"); Console.WriteLine($"File Size {pe.FileSize}"); ``` -------------------------------- ### Access PE File Sections (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/sections.md Retrieves all section table entries from a PE file. This requires an instance of the PeFile class, which takes the file path as a constructor argument. The result is an array of ImageSectionHeader objects. ```csharp var peFile = new PeFile("myapp.exe"); // Get array with all section table entries. var sections = peFile.ImageSectionHeaders; ``` -------------------------------- ### Calculate and Print TypeRefHash (TRH) in C# Source: https://github.com/secana/penet/blob/main/docfx/articles/typerefhash.md This C# code snippet demonstrates how to calculate the TypeRefHash (TRH) for a given .NET file. It utilizes the PeFile class to access the TRH property and prints it as a hexadecimal string. This is useful for identifying .NET malware families with shared code. ```csharp var peFile = new PeFile(file); // get the TRH as a hex-string. var trh = peFile.TypeRefHash; Console.WriteLine(trh); // prints for example the TRH: // > d633db771449e2c37e1689a8c291a4f4646ce156652a9dad5f67394c0d92a8c4 ``` -------------------------------- ### Add Section to PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/sections.md Adds a new section to the end of a PE file. The function requires the section name (max 8 characters), size, and characteristics. An existing PeFile instance is needed to perform this operation. ```csharp var peFile = new PeFile("myapp.exe"); // Add a new section with the name ".name", the size 100 and section characteristics. // Section names have a max. length of 8 characters. peFile.AddSection(".name", 100, (ScnCharacteristicsType)0x40000040); ``` -------------------------------- ### Remove Section from PE File (C#) Source: https://github.com/secana/penet/blob/main/docfx/articles/sections.md Removes a specified section from a PE file, either by removing both the section table entry and its content, or by only removing the section table entry. This operation requires a PeFile instance and the name of the section to be removed. ```csharp var peFile = new PeFile("myapp.exe"); // Remove the resource section from the section table and the content // of the section from the file. peFile.RemoveSection(".rsrc"); // Alternatively you can only remove the section from the section table // and keep the content of the section in the file. peFile.RemoveSection(".rsrc", false); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.