### Malduck Installation Source: https://github.com/cert-polska/malduck/blob/master/README.md Command to install the Malduck library using pip. This is the standard method for installing Python packages. ```shell pip install malduck ``` -------------------------------- ### APLib Decompression Example Source: https://github.com/cert-polska/malduck/blob/master/README.md Illustrates decompression of a headerless buffer compressed using the APLib algorithm. The input is a bytes object containing the compressed data. ```python from malduck import aplib # Headerless compressed buffer aplib(b'T\x00he quick\xecb\x0erown\xcef\xaex\x80jumps\xed\xe4veur`t?lazy\xead\xfeg\xc0\x00') ``` -------------------------------- ### Serpent Encryption Example Source: https://github.com/cert-polska/malduck/blob/master/README.md Shows how to perform encryption using the Serpent cipher in CBC mode. Requires a key, plaintext, and an initialization vector. The order of plaintext and IV parameters differs from AES. ```python from malduck import serpent key = b'a'*16 iv = b'b'*16 plaintext = b'data'*16 ciphertext = serpent.cbc.encrypt(key, plaintext, iv) ``` -------------------------------- ### Extractor Engine Module Example Source: https://github.com/cert-polska/malduck/blob/master/README.md Defines a custom extractor module for the 'citadel' family using Malduck's Extractor class. It includes methods to find specific strings and extract associated data, demonstrating how to override default behavior and handle different string matches. ```python from malduck import Extractor class Citadel(Extractor): family = "citadel" yara_rules = ("citadel",) overrides = ("zeus",) @Extractor.string("briankerbs") def citadel_found(self, p, addr, match): log.info('[+] `Coded by Brian Krebs` str @ %X' % addr) return True @Extractor.string def cit_login(self, p, addr, match): log.info('[+] Found login_key xor @ %X' % addr) hit = p.uint32v(addr + 4) print(hex(hit)) if p.is_addr(hit): return {'login_key': p.asciiz(hit)} hit = p.uint32v(addr + 5) print(hex(hit)) if p.is_addr(hit): return {'login_key': p.asciiz(hit)} ``` -------------------------------- ### Memory Model PE Resource Extraction Source: https://github.com/cert-polska/malduck/blob/master/README.md Demonstrates how to open a PE file using Malduck's procmempe module and extract specific resources by name. The 'image=True' argument indicates that the file should be treated as an image. ```python from malduck import procmempe with procmempe.from_file("notepad.exe", image=True) as p: resource_data = p.pe.resource("NPENCODINGDIALOG") ``` -------------------------------- ### Packing/Unpacking Bytes (p64/u64) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use p64() for packing integers into 64-bit byte strings and u64() for unpacking them. Supports various integer sizes (8, 16, 32, 64). ```python p64(1234567890123456789) # Output: b'\x12A\x91\x04\x00\x00\x00\x00' u64(b'\x12A\x91\x04\x00\x00\x00\x00') # Output: 1234567890123456789 ``` -------------------------------- ### Disassemble Process Memory with Malduck Source: https://context7.com/cert-polska/malduck/llms.txt Demonstrates how to load a memory dump and disassemble instructions by size or count, including operand inspection. ```python with procmem.from_file("dump.bin", base=0x400000) as p: # Disassemble by size for ins in p.disasmv(0x401000, size=0x100): print(f"{hex(ins.addr)}: {ins.mnem}") # Access operands if ins.op1: if ins.op1.is_reg: print(f" op1 register: {ins.op1.reg}") elif ins.op1.is_imm: print(f" op1 immediate: {hex(ins.op1.value)}") elif ins.op1.is_mem: mem = ins.op1.mem print(f" op1 memory: {mem.size} [{mem.base}+{hex(mem.disp)}]") # Disassemble by instruction count for ins in p.disasmv(0x401000, count=10, x64=True): # Find mov instructions with immediate values if ins.mnem == 'mov' and ins.op2 and ins.op2.is_imm: print(f"MOV with immediate: {hex(ins.op2.value)}") # Create instruction for comparison expected = insn(mnem='mov', op1='eax', addr=0x401000) ``` -------------------------------- ### Yara Rule Matching in Malduck Source: https://context7.com/cert-polska/malduck/llms.txt Shows how to define Yara rules programmatically, match them against data, and perform memory-aware matching using ProcessMemory. ```python from malduck import procmem, Yara, YaraString # Define rules in Python ruleset = Yara( name="MalwareRule", strings={ "mz_header": YaraString("MZ", ascii=True), "pe_sig": YaraString("PE\x00\x00", ascii=True), "hex_pattern": YaraString("4D 5A ?? ?? 50 45 00 00", type=YaraString.HEX), "url": YaraString(r"https?://[\w./]+", type=YaraString.REGEX), }, condition="$mz_header at 0 and $pe_sig" ) # Match against data match = ruleset.match(data=b'MZ...\x00PE\x00\x00...') if match: print("Rule matched!") # Access matched strings if "mz_header" in match.MalwareRule: offsets = match.MalwareRule["mz_header"] print(f"MZ header found at offsets: {offsets}") # Load rules from directory ruleset = Yara.from_dir("/path/to/yara/rules", recursive=True) # Match with ProcessMemory (virtual address mapping) with procmem.from_file("dump.bin", base=0x400000) as p: # Non-region-wise matching (raw offsets) matches = p.yarap(ruleset) # Region-wise matching (virtual addresses) matches = p.yarav(ruleset) # Extended info with string content matches = p.yarav(ruleset, extended=True) for rule_name in matches.keys(): rule_match = matches[rule_name] for string_id in rule_match.keys(): for string_match in rule_match[string_id]: print(f"{string_id} at {hex(string_match.offset)}: {string_match.content}") ``` -------------------------------- ### Null-terminated ASCII String (asciiz) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use asciiz() to convert a Python string to a null-terminated byte string. Ensure the input string is ASCII compatible. ```python asciiz('hello') # Output: b'hello\x00' ``` -------------------------------- ### Perform Binary String Operations Source: https://context7.com/cert-polska/malduck/llms.txt Utility functions for packing/unpacking integers, hex encoding, base64, padding, and string manipulation. ```python from malduck import ( u32, u16, u8, p32, p16, p8, # Little-endian pack/unpack u32be, u16be, p32be, # Big-endian variants enhex, unhex, # Hex encode/decode base64, # Base64 decode pad, unpad, pkcs7, unpkcs7, # Padding utilities chunks, asciiz, utf16z, # String utilities bigint # Arbitrary-size integers ) # Unpack integers from binary data data = b'\xef\xbe\xad\xde\x00\x00\x00\x00' dword_value = u32(data) # 0xDEADBEEF word_value = u16(data) # 0xBEEF byte_value = u8(data) # 0xEF # With offset second_dword = u32(data, offset=4) # 0x00000000 # Pack integers to bytes packed = p32(0xDEADBEEF) # b'\xef\xbe\xad\xde' packed_be = p32be(0xDEADBEEF) # b'\xde\xad\xbe\xef' # Hex encode/decode hex_str = enhex(b'hello') # b'68656c6c6f' decoded = unhex('68656c6c6f') # b'hello' # Base64 decode decoded = base64.decode(b'SGVsbG8gV29ybGQ=') # b'Hello World' encoded = base64.encode(b'Hello World') # PKCS7 padding padded = pad(b'data', 16) # Pad to 16-byte boundary unpadded = unpad(padded) # Remove PKCS7 padding # Split data into chunks data_chunks = chunks(b'AABBCCDD', 2) # [b'AA', b'BB', b'CC', b'DD'] # Null-terminated strings ascii_str = asciiz(b'hello\x00world') # b'hello' utf16_str = utf16z(b'h\x00i\x00\x00\x00') # b'hi' # Arbitrary-size integers (for RSA keys, etc.) big_value = bigint.unpack(b'\x01\x02\x03\x04\x05\x06\x07\x08') packed_big = bigint.pack(0x123456789ABCDEF0, size=8) ``` -------------------------------- ### Load and Parse PE File Source: https://context7.com/cert-polska/malduck/llms.txt Load a PE file from binary data using the `PE` class and access its structure, directory entries, and sections. This is useful for analyzing PE files directly without a `ProcessMemory` wrapper. ```python from malduck import pe, PE # Load PE from file data with open("malware.exe", "rb") as f: pe_obj = PE(f.read()) # Access PE structure print(f"Image Base: {hex(pe_obj.optional_header.ImageBase)}") print(f"Entry Point: {hex(pe_obj.optional_header.AddressOfEntryPoint)}") print(f"64-bit: {pe_obj.is64bit}") # Get directory entries import_dir = pe_obj.directory("IMPORT") export_dir = pe_obj.directory("EXPORT") resource_dir = pe_obj.directory("RESOURCE") # Get section code_section = pe_obj.section(".text") data_section = pe_obj.section(".data") # Extract resources by type or name icon = pe_obj.resource("RT_ICON") manifest = pe_obj.resource("RT_MANIFEST") custom = pe_obj.resource(b"MYCONFIG") by_id = pe_obj.resource(101) # Numeric identifier # Iterate all resources for data in pe_obj.resources("RT_RCDATA"): print(f"RCDATA resource: {len(data)} bytes") # Validation checks (useful for detecting dumps vs files) if pe_obj.validate_import_names(): print("Import table looks valid") if pe_obj.validate_resources(): print("Resource table looks valid") if pe_obj.validate_padding(): print("Not a memory dump") ``` -------------------------------- ### Fixed-Integer Types Reference Source: https://github.com/cert-polska/malduck/blob/master/docs/ints.md Overview of the fixed-integer types supported by the Malduck framework. ```APIDOC ## Fixed-Integer Types ### Description This section defines the fixed-integer data types available in the system, categorized by bit-width and signedness. ### Unsigned Types - **UInt64** (QWORD) - **UInt32** (DWORD) - **UInt16** (WORD) - **UInt8** (BYTE) ### Signed Types - **Int64** - **Int32** - **Int16** - **Int8** ``` -------------------------------- ### Bitwise Utilities Source: https://context7.com/cert-polska/malduck/llms.txt Functions for bitwise rotation and memory alignment, useful for implementing custom hash algorithms. ```python from malduck import rol, ror, align, align_down # Bitwise rotate left/right (default: 32-bit) rotated = rol(0x12345678, 8) # Rotate left by 8 bits rotated = ror(0x12345678, 8) # Rotate right by 8 bits # 64-bit rotation rotated_64 = rol(0x123456789ABCDEF0, 16, bits=64) # Align values aligned = align(0x1234, 0x1000) # 0x2000 (round up) aligned_down = align_down(0x1234, 0x1000) # 0x1000 (round down) # Implementing ROL7 hash def rol7_hash(name: bytes) -> int: from malduck import DWORD hh = DWORD(0) for c in name: hh = hh.rol(7) ^ c return int(hh) ``` -------------------------------- ### Calculate Hashing Functions Source: https://context7.com/cert-polska/malduck/llms.txt Common hashing algorithms for identifying samples and validating data. ```python from malduck import md5, sha1, sha256, sha512, crc32 data = b'malware sample data' # Get hash digests (returns raw bytes) md5_hash = md5(data) sha1_hash = sha1(data) sha256_hash = sha256(data) sha512_hash = sha512(data) # CRC32 checksum checksum = crc32(data) ``` -------------------------------- ### Disassembly with Capstone Source: https://context7.com/cert-polska/malduck/llms.txt Disassemble raw bytes using the Capstone engine for x86/x64 analysis. ```python from malduck import procmem, disasm, insn # Disassemble raw bytes code = b'\x55\x48\x89\xe5\x48\x83\xec\x10' for instruction in disasm(code, addr=0x401000, x64=True): print(f"{hex(instruction.addr)}: {instruction.mnem} {instruction}") ``` -------------------------------- ### Convert to hex string Source: https://context7.com/cert-polska/malduck/llms.txt Utility for converting binary hash outputs into hexadecimal strings. ```python from malduck import enhex md5_hex = enhex(md5(data)) sha256_hex = enhex(sha256(data)) ``` -------------------------------- ### PKCS7 Padding (pkcs7) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use pkcs7() to apply PKCS#7 padding to a byte string. The padding value is the number of padding bytes added. ```python pkcs7(b'YELLOW SUBMARINE', 16) # Output: b'YELLOW SUBMARINE\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10' ``` -------------------------------- ### Define Custom Malware Extractor Source: https://context7.com/cert-polska/malduck/llms.txt Create a custom extractor by inheriting from `Extractor` and defining methods decorated with `@Extractor.string`, `@Extractor.extractor`, `@Extractor.rule`, `@Extractor.final`, `@Extractor.weak`, or `@Extractor.needs_pe`. These methods handle specific extraction logic based on Yara matches or PE structure. ```python from malduck import Extractor, procmem class MyMalwareExtractor(Extractor): family = "mymalware" yara_rules = ("mymalware_rule",) overrides = ("generic_trojan",) # Override less specific matches # String-based extractor - called for each $config_marker hit @Extractor.string("config_marker") def extract_config(self, p, addr, match): # p: ProcessMemory object # addr: Virtual address of match # match: YaraStringMatch with identifier, offset, content # Read config data after marker config_data = p.readv(addr + len(match.content), 256) # Return extracted config (dict adds to final config) return { "c2_server": p.asciiz(addr + 0x10).decode(), "encryption_key": p.readv(addr + 0x50, 16), } # Simplified extractor - only receives offset @Extractor.extractor("key_pattern") def extract_key(self, p, addr): key = p.readv(addr, 32) return {"rc4_key": key} # Multiple string patterns trigger same method @Extractor.string("c2_url1", "c2_url2", "c2_url3") def extract_c2(self, p, addr, match): url = p.asciiz(addr).decode() return {"c2_urls": [url]} # Rule-based extractor - called once per rule match @Extractor.rule("mymalware_rule") def on_rule_match(self, p, matches): # matches: YaraRuleMatch with all matched strings if "version_string" in matches: for string_match in matches["version_string"]: return {"version": string_match.content.decode()} # Final extractor - called after all other extractors @Extractor.final def finalize_config(self, p): # Access previously collected config if "c2_server" in self.collected_config: return {"status": "complete"} # Weak extractors don't confirm family match @Extractor.weak @Extractor.extractor("possible_key") def weak_key_extraction(self, p, addr): return {"possible_key": p.readv(addr, 16)} # Require PE format @Extractor.needs_pe @Extractor.final def extract_from_resources(self, p): config = p.pe.resource("CONFIG") if config: return {"resource_config": config} ``` -------------------------------- ### Perform AES Encryption and Decryption Source: https://context7.com/cert-polska/malduck/llms.txt Supports CBC, ECB, and CTR modes with various key sizes. Includes utility for importing keys from Windows BLOB structures. ```python from malduck import aes # AES-CBC mode encryption and decryption key = b'A' * 16 # 128-bit key iv = b'B' * 16 # Initialization vector plaintext = b'secret data here' * 4 # Must be multiple of 16 bytes ciphertext = aes.cbc.encrypt(key, iv, plaintext) decrypted = aes.cbc.decrypt(key, iv, ciphertext) # decrypted == plaintext # AES-ECB mode (no IV needed) ecb_ciphertext = aes.ecb.encrypt(key, plaintext) ecb_decrypted = aes.ecb.decrypt(key, ecb_ciphertext) # AES-CTR mode with nonce nonce = b'\x00' * 16 ctr_ciphertext = aes.ctr.encrypt(key, nonce, plaintext) ctr_decrypted = aes.ctr.decrypt(key, nonce, ctr_ciphertext) # Import key from Windows BLOB structure blob_data = b'\x08\x02\x00\x00\x10\x66\x00\x00' + b'\x10\x00\x00\x00' + b'A' * 16 result = aes.import_key(blob_data) # result = ('AES-128', b'AAAAAAAAAAAAAAAA') ``` -------------------------------- ### Use Fixed Integer Types Source: https://context7.com/cert-polska/malduck/llms.txt Utilize fixed-size integers with C-style overflow behavior and bitwise rotation for algorithms. ```python from malduck import DWORD, WORD, BYTE, QWORD, UInt32, Int32 # C-style integer overflow result = DWORD(0xFFFFFFFF) + 1 # result == 0 (wraps around) # Implementing SDBM hash with automatic overflow handling def sdbm_hash(name: bytes) -> int: hh = 0 for c in name: hh = DWORD(c) + (hh << 6) + (hh << 16) - hh return int(hh) hash_value = sdbm_hash(b"kernel32.dll") # Bitwise rotate operations value = DWORD(0x12345678) rotated_left = value.rol(8) # Rotate left by 8 bits rotated_right = value.ror(4) # Rotate right by 4 bits # Pack/unpack values packed = DWORD(0xDEADBEEF).pack() # Little-endian bytes packed_be = DWORD(0xDEADBEEF).pack_be() # Big-endian bytes unpacked = DWORD.unpack(b'\xef\xbe\xad\xde') # From little-endian unpacked_be = DWORD.unpack_be(b'\xde\xad\xbe\xef') # From big-endian # Unpack multiple values (ctypes-like multiplication) values = (BYTE * 4).unpack(b'\x01\x02\x03\x04') # values == (1, 2, 3, 4) # Signed integers signed = Int32(0xFFFFFFFF) # signed == -1 ``` -------------------------------- ### Use Extractor Engine with ProcessMemory Source: https://context7.com/cert-polska/malduck/llms.txt Load extractor modules from a directory and use `ExtractManager` to run extraction on a `ProcessMemory` object. The `extract` method returns the collected configuration. ```python # Use extractor with ProcessMemory from malduck.extractor import ExtractManager, ExtractorModules # Load modules from directory modules = ExtractorModules("/path/to/extractors") manager = ExtractManager(modules) with procmem.from_file("sample.bin") as p: # Run extraction config = p.extract(modules=modules) if config: print(f"Extracted config: {config}") ``` -------------------------------- ### SDBM Hash Calculation with DWORD Source: https://github.com/cert-polska/malduck/blob/master/README.md Implements the SDBM hash algorithm using Malduck's DWORD fixed integer type for bitwise operations. Operations on DWORD objects ensure correct handling of integer sizes. ```python from malduck import DWORD def sdbm_hash(name: bytes) -> int: hh = 0 for c in name: # operations on the DWORD type produce a dword, so a result # is also a DWORD. hh = DWORD(c) + (hh << 6) + (hh << 16) - hh return int(hh) ``` -------------------------------- ### Perform XOR Encryption and Decryption Source: https://context7.com/cert-polska/malduck/llms.txt Supports single-byte and multi-byte keys with automatic key cycling for decoding obfuscated strings. ```python from malduck import xor # Single-byte XOR key encrypted = b'\x37\x2a\x39\x39\x3a' # "hello" XOR'd with 0x5F decrypted = xor(0x5F, encrypted) # decrypted == b'hello' # Multi-byte XOR key (cycles automatically) key = b'KEY' data = b'Secret Message!!' encrypted = xor(key, data) decrypted = xor(key, encrypted) # decrypted == b'Secret Message!!' # Decode malware config strings config_blob = b'\x1e\x0b\x1c\x1c\x1f\x49\x4c\x4c' decoded = xor(b'secret', config_blob) ``` -------------------------------- ### Creating Chunks (chunks) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use chunks() to create a list of chunks of a specified size from a byte string. This is a non-iterator alternative to chunks_iter(). ```python chunks(b'abcdefghijkl', 3) # Output: [b'abc', b'def', b'ghi', b'jkl'] ``` -------------------------------- ### ProcessMemory Interface Source: https://context7.com/cert-polska/malduck/llms.txt Unified interface for reading, searching, and patching memory dumps or binary data. ```python from malduck import procmem # Load from file with base address with procmem.from_file("memory_dump.bin", base=0x400000) as p: # Read bytes at virtual address data = p.readv(0x401000, 256) # Read null-terminated strings ascii_string = p.asciiz(0x401000) utf16_string = p.utf16z(0x402000) # Read integers at virtual address dword = p.uint32v(0x401000) qword = p.uint64v(0x401000) signed_int = p.int32v(0x401000) # Check if address is valid if p.is_addr(0x401000): print("Address is mapped") # Search for bytes for addr in p.findv(b'MZ'): print(f"Found MZ at {hex(addr)}") # Search with regex for addr in p.regexv(b'http[s]?://[^\x00]+'): print(f"URL at {hex(addr)}") # Search with wildcards (Yara hex strings) for addr in p.findbytesv("4D 5A ?? ?? 50 45"): print(f"PE header pattern at {hex(addr)}") # Load from bytes payload = b'\x4d\x5a...' p = procmem(payload, base=0x10000000) # Patch memory p.patchv(0x10001000, b'\x90\x90\x90\x90') # NOP slide # Virtual to physical offset translation offset = p.v2p(0x401000) vaddr = p.p2v(0x1000) ``` -------------------------------- ### Perform Miscellaneous Cryptographic Operations Source: https://context7.com/cert-polska/malduck/llms.txt Implementations for Blowfish, Serpent, ChaCha20, Salsa20, DES3, Rabbit, and Camellia algorithms. ```python from malduck import blowfish, serpent, chacha20, salsa20, des3, rabbit, camellia # Blowfish ECB key = b'blowfish' plaintext = b'data' * 16 ciphertext = blowfish.ecb.encrypt(key, plaintext) decrypted = blowfish.ecb.decrypt(key, ciphertext) # Serpent CBC key = b'a' * 16 iv = b'b' * 16 plaintext = b'data' * 16 ciphertext = serpent.cbc.encrypt(key, plaintext, iv=iv) decrypted = serpent.cbc.decrypt(key, ciphertext, iv=iv) # ChaCha20 stream cipher key = b'chachaKeyHereNow' * 2 # 32 bytes nonce = b'\x01\x02\x03\x04\x05\x06\x07\x08' plaintext = b'data' * 16 ciphertext = chacha20.encrypt(key, plaintext, nonce) decrypted = chacha20.decrypt(key, ciphertext, nonce) # Salsa20 stream cipher key = b'salsaFTW' * 4 # 32 bytes ciphertext = salsa20.encrypt(key, plaintext, nonce) decrypted = salsa20.decrypt(key, ciphertext, nonce) # Triple DES (falls back to DES for 8-byte keys) key = b'des3des3des3des3des3des3' # 24 bytes for 3DES iv = b'12345678' ciphertext = des3.cbc.encrypt(key, plaintext, iv) # Rabbit stream cipher key = b'a' * 16 iv = b'b' * 8 ciphertext = rabbit(key, iv, plaintext) # Camellia (ECB, CBC, CTR, CFB, OFB modes) ciphertext = camellia.cbc.encrypt(key, iv, plaintext) ``` -------------------------------- ### UTF-16 Null-terminated String (utf16z) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use utf16z() to convert a Python string to a null-terminated UTF-16 byte string. Handles surrogate pairs correctly. ```python utf16z('hello') # Output: b'h\x00e\x00l\x00l\x00o\x00\x00\x00' ``` -------------------------------- ### Camellia CBC Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Camellia in CBC mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import camellia key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = camellia.cbc.encrypt(key, iv, plaintext) ``` -------------------------------- ### IPv4 Address to String (inet_ntoa) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use inet_ntoa() to convert a 4-byte packed IPv4 address into its standard dot-decimal string representation. ```python inet_ntoa(b'\x7f\x00\x00\x01') # Output: '127.0.0.1' ``` -------------------------------- ### XOR "Stream Cipher" Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Performs XOR operation on data using a key. This is a simple XOR operation, not a secure stream cipher. ```python from malduck import xor key = b'a'*16 xored = b'data'*16 unxored = xor(key, xored) ``` -------------------------------- ### AES CBC Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using AES in CBC mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import aes key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = aes.cbc.encrypt(key, iv, plaintext) ``` -------------------------------- ### Decompress gzip and LZNT1 Data Source: https://context7.com/cert-polska/malduck/llms.txt Handle gzip/zlib and Windows RtlDecompressBuffer (LZNT1) compressed payloads. ```python from malduck import gzip, lznt1, unhex # gzip decompression (auto-detects gzip vs zlib by magic bytes) zlib_data = unhex(b'789ccb48cdc9c95728cf2fca4901001a0b045d') decompressed = gzip(zlib_data) # decompressed == b'hello world' # gzip with 1f8b08 header gzip_data = unhex(b'1f8b08082199b75a0403312d3100cb48cdc9c95728cf2fca49010085114a0d0b000000') decompressed = gzip(gzip_data) # LZNT1 decompression (Windows RtlDecompressBuffer compatible) lznt1_data = b"\x1a\xb0\x00compress\x00edtestda\x04ta\x07\x88alot" decompressed = lznt1(lznt1_data) # decompressed == b'compressedtestdatadataalotalot' ``` -------------------------------- ### Iterating Over Chunks (chunks_iter) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use chunks_iter() to create an iterator that yields chunks of a specified size from a byte string. Useful for processing data in segments. ```python chunks_iter(b'abcdefghijkl', 3) # Output: ``` -------------------------------- ### Camellia OFB Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Camellia in OFB mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import camellia key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = camellia.ofb.encrypt(key, iv, plaintext) ``` -------------------------------- ### Serpent CBC Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Serpent in CBC mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import serpent key = b'a'*16 iv = b'b'*16 plaintext = b'data'*16 ciphertext = serpent.cbc.encrypt(key, plaintext, iv=iv) ``` -------------------------------- ### Camellia CTR Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Camellia in CTR mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import camellia key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = camellia.ctr.encrypt(key, iv, plaintext) ``` -------------------------------- ### Hexadecimal Decoding (unhex) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use unhex() to convert a hexadecimal string (or byte string) back to its original byte string. Input must contain an even number of hex digits. ```python unhex(b'123456') # Output: b'\x124V' ``` -------------------------------- ### Hexadecimal Encoding (enhex) Source: https://github.com/cert-polska/malduck/blob/master/docs/string.md Use enhex() to convert a byte string to its hexadecimal representation. Each byte is represented by two hexadecimal characters. ```python enhex(b'\x12\x34\x56') # Output: b'123456' ``` -------------------------------- ### ProcessMemoryPE Parsing Source: https://context7.com/cert-polska/malduck/llms.txt Extension of ProcessMemory for parsing PE headers, sections, and resources. ```python from malduck import procmempe # Load PE file as memory-mapped image with procmempe.from_file("malware.exe", image=True) as p: # Access PE object pe = p.pe # Check architecture if pe.is64bit: print("64-bit PE") elif pe.is32bit: print("32-bit PE") # Access headers image_base = pe.optional_header.ImageBase entry_point = pe.optional_header.AddressOfEntryPoint # Iterate sections for section in pe.sections: name = section.Name.rstrip(b'\x00') va = section.VirtualAddress size = section.SizeOfRawData print(f"Section {name}: VA={hex(va)}, Size={hex(size)}") # Get section by name text_section = pe.section(".text") # Extract resources icon_data = pe.resource("RT_ICON") config = pe.resource("CONFIG") # Get all resources of a type for rsrc in pe.resources("RT_RCDATA"): print(f"Resource data: {len(rsrc)} bytes") # Image boundaries start = p.imgbase end = p.imgend # Store modified PE back to file pe_data = p.store() with open("dumped.exe", "wb") as f: f.write(pe_data) # Load memory dump containing PE with procmempe.from_file("dump.dmp", base=0x140000000, image=True) as p: # Auto-detect if PE needs to be loaded as image if p.is_image_loaded_as_memdump(): p = procmempe.from_memory(p, image=True) ``` -------------------------------- ### Camellia CFB Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Camellia in CFB mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import camellia key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = camellia.cfb.encrypt(key, iv, plaintext) ``` -------------------------------- ### Camellia ECB Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Camellia in ECB mode. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import camellia key = b'A'*16 iv = b'B'*16 plaintext = b'data'*16 ciphertext = camellia.ecb.encrypt(key, iv, plaintext) ``` -------------------------------- ### Rabbit Stream Cipher Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using the Rabbit stream cipher. Requires a 16-byte key and a 16-byte initialization vector. ```python from malduck import rabbit key = b'a'*16 iv = b'b'*16 plaintext = b'data'*16 ciphertext = rabbit(key, iv, plaintext) ``` -------------------------------- ### Salsa20 Decryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Decrypts data using the Salsa20 stream cipher. Assumes an empty nonce if none is provided. Requires a 32-byte key. ```python from malduck import salsa20 key = b'salsaFTW' * 4 nonce = b'\x01\x02\x03\x04\x05\0x6\0x7' plaintext = b'data' * 16 ciphertext = salsa20.decrypt(key, plaintext, nonce) ``` -------------------------------- ### Blowfish ECB Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Blowfish in ECB mode. Requires a key of at least 8 bytes. ```python from malduck import blowfish key = b'blowfish' plaintext = b'data'*16 ciphertext = blowfish.ecb.encrypt(key, plaintext) ``` -------------------------------- ### Decompress aPLib Data Source: https://context7.com/cert-polska/malduck/llms.txt Decompress aPLib-compressed payloads, supporting both headerless and AP32-headed buffers. ```python from malduck import aplib # Decompress headerless aPLib data compressed = b'T\x00he quick\xecb\x0erown\xcef\xaex\x80jumps\xed\xe4veur`t?lazy\xead\xfeg\xc0\x00' decompressed = aplib(compressed) # decompressed == b'The quick brown fox jumps over the lazy dog' # Decompress with AP32 header (auto-detected) headed_compressed = b'AP32\x18\x00\x00\x00\r\x00\x00\x00...' decompressed = aplib(headed_compressed) # Force headerless mode even if data starts with AP32 decompressed = aplib(data, headerless=True) ``` -------------------------------- ### DES3 CBC Mode Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using Triple DES in CBC mode. Falls back to single DES for 8-byte keys. Requires a key and an initialization vector. ```python from malduck import des3 key = b'des3des3' iv = b'3des3des' plaintext = b'data' * 16 ciphertext = des3.cbc.encrypt(key, plaintext) ``` -------------------------------- ### ChaCha20 Decryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Decrypts data using the ChaCha20 stream cipher. Assumes an empty nonce if none is provided. Requires a 32-byte key. ```python from malduck import chacha20 key = b'chachaKeyHereNow' * 2 nonce = b'\x01\x02\x03\x04\x05\0x6\0x7' plaintext = b'data'*16 ciphertext = chacha20.decrypt(key, plaintext, nonce) ``` -------------------------------- ### RC4 Stream Cipher Encryption Source: https://github.com/cert-polska/malduck/blob/master/docs/crypto.md Encrypts data using the RC4 stream cipher. Requires a key of at least 16 bytes. ```python from malduck import rc4 key = b'a'*16 plaintext = b'data'*16 ciphertext = rc4(key, plaintext) ``` -------------------------------- ### Perform RC4 Stream Cipher Operations Source: https://context7.com/cert-polska/malduck/llms.txt Symmetric stream cipher implementation where the same function handles both encryption and decryption. ```python from malduck import rc4 key = b'malware_key' encrypted_data = b'\x9d\x8e\xb7\xa5\x9c' # Example encrypted bytes # Decrypt RC4 encrypted data decrypted = rc4(key, encrypted_data) # Encrypt data with RC4 plaintext = b'Hello World' ciphertext = rc4(key, plaintext) # Verify round-trip assert rc4(key, ciphertext) == plaintext ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.