<?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 NIRVANA on Medium]]></title>
        <description><![CDATA[Stories by NIRVANA on Medium]]></description>
        <link>https://medium.com/@0xnirsec?source=rss-f2838142e6d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wMt-sRJbImusFd49WEd9sA.jpeg</url>
            <title>Stories by NIRVANA on Medium</title>
            <link>https://medium.com/@0xnirsec?source=rss-f2838142e6d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:08:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0xnirsec/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[Payload Placement in .data Section— NIR(11)]]></title>
            <link>https://0xnirsec.medium.com/payload-placement-in-data-section-nir-11-82e6e0d325e6?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/82e6e0d325e6</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[nirvana]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 06:36:10 GMT</pubDate>
            <atom:updated>2026-07-31T06:44:51.072Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, cybersecurity enthusiasts and white-hat hackers!</p><p>In our previous blog, we explored Section Headers in detail and understood the different types of sections present in a PE file. That knowledge will be essential for today’s discussion.</p><p>In this blog, we will begin by placing our payload in the .data section of a PE file. In upcoming blogs, we will explore how to place payloads in other sections such as .text, .rdata, .rsrc, and more.</p><p>So, let’s get started.</p><h3><strong>.data Section</strong></h3><p>The .data section stores all <strong>initialized global and static variables</strong> defined in a program. These variables have predefined values in the source code, and their contents are loaded into memory when the program starts executing.</p><p>To place a payload inside the .data section, we can define it as a <strong>global variable</strong>. Since global variables are stored in the .data section (when initialized), the payload will automatically be placed there during compilation.</p><pre>#include &lt;Windows.h&gt;<br>#include &lt;stdio.h&gt;<br><br>// msfvenom calc shellcode<br>// msfvenom -p windows/x64/exec CMD=calc.exe -f c <br><br>unsigned char Payload[] = {<br> 0xFC, 0x48, 0x83, 0xE4, 0xF0, 0xE8, 0xC0, 0x00, 0x00, 0x00, 0x41, 0x51,<br> 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xD2, 0x65, 0x48, 0x8B, 0x52,<br> 0x60, 0x48, 0x8B, 0x52, 0x18, 0x48, 0x8B, 0x52, 0x20, 0x48, 0x8B, 0x72,<br> 0x50, 0x48, 0x0F, 0xB7, 0x4A, 0x4A, 0x4D, 0x31, 0xC9, 0x48, 0x31, 0xC0,<br> 0xAC, 0x3C, 0x61, 0x7C, 0x02, 0x2C, 0x20, 0x41, 0xC1, 0xC9, 0x0D, 0x41,<br> 0x01, 0xC1, 0xE2, 0xED, 0x52, 0x41, 0x51, 0x48, 0x8B, 0x52, 0x20, 0x8B,<br> 0x42, 0x3C, 0x48, 0x01, 0xD0, 0x8B, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48,<br> 0x85, 0xC0, 0x74, 0x67, 0x48, 0x01, 0xD0, 0x50, 0x8B, 0x48, 0x18, 0x44,<br> 0x8B, 0x40, 0x20, 0x49, 0x01, 0xD0, 0xE3, 0x56, 0x48, 0xFF, 0xC9, 0x41,<br> 0x8B, 0x34, 0x88, 0x48, 0x01, 0xD6, 0x4D, 0x31, 0xC9, 0x48, 0x31, 0xC0,<br> 0xAC, 0x41, 0xC1, 0xC9, 0x0D, 0x41, 0x01, 0xC1, 0x38, 0xE0, 0x75, 0xF1,<br> 0x4C, 0x03, 0x4C, 0x24, 0x08, 0x45, 0x39, 0xD1, 0x75, 0xD8, 0x58, 0x44,<br> 0x8B, 0x40, 0x24, 0x49, 0x01, 0xD0, 0x66, 0x41, 0x8B, 0x0C, 0x48, 0x44,<br> 0x8B, 0x40, 0x1C, 0x49, 0x01, 0xD0, 0x41, 0x8B, 0x04, 0x88, 0x48, 0x01,<br> 0xD0, 0x41, 0x58, 0x41, 0x58, 0x5E, 0x59, 0x5A, 0x41, 0x58, 0x41, 0x59,<br> 0x41, 0x5A, 0x48, 0x83, 0xEC, 0x20, 0x41, 0x52, 0xFF, 0xE0, 0x58, 0x41,<br> 0x59, 0x5A, 0x48, 0x8B, 0x12, 0xE9, 0x57, 0xFF, 0xFF, 0xFF, 0x5D, 0x48,<br> 0xBA, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8D, 0x8D,<br> 0x01, 0x01, 0x00, 0x00, 0x41, 0xBA, 0x31, 0x8B, 0x6F, 0x87, 0xFF, 0xD5,<br> 0xBB, 0xE0, 0x1D, 0x2A, 0x0A, 0x41, 0xBA, 0xA6, 0x95, 0xBD, 0x9D, 0xFF,<br> 0xD5, 0x48, 0x83, 0xC4, 0x28, 0x3C, 0x06, 0x7C, 0x0A, 0x80, 0xFB, 0xE0,<br> 0x75, 0x05, 0xBB, 0x47, 0x13, 0x72, 0x6F, 0x6A, 0x00, 0x59, 0x41, 0x89,<br> 0xDA, 0xFF, 0xD5, 0x63, 0x61, 0x6C, 0x63, 0x00<br>};<br><br>int main() {<br>    printf(&quot;[i] Payload (Loc) : 0x%p \n&quot;, Payload);<br>    printf(&quot;[#] Press &lt;Enter&gt; to exit . . &quot;);<br>    getchar();<br>    return 0;<br>}</pre><p>As shown in the code above, the Payload array is defined <strong>outside the </strong><strong>main function</strong>, making it a global variable. Because it is initialized, it will be stored in the .data section of the compiled executable. Therefore, when we inspect the .data section of the binary, we will find our payload located there.</p><h3>Verifying Payload in .data Section</h3><p>Now that we have placed our payload inside the .data section, the next step is to <strong>verify whether it is actually stored there or not</strong>. We can do this using different analysis tools.</p><h4>Method 1: Using PE-bear (Static Analysis)</h4><p>In this method, we use <strong>PE-bear</strong> to statically analyze the compiled executable.</p><p><strong>Steps:</strong></p><ol><li>Open <strong>PE-bear</strong>.</li><li>Load your compiled .exe file.</li><li>Navigate to the <strong>Sections</strong> tab.</li><li>Click on the .data section.</li><li>Observe the raw bytes in the hex view.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBFfCk5F2NqhKjw9-oDuuw.png" /></figure><p>As shown in the image above, the exact <strong>calc shellcode (payload)</strong> is visible inside the .data section. This confirms that our global Payload array has been successfully placed there by the compiler.</p><p>This is a <strong>static verification method</strong>, meaning we are analyzing the file <strong>without executing it</strong>.</p><h4>Method 2: Using x64dbg (Dynamic Analysis)</h4><p>To verify using <strong>x64dbg</strong>, first open x64dbg and load your .exe file.<br>After loading, go to <strong>Memory Map</strong>, where you will see something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZXBxUbVRfASystNqwxBRg.png" /></figure><p>Now go to the .data section where <strong>Party = User</strong>. When you click on it, it will open in the <strong>Dump window</strong>, and here you can notice that our payload is present.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYseBr_bpkjQ2HIBqVm-8A.png" /></figure><p><strong>Finding Exact Location (Optional but Important)</strong></p><p>To find the exact runtime location of the payload, we set a breakpoint using a known string like: “<strong><em>Press &lt;Enter&gt; to exit” . </em></strong>This step is not required for .data verification, but it helps to understand memory locations.</p><p>First, reload the .exe in x64dbg (press <strong>Restart</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*ACecJMQfuyZ2J3bjuVDAXw.png" /></figure><p>To search for strings, <strong>right-click inside the red-marked area shown in the image</strong>, and a menu will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKa_vxRF-55guEZcOvQTZQ.png" /></figure><p>In that menu, go to: <strong>Search → All Modules → String references</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*t1nEOYS7QLairkNoDWbykA.png" /></figure><p>Then search for the string: <strong>Press &lt;Enter&gt; to exit</strong>, which we added in our program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XfExcrA-fAUv7mneb9DKA.png" /></figure><p>Then you will get the address of that string, and we can set a breakpoint there by clicking on that address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcX0SYTw9s1SzG_gq9uC7Q.png" /></figure><p>You can set a breakpoint by clicking the <strong>red dot</strong>, or you can also press <strong>F2</strong>.<br>After setting the breakpoint, restart the execution again (like we did earlier), then press <strong>F9</strong> to run forward in the code. You can also use <strong>F10</strong>, but it executes one instruction at a time, so <strong>F9 is better for fast forwarding</strong>.</p><p>Once it hits the breakpoint, open the .exe running in the other window and check the <strong>address of the payload</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp5zvf6U-a_JHwVmBN0s8w.png" /></figure><p>My address is 0x00007FF6AC803080 (your address may be different). Once we get the address, go to <strong>Dump 1</strong>.</p><p>Move your cursor to the red-marked area, <strong>right-click there</strong>, then select <strong>Expression</strong>, and follow the steps shown in the image below. Or you can directly press <strong>Ctrl + G</strong>, but since this is your first time, I’m explaining it in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*WDHnyKvTrY1IuhJm_IAFeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*FzxRPY6LsbG3KB_6EQ40yQ.png" /></figure><p>Now an input box will appear — enter your <strong>payload address</strong> there and press <strong>Enter</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*qSzT1C31VHLCeLe7MVCDqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*lEKVeXjuGg9arwbwoNJy6A.png" /></figure><p>Then you will see the <strong>exact location of the payload in memory</strong>. Using this method, you can use <strong>x64dbg</strong> to find the location, set breakpoints, and search for strings. This is not directly related to the <strong>.data section</strong>, but it is useful knowledge that will help in future blogs.</p><h4><strong>Method 3: Dumpbin</strong></h4><p>If you have <strong>Visual Studio</strong> installed, you can use this tool. For that, open the <strong>x64 Native Tools Command Prompt</strong> provided by Visual Studio, then navigate to the location where your .exe file is present.</p><p>Use the command: dumpbin /ALL &lt;exe location&gt;<br>It will print a lot of data, but we need to <strong>find the </strong><strong>.data section</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Q90UIfo8k0S9aIBeuc8q7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*6jM5KKKxcGmh079MUwN17Q.png" /></figure><p>The image above shows that our <strong>payload is present inside the </strong><strong>.data section</strong>. Using multiple methods, we confirmed that our payload is located in the .data section. The methods, tools, and commands used in this blog are important to remember, because in future blogs I will directly show images. Using this knowledge, you should be able to <strong>analyze it manually and explore by yourself</strong>.</p><p>I hope you found this blog helpful in understanding both <strong>how to place a payload inside the </strong><strong>.data section</strong> and <strong>how to verify it using different tools and methods</strong>.</p><p>The main goal of this blog was to demonstrate:</p><ul><li>How global initialized variables store data in the <strong>.data section</strong></li><li>How we can <strong>place our payload there during compilation</strong></li><li>And how to <strong>verify it using static and dynamic analysis tools</strong></li></ul><p>If you are new to this, don’t worry if some parts feel confusing at first. With more practice and hands-on analysis, these concepts will become much clearer.In upcoming blogs, we will explore placing payloads in other sections like <strong>.text, </strong><strong>.rdata, </strong><strong>.rsrc</strong>, and also move towards more advanced topics like <strong>process injection, obfuscation, and evasion techniques</strong>.</p><p><strong>Note:</strong> This content is created for learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82e6e0d325e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Section Headers and Sections (PE) — NIR(10)]]></title>
            <link>https://0xnirsec.medium.com/introduction-to-section-headers-and-sections-pe-nir-10-0c863acc0233?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c863acc0233</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[windows-internals]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 06:26:01 GMT</pubDate>
            <atom:updated>2026-07-28T06:26:01.563Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous blog, we explored the Optional Header and Data Directory in detail. Now, it’s time to move forward and dive into Section Headers and the different types of sections in a PE file.</p><h3>What is Section Headers ?</h3><p>A <strong>Section Header</strong> is a structure defined in <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header"><em>winnt.h</em></a><em> </em>as <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header">_IMAGE_SECTION_HEADER</a>. It does not store the actual content of a section; instead, It acts like a pointer to the section and gives important information about it. This includes information such as the section’s name, its size on disk and in memory, its location within the file, and the permissions (read, write, execute) assigned to it. Using this information, the Windows loader can correctly locate each section in the PE file and map it into memory with the appropriate attributes during program execution.</p><p>If we look at its definition, we get the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*zpNvKqT_lcJSSPN40qbzWw.png" /><figcaption>IMAGE_SECTION_HEADER</figcaption></figure><p><strong>Name : </strong>First field of the Section Header. It is a byte array of size IMAGE_SIZEOF_SHORT_NAME (8 bytes) that stores the name of the section (like .text, .data). This means a section name cannot be longer than 8 characters. If a section name is longer than 8 characters, object files store it in a string table and put a pointer in the Name field. But executable files don’t use a string table, so section names must stay within 8 characters.</p><p><strong>PhysicalAddress / VirtualSize: </strong>This field is defined as a <strong>union</strong>, which means both PhysicalAddress and VirtualSize share the same memory location, but only one is actually used depending on the file type. For executable images (.exe, .dll), <strong>VirtualSize</strong> is used. It represents the <strong>actual size of the section in memory</strong> after it is loaded by the Windows loader. PhysicalAddress is mainly used in object files (.obj) and is generally not relevant for executable images.</p><p><strong>VirtualAddress: </strong>This field stores the <strong>Relative Virtual Address (RVA)</strong> of the first byte of the section when the program is loaded into memory. It tells <strong>where this section will be placed in memory</strong>, but not as an absolute address. Instead, it is <strong>relative to the Image Base</strong> (the starting address where the PE file is loaded).</p><p><strong>SizeOfRawData: </strong>This is the size of the section’s data on disk (inside the PE file). As we covered in our previous blog on <a href="https://0xnirsec.medium.com/introduction-to-nt-headers-pe-nir-8-adbae96b7413">NT — Headers</a> , FileAlignment defines how section data is aligned inside the PE file on disk. SizeOfRawData must follow this rule — it must be a multiple of FileAlignment. For example, if FileAlignment = 0x200 (512 bytes) and the section&#39;s actual data is only 300 bytes, SizeOfRawData will be rounded up to 512, and the remaining bytes are padded with zeros to meet the alignment requirement.</p><p>VirtualSize, on the other hand, is not aligned because it represents the <strong>actual size</strong> of the section&#39;s data in memory — exactly how many bytes are really used. As we explained, alignment only controls <strong>where</strong> sections are placed (in memory via SectionAlignment, on disk via FileAlignment), not <strong>how much</strong> real data they contain. So VirtualSize stays as-is and is never rounded up.</p><blockquote>Now the important question — <strong>why does in-memory padding exist at all?</strong></blockquote><blockquote>As we covered in our <a href="https://medium.com/@0xnirsec/windows-memory-management-nir-5-5460da66aa72?sharedUserId=0xnirsec">Windows Memory Management</a> blog, Windows divides physical memory into fixed-size <strong>pages of 4 KB</strong> (0x1000 bytes). The OS can only assign permissions (Read / Write / Execute) on a <strong>per-page basis</strong> — it cannot protect half a page differently from the other half. This is exactly why SectionAlignment = 0x1000:</blockquote><p>A concrete example:</p><pre>Actual data       = 0x350   ← VirtualSize, truth size<br>FileAlignment     = 0x200  (from Optional Header)<br>SectionAlignment  = 0x1000 (from Optional Header)<br><br>On disk:<br>SizeOfRawData = 0x400   ← rounded to FileAlignment (0x200)<br>padding       = 0xB0 zeros<br><br>In memory:<br>region size   = 0x1000  ← rounded to SectionAlignment (0x1000) = 1 page<br>padding       = 0xCB0 zeros added by loader</pre><p><strong>PointerToRawData: </strong>This field stores the file offset to where the section’s raw data begins inside the PE file. In other words, it tells the loader exactly where to find this section’s bytes on disk. Like SizeOfRawData, this value must also be aligned to FileAlignment. If a section has no data on disk (like a .bss section), this field is set to 0.</p><p><strong>PointerToRelocations: </strong>Points to the relocation entries for this section. In executable files (.exe, .dll), this is almost always 0 because relocations are handled by the .reloc section instead. It is more relevant in object files (.obj) where the linker hasn&#39;t resolved addresses yet.</p><p><strong>PointerToLinenumbers: </strong>Points to line-number information that was used in older COFF-style debugging to map source code lines to machine code. This is fully deprecated in modern toolchains and is always set to 0.</p><p><strong>NumberOfRelocations: </strong>The count of relocation entries pointed to by PointerToRelocations. Set to 0 in executable images for the same reason above.</p><p><strong>NumberOfLinenumbers: </strong>The count of line-number entries pointed to by PointerToLinenumbers. Also deprecated and always 0 in modern binaries.</p><p><strong>Characteristics:</strong> A bitmask of flags that describe the section’s properties and memory permissions. Each bit represents a specific attribute. The most important ones are:</p><pre>| Flag                               | Value       | Meaning                                 |<br>|------------------------------------|-------------|-----------------------------------------|<br>| IMAGE_SCN_CNT_CODE                 | 0x00000020  | Section contains executable code        |<br>| IMAGE_SCN_CNT_INITIALIZED_DATA     | 0x00000040  | Section contains initialized data       |<br>| IMAGE_SCN_CNT_UNINITIALIZED_DATA   | 0x00000080  | Section contains uninitialized data     |<br>| IMAGE_SCN_MEM_EXECUTE              | 0x20000000  | Section can be executed                 |<br>| IMAGE_SCN_MEM_READ                 | 0x40000000  | Section can be read                     |<br>| IMAGE_SCN_MEM_WRITE                | 0x80000000  | Section can be written to               |</pre><p>A complete list of section characteristics flags can be found on the <a href="https://docs.microsoft.com/en-us/windows/win32/debug/pe-format">official Microsoft documentation</a>.</p><p><strong>Note:</strong> You don’t need to memorize all section fields right now. This is just for understanding. Focus mainly on the important ones: Characteristics, VirtualSize, SizeOfRawData, PointerToRawData, Name, and VirtualAddress.</p><p>The image below shows real section headers from an actual PE file, viewed in a debugger. Let’s connect what we just learned to what we can see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wnsYAdWeEBOGoC29wvkhA.png" /></figure><p>A few things to notice directly from this real example:</p><ul><li><strong>.textbss</strong> has Raw Addr = 0 and Raw Size = 0 — it has <strong>no data on disk</strong> at all. It only exists in memory (VirtualSize = 0x10000). This is the uninitialized BSS section, zero-filled by the loader at runtime.</li><li><strong>.text</strong> has VirtualSize = 0x756A and Raw Size = 0x7600 — these are close but not equal. 0x7600 is the disk size rounded to FileAlignment, while 0x756A is the actual real data size. This is exactly the padding we discussed.</li><li><strong>.text</strong> has Characteristics = 60000020 which means <strong>Execute + Read</strong> only — no write permission, as expected for a normal code section.</li><li><strong>.rdata</strong> has only <strong>Read</strong> permission (r--) — it holds read-only data like strings and constants, so no execute or write is needed.</li><li>All Virtual Addresses are aligned to 0x1000 (1000, 11000, 19000...) — confirming SectionAlignment = 0x1000, exactly one page boundary per section, as we covered in our <a href="https://medium.com/@0xnirsec/windows-memory-management-nir-5-5460da66aa72?sharedUserId=0xnirsec">Windows Memory Management</a> blog.</li></ul><h3>Sections in PE Files</h3><p>A <strong>section</strong> is the actual container that holds the real content of a PE file — the code, data, resources, and other information needed for the program to run. A PE file is divided into multiple sections, each serving a specific purpose. The Windows loader reads the section headers and maps each section into memory with the correct permissions.</p><h4><strong>.text</strong></h4><p>This is the most important section in any PE file. It contains the <strong>compiled machine code</strong> — the actual CPU instructions that make up the program.</p><pre>Permissions  →  Execute + Read  (r-x)<br>Contains     →  compiled functions, entry point, all executable code</pre><ul><li>The program’s <strong>entry point</strong> (AddressOfEntryPoint from the Optional Header) always points inside this section</li><li>It is <strong>never writable</strong> in a normal binary — code should not modify itself at runtime</li><li>If you see .text with <strong>Write permission</strong>, that is immediately suspicious — it could mean self-modifying code or an injected payload</li></ul><h4>.data</h4><p>This section holds <strong>global and static variables</strong> that have been given a value at compile time.</p><pre>int counter = 100;<br>char name[] = &quot;NIRVANA&quot;;</pre><pre>Permissions  →  Read + Write  (rw-)<br>Contains     →  initialized global variables, static variables with values</pre><ul><li>It is <strong>writable</strong> because these variables need to change at runtime</li><li>It is <strong>not executable</strong> — data should never be executed</li><li>Strings that your program modifies at runtime also live here</li></ul><h4>.idata — Import Data Section</h4><p>This section holds the <strong>Import Directory Table</strong> — the list of all DLLs and functions the PE file needs from the OS or other libraries.</p><pre>Permissions  →  Read + Write  (rw-)<br>Contains  →  Import Address Table (IAT), DLL names</pre><ul><li>When the loader maps the PE into memory, it <strong>fills in the IAT</strong> with the real addresses of imported functions</li><li>This is why it needs <strong>Write</strong> permission — the loader writes addresses into it at load time</li><li>Malware analysts always check .idata first — the imported functions tell you exactly what the malware can do (network, file system, process injection, etc.)</li><li>It is sometimes merged into .rdata in modern compilers</li></ul><h4>.rdata</h4><p>This section holds <strong>data that never changes</strong> at runtime — constants, string literals, and important PE structures.</p><pre>const char* msg = &quot;Hello World&quot;;<br>const int MAX = 999;</pre><pre>Permissions  →  Read only  (r--)<br>Contains     →  string literals, constants, debug info,<br>                Import Directory Table, Import Name Table (INT)</pre><ul><li>The <strong>Import Directory</strong> and <strong>Export Directory</strong> (from the Data Directory) live here</li><li>It is <strong>not writable and not executable</strong> — purely read-only</li></ul><blockquote>The .idata section is used by the loader to resolve imports at runtime and requires write access, while .rdata stores constant read-only data and is not modified during execution.</blockquote><h4>.bss</h4><p>This section holds <strong>global and static variables that have no initial value</strong> assigned at compile time.</p><pre>int counter;<br>char buffer[1024];</pre><pre>Permissions  →  Read + Write  (rw-)<br>Contains     →  uninitialized global/static variables</pre><ul><li>Often has <strong>no raw data on disk</strong> (SizeOfRawData = 0, PointerToRawData = 0)</li><li>The loader simply <strong>zero-fills</strong> this region in memory at load time</li><li>This is why in our real example .textbss had Raw Addr = 0 and Raw Size = 0</li></ul><h4>.rsrc</h4><p>This section holds all the <strong>resources</strong> embedded inside the PE file — things a user can see or interact with.</p><pre>Permissions  →  Read only  (r--)<br>Contains     →  icons, images, dialogs, menus, version info, manifest, strings</pre><ul><li>Resources are stored in a <strong>tree structure</strong> with three levels: Type → Name → Language</li><li>The application’s <strong>icon</strong> you see in Windows Explorer comes from here</li><li>Malware often hides <strong>encrypted payloads</strong> inside fake resources in this section</li><li>Tools like <strong>Resource Hacker</strong> are used to view and extract .rsrc content</li></ul><h4>.pdata</h4><p>This section is used on <strong>64-bit</strong> systems for <strong>Structured Exception Handling (SEH)</strong>. It holds a table of function entries that describe how to handle exceptions in each function.</p><pre>Permissions  →  Read only  (r--)<br>Contains     →  RUNTIME_FUNCTION entries for exception unwinding</pre><ul><li>Each entry stores the start address, end address, and unwind info for a function</li><li>Only present on <strong>x64 and ARM</strong> — x86 uses a different exception model</li><li>The OS uses this during exception unwinding to know how to clean up the stack</li></ul><h4>.reloc — Base Relocation Section</h4><p>This section holds <strong>relocation entries</strong> — a list of addresses inside the PE that need to be adjusted if the image cannot load at its preferred ImageBase.</p><pre>Permissions  →  Read only  (r--)<br>Contains     →  base relocation blocks and fixup entries</pre><ul><li>If the PE loads at a different address than ImageBase, the loader uses .reloc to <strong>patch all hardcoded addresses</strong></li><li>With <strong>ASLR</strong> (Address Space Layout Randomization) enabled, this section is used every time the program runs</li><li>If this section is stripped from a DLL, the DLL <strong>must</strong> load at its preferred base address or it will crash</li><li>Malware sometimes strips .reloc to make manual mapping harder</li></ul><blockquote><strong>Note:</strong> Not every PE file contains all of these sections. The compiler and linker decide which sections to include based on what the program actually uses. Some sections may be merged together — for example, modern MSVC often merges .idata into .rdata. What matters is understanding what each section is responsible for, because when you analyze a real binary, you will encounter these sections constantly — whether in a legitimate program or a malicious one.</blockquote><h3>Rich Header</h3><p>The <strong>Rich Header</strong> is a hidden, undocumented structure that sits between the <strong>DOS Stub</strong> and the <strong>PE Signature</strong> (PE\0\0). It is not part of the official PE specification — Microsoft never publicly documented it. It was discovered by reverse engineers who noticed a pattern of bytes in PE files built with Microsoft&#39;s toolchain.</p><pre>┌─────────────────────────┐<br>│  DOS Header  (64 bytes) │<br>├─────────────────────────┤<br>│  DOS Stub               │<br>├─────────────────────────┤<br>│  Rich Header            │  ← sits here, hidden between stub and PE sig<br>├─────────────────────────┤<br>│  PE Signature &quot;PE\0\0&quot;  │<br>│  File Header            │<br>│  Optional Header        │<br>│  Section Headers        │<br>└─────────────────────────┘</pre><p>It only exists in binaries compiled with <strong>Microsoft Visual Studio</strong> or the <strong>MSVC toolchain</strong>. Binaries compiled with GCC, Clang, or MinGW do not have a Rich Header. The Rich Header stores a <strong>build metadata fingerprint</strong> — a list of all the Microsoft compiler tools and their versions that were used to build the PE file.</p><p><strong>For malware analysis and threat intelligence</strong>, the Rich Header is extremely valuable:</p><p><strong>1. Compiler Fingerprinting</strong><br>You can identify exactly which version of Visual Studio was used. This helps analysts group malware samples from the same threat actor — if two malware samples share the same exact Rich Header, they were likely built on the same machine with the same environment.</p><pre>Same Rich Header across samples  →  same build environment  →  same author</pre><p><strong>2. Threat Actor Attribution</strong><br>Nation-state malware groups have been attributed partly based on Rich Header analysis. If a new sample shares a Rich Header fingerprint with a known APT sample, it is a strong indicator of the same group.</p><p><strong>3. Evasion Detection</strong><br>Some malware deliberately <strong>zeroes out or corrupts the Rich Header</strong> to avoid fingerprinting. A missing or zeroed Rich Header in a binary that should have one is itself a red flag.</p><p><strong>Note:</strong> The Rich Header is not required for a PE file to run — the Windows loader completely ignores it. Its only purpose is to embed build metadata. This is exactly why malware authors either remove it to avoid attribution, or sometimes <strong>fake it</strong> to impersonate a legitimate compiler environment and mislead analysts. So when analyzing a suspicious binary, always check the Rich Header — its presence, absence, or inconsistency all tell a story.</p><p>The image below shows a real Rich Header parsed by a debugger. The most important thing to notice here is the <strong>VS Version column</strong> — every entry shows <strong>Visual Studio 2015 14.00</strong>. This tells us exactly which version of Visual Studio was used to compile this binary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0nz5Ci8dSv7IvbfvmLvXg.png" /><figcaption>Rich Header</figcaption></figure><p><strong>Conclusion:</strong><br>With this, our journey through <strong>PE Internals</strong> comes to an end. Using the image shown below, we covered most of the important components, including headers and different sections, and understood how they work together inside a PE file .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*vc0KOnZNLmNlfu0y_CBejw.png" /></figure><p>This blog was designed to build a <strong>strong and clear foundation</strong>. However, this is just the beginning. This knowledge becomes especially powerful when analyzing suspicious binaries, understanding obfuscation techniques, or developing low-level tools.</p><p><strong>Note:</strong> This content is intended for <strong>educational and defensive cybersecurity purposes only</strong>. Always use this knowledge ethically and responsibly.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c863acc0233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Data Directory (PE)-Nir(9)]]></title>
            <link>https://0xnirsec.medium.com/introduction-to-data-directory-pe-nir-9-0d2d26cfbcbe?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d2d26cfbcbe</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[portable-executable]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 16:06:21 GMT</pubDate>
            <atom:updated>2026-07-26T16:06:21.551Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Cybersecurity enthusiasts and white hat hackers!!</p><p>In our previous blog, we explored the NT Header in detail and understood its critical role in the structure of a Portable Executable (PE) file. However, one of the most important parts is still remaining — the Data Directory, which is a part of the Optional Header.</p><p>In today’s blog, we are going to dive deep into the Data Directory, which plays a crucial role in helping the Windows loader locate essential components such as imports, exports, resources, and more within a PE file.</p><h4>Where is Data Directory Located?</h4><p>Inside the IMAGE_OPTIONAL_HEADER64 structure:</p><pre>typedef struct _IMAGE_OPTIONAL_HEADER64 {<br> WORD Magic;<br> BYTE MajorLinkerVersion;<br> BYTE MinorLinkerVersion;<br> DWORD SizeOfCode;<br> DWORD SizeOfInitializedData;<br> DWORD SizeOfUninitializedData;<br> DWORD AddressOfEntryPoint;<br> DWORD BaseOfCode;<br> ULONGLONG ImageBase;<br> DWORD SectionAlignment;<br> DWORD FileAlignment;<br> WORD MajorOperatingSystemVersion;<br> WORD MinorOperatingSystemVersion;<br> WORD MajorImageVersion;<br> WORD MinorImageVersion;<br> WORD MajorSubsystemVersion;<br> WORD MinorSubsystemVersion;<br> DWORD Win32VersionValue;<br> DWORD SizeOfImage;<br> DWORD SizeOfHeaders;<br> DWORD CheckSum;<br> WORD Subsystem;<br> WORD DllCharacteristics;<br> ULONGLONG SizeOfStackReserve;<br> ULONGLONG SizeOfStackCommit;<br> ULONGLONG SizeOfHeapReserve;<br> ULONGLONG SizeOfHeapCommit;<br> DWORD LoaderFlags;<br> DWORD NumberOfRvaAndSizes;<br> IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; // Here <br>} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;</pre><pre>IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];</pre><p>This is the exact place where the Data Directory exists.</p><h3>What is Data Directory?</h3><p>The Data Directory is a fixed-size array of 16 entries inside the Optional Header. Each entry does not store actual data; instead, it stores a pointer to another structure (such as export, import, etc.) along with its size, which indicates how large the structure it is pointing to is.</p><p>Each entry is represented by the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_data_directory">IMAGE_DATA_DIRECTORY</a> structure, defined in winnt.h as:</p><pre>typedef struct _IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress; // RVA that points to the location of another structure (tells where the structure is located (as an RVA, not a full address))<br>    DWORD Size;           // Size of that structure in bytes (tells how big that structure is)<br>} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;</pre><p>This structure has only two fields:</p><ul><li>VirtualAddress — the RVA that points to the actual structure inside the PE file</li><li>Size — the size of that structure in bytes</li></ul><blockquote><strong>Note:</strong> Despite being named VirtualAddress, this field stores an <strong>RVA</strong>, not an absolute virtual address. The actual memory address is calculated as:</blockquote><blockquote>Actual Address = ImageBase + VirtualAddress</blockquote><p>And the full array is declared inside the Optional Header as:</p><pre>IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];</pre><p>Where:</p><pre>#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16</pre><p>So this is simply <strong>16 entries</strong> of the same IMAGE_DATA_DIRECTORY structure, each pointing to a different and specific structure inside the PE file.</p><p>For example:</p><pre>DataDirectory[0] → VirtualAddress points to → IMAGE_EXPORT_DIRECTORY<br>DataDirectory[1] → VirtualAddress points to → IMAGE_IMPORT_DESCRIPTOR<br>DataDirectory[5] → VirtualAddress points to → IMAGE_BASE_RELOCATION<br>DataDirectory[9] → VirtualAddress points to → IMAGE_TLS_DIRECTORY</pre><p>So the IMAGE_DATA_DIRECTORY structure is always the same — but the <strong>structure it points to</strong> is different for each index.</p><p>Now, as I already told you, there are 16 entries in the Data Directory, which is defined in winnt.h like this:</p><pre>#define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16</pre><p>But the main question is — how do we know which structure each entry is pointing to?</p><p>For that, we use the predefined indexes (also given in winnt.h). Each index is fixed for a specific structure. For example, if we use DataDirectory[0], it will always point to the Export Directory. Even though every entry has the same format (VirtualAddress and Size), what it points to depends on the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*_8JhAR9rixy_Htci7bl8VA.png" /></figure><p>The image above (taken from winnt.h) shows all these entries. It clearly tells which index is used for which directory. The table below makes it even easier to understand.</p><pre>| Index | Name           | Points To                               |<br>| ----- | -------------- | ----------------------------------------|<br>| 0     | EXPORT         | IMAGE_EXPORT_DIRECTORY                  |<br>| 1     | IMPORT         | IMAGE_IMPORT_DESCRIPTOR                 |<br>| 2     | RESOURCE       | IMAGE_RESOURCE_DIRECTORY                |<br>| 3     | EXCEPTION      | IMAGE_RUNTIME_FUNCTION_ENTRY            |<br>| 4     | SECURITY       | WIN_CERTIFICATE                         |<br>| 5     | BASERELOC      | IMAGE_BASE_RELOCATION                   |<br>| 6     | DEBUG          | IMAGE_DEBUG_DIRECTORY                   |<br>| 7     | ARCHITECTURE   | Reserved (deprecated)                   |<br>| 8     | GLOBALPTR      | RVA of global pointer                   |<br>| 9     | TLS            | IMAGE_TLS_DIRECTORY                     |<br>| 10    | LOAD_CONFIG    | IMAGE_LOAD_CONFIG_DIRECTORY             |<br>| 11    | BOUND_IMPORT   | IMAGE_BOUND_IMPORT_DESCRIPTOR           |<br>| 12    | IAT            | IMAGE_THUNK_DATA (Import Address Table) |<br>| 13    | DELAY_IMPORT   | IMAGE_DELAYLOAD_DESCRIPTOR              |<br>| 14    | COM_DESCRIPTOR | IMAGE_COR20_HEADER (.NET)               |<br>| 15    | RESERVED       | Must be 0                               |</pre><p>This table shows all 16 entries and what each one points to inside the PE file. So even though the structure (IMAGE_DATA_DIRECTORY) is always the same, its meaning changes based on its position (index). For example, index 0 → Export, index 1 → Import, index 5 → Base Relocation, and so on.</p><p>In simple words, the Data Directory works like a lookup table. Each index is reserved for a specific type of data. This helps the Windows loader quickly find things like imports, exports, resources, TLS, etc.</p><p>Now I assume that you have a good idea about these concepts, but to make it even clearer, we will go through an example. I know this topic can be confusing at first — even I was confused when I first learned it — so let’s break it down step by step.</p><p>We already know that the Data Directory is an array of 16 entries, and each entry is represented by the IMAGE_DATA_DIRECTORY structure:</p><pre>typedef struct _IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress;<br>    DWORD Size;<br>} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;</pre><p>Now the important question is — how does this simple two-field structure know what it is pointing to? . These pointer values are inserted by the linker at compile time.</p><p>Let’s understand this with an example.</p><p>The full array declaration inside the Optional Header is:</p><pre>IMAGE_DATA_DIRECTORY DataDirectory[16];</pre><p>Now assume we are looking at DataDirectory[0], which corresponds to IMAGE_DIRECTORY_ENTRY_EXPORT. For this specific slot, the same IMAGE_DATA_DIRECTORY structure now looks like this internally:</p><pre>typedef struct _IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress;  // RVA pointing to IMAGE_EXPORT_DIRECTORY<br>    DWORD Size;            // Size of IMAGE_EXPORT_DIRECTORY<br>} IMAGE_DATA_DIRECTORY;</pre><p>The VirtualAddress here is the RVA of IMAGE_EXPORT_DIRECTORY, which is a completely separate and detailed structure that lives somewhere inside the PE file. The Size is how large that IMAGE_EXPORT_DIRECTORY structure is.</p><p>The same logic applies to every other index:</p><pre>// DataDirectory[1] - Import Table<br>IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress;  // RVA of IMAGE_IMPORT_DESCRIPTOR<br>    DWORD Size;            // Size of IMAGE_IMPORT_DESCRIPTOR<br>}<br><br>// DataDirectory[5] - Base Relocation Table<br>IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress;  // RVA of IMAGE_BASE_RELOCATION<br>    DWORD Size;            // Size of IMAGE_BASE_RELOCATION<br>}<br><br>// DataDirectory[9] - TLS Table<br>IMAGE_DATA_DIRECTORY {<br>    DWORD VirtualAddress;  // RVA of IMAGE_TLS_DIRECTORY<br>    DWORD Size;            // Size of IMAGE_TLS_DIRECTORY<br>}</pre><p>So in simple terms:</p><ul><li>The IMAGE_DATA_DIRECTORY structure is always the same — just VirtualAddress + Size</li><li>The <strong>index</strong> decides what structure the VirtualAddress is pointing to</li><li>The actual detailed structure (like IMAGE_EXPORT_DIRECTORY or IMAGE_IMPORT_DESCRIPTOR) lives separately inside the PE file</li><li>VirtualAddress is always an RVA, so to reach the actual structure in memory:</li></ul><pre>Actual Address = ImageBase + VirtualAddress</pre><p>And if VirtualAddress = 0, it simply means that particular structure does <strong>not exist</strong> in the PE file. For example, if a PE file has no exports, DataDirectory[0].VirtualAddress will be 0. This is the foundation of how Windows loader navigates through a PE file — it goes to a specific index in the Data Directory, reads the VirtualAddress, adds the ImageBase, and reaches the actual structure it needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*W20zMXcKZsWmCaijDtT13w.png" /><figcaption>Example with PE-bear (DataDirectory)</figcaption></figure><p>Understanding this is very important in reverse engineering and malware analysis, because it helps you know where important parts of a PE file are located and how they are used during execution. It also helps when writing your own functions, and you will see it used many times in techniques like Hell’s Gate and SysWhispers.</p><p>Till now you have idea of data directory now we will learn about all the 16 entry in detail</p><h3>IMAGE_EXPORT_DIRECTORY</h3><p>IMAGE_EXPORT_DIRECTORY is a structure in a PE file that contains information about all the functions and data that a program (DLL or EXE) exports, meaning the functions that can be used by other programs. It basically stores the details needed to find exported function names, their addresses, and their ordinals.</p><p>Now, to understand this better, connect it with what we learned earlier.</p><p>If you remember our previous blog on <a href="https://medium.com/@0xnirsec/windows-architecture-how-windows-executes-api-calls-nir-4-ced348909335"><strong>Windows API Execution Flow</strong></a>, we saw how a simple API call travels through multiple layers — from the user process, through kernel32.dll, kernelbase.dll, and finally ntdll.dll before reaching the kernel via a syscall. In that flow, we noticed that DLLs like kernel32.dll and kernelbase.dll <strong>export functions</strong> such as CreateFile and CreateFileW that our application can call. But have you ever wondered — how does Windows actually know where those functions are located inside the DLL? When your program calls CreateFileW, it does not hardcode the memory address of that function. Instead, Windows finds it automatically at runtime.</p><p>Every DLL that exports functions contains this special structure inside its PE file. It acts like a directory or a lookup table that stores two critical pieces of information — the <strong>name of every exported function</strong> and the <strong>RVA (Relative Virtual Address)</strong> pointing to where that function actually lives in memory. So when Windows loads kernel32.dll and your process needs CreateFileW, the loader walks through the IMAGE_EXPORT_DIRECTORY of that DLL, searches for the name CreateFileW, finds its corresponding address, and hands it back to your program. You never had to remember or hardcode any address — Windows did all of that using IMAGE_EXPORT_DIRECTORY behind the scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*qVjxY2TjUfW_JeCSFIL3ng.png" /><figcaption>IMAGE_EXPORT_DIRECTORY</figcaption></figure><p>IMAGE_EXPORT_DIRECTORY is a structure that stores all the key information about exported functions in a DLL. It includes basic details like the DLL name (Name), the starting ordinal (Base), the total number of exported functions (NumberOfFunctions), and how many of them have names (NumberOfNames). The most important part of this structure is the three arrays: AddressOfFunctions, AddressOfNames, and AddressOfNameOrdinals. These work together to map a function name to its actual memory address by following the flow: name → ordinal → function address. In simple terms, this structure helps Windows locate exported functions inside a DLL. I will cover this in much more detail in a future module.</p><h3>IMAGE_IMPORT_DESCRIPTOR</h3><p>IMAGE_IMPORT_DESCRIPTOR is a structure in a PE file that contains information about all the functions that a program (EXE or DLL) imports, meaning the functions it needs to borrow from other DLLs in order to work. It basically stores the details needed to find which DLL is being used and which functions are being called from it.</p><p>Now, to understand this better, connect it with what we learned earlier.</p><p>If you remember our previous blog on <a href="https://medium.com/@0xnirsec/windows-architecture-how-windows-executes-api-calls-nir-4-ced348909335">Windows API Execution Flow</a>, we saw how our user process FILE.exe called CreateFileW from kernel32.dll. But have you ever wondered — how did FILE.exe even know that it needed kernel32.dll in the first place? And how did Windows know which functions to load from that DLL before the program even started running? The answer lies in the import table.</p><p>This is exactly where IMAGE_IMPORT_DESCRIPTOR comes into the picture. Every EXE or DLL that uses functions from another DLL contains this structure inside its PE file. It acts like a shopping list — it tells Windows which DLLs the program depends on and which functions it needs from each of them. So when Windows loads FILE.exe, before execution even begins, the loader reads through the IMAGE_IMPORT_DESCRIPTOR, finds that the program needs CreateFileW from kernel32.dll, loads that DLL into memory, finds the function address using the IMAGE_EXPORT_DIRECTORY of kernel32.dll, and writes it into the program so it is ready to use. You never had to manually load any DLL or find any address yourself — Windows did all of that using IMAGE_IMPORT_DESCRIPTOR behind the scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*usDCv_doW1g3L1sYpzCzig.png" /></figure><p>IMAGE_IMPORT_DESCRIPTOR is a structure that stores all the key information about the DLLs a program imports from. Looking at the structure definition in above image, it contains the following fields. OriginalFirstThunk points to the <strong>Import Lookup Table (ILT)</strong>, which is a backup copy that stores the original function names or ordinals and never gets modified by Windows. TimeDateStamp is 0 when imports are not yet bound, meaning Windows has not resolved the addresses yet. ForwarderChain is used when one DLL forwards a function call to another DLL, and is -1 when there are no forwarders. Name is an RVA pointing to the ASCII name of the DLL being imported from, for example KERNEL32.dll. FirstThunk points to the <strong>Import Address Table (IAT) </strong>array (array of IMAGE_THUNK_DATA entries), which is where Windows writes the actual memory addresses of functions at load time. Specifically, the FirstThunk field inside the descriptor points directly to the IAT, which is where Windows patches in the real function addresses when the DLL is loaded. Before the program runs, these entries hold function name references. The moment Windows loads the program, it replaces every single one of them with the real memory address of that function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Xsy9KE1YkLigS0QE_ur-sQ.png" /><figcaption>Example of IMAGE_IMPORT_DESCRIPTOR</figcaption></figure><p>There is one IMAGE_IMPORT_DESCRIPTOR entry for each DLL the program depends on, and the list ends with a null entry. In simple terms, this structure tells Windows everything it needs to know to wire up a program&#39;s dependencies before it starts running. I will cover this in much more detail in a future module.</p><h3>IMAGE_RESOURCE_DIRECTORY</h3><p>IMAGE_RESOURCE_DIRECTORY is a structure in a PE file that contains information about all the resources embedded inside a program, meaning things like icons, images, dialog boxes, string tables, version information, and menus that the program carries within itself. It basically stores the details needed to organize and locate these embedded resources at runtime.</p><p>Now, to understand this better, think about something simple. When you open any Windows application like Notepad or Chrome, you see an icon in the taskbar and title bar. That icon is not loaded from some external file — it is embedded directly inside the EXE itself. Similarly, when an application shows an error message dialog or a menu, those are also not stored separately outside the program. They are embedded as resources inside the PE file, and IMAGE_RESOURCE_DIRECTORY is the structure that keeps track of all of them.</p><p>Every EXE or DLL that contains embedded resources has this structure inside its PE file. The first level represents the <strong>resource type</strong>, such as icon, dialog, string table, or version info. The second level represents the <strong>resource ID or name</strong>, which identifies the specific resource within that type. The third level represents the <strong>language</strong>, allowing the same resource to exist in multiple languages for localization purposes. Windows walks down this tree whenever it needs to find and load a specific resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*BvXY6TuG1PObiGbrwAIB8g.png" /></figure><p>Looking at the structure definition, it contains the following fields. Characteristics is reserved and always zero. TimeDateStamp records when the resource directory was created. MajorVersion and MinorVersion are version numbers that are almost always zero in practice. The two most important fields are NumberOfNamedEntries and NumberOfIdEntries — NumberOfNamedEntries tells you how many resources in this directory are identified by a string name, while NumberOfIdEntries tells you how many are identified by a numeric ID. After the structure itself comes an array of IMAGE_RESOURCE_DIRECTORY_ENTRY entries, one for each resource, which point deeper into the tree until you finally reach the actual raw resource data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*Y1DMm8XTQSm_cO16yiYMFw.png" /><figcaption>Example of IMAGE_RESOURCE_DIRECTORY</figcaption></figure><p>In simple terms, this structure is how Windows knows what resources are packed inside a program and where to find each one of them.</p><h3>IMAGE_THUNK_DATA / IAT</h3><p>IMAGE_THUNK_DATA is a structure in a PE file that represents a single entry inside either the Import Lookup Table (ILT) or the Import Address Table (IAT). In simple words, if the IAT is a table with multiple rows, then one IMAGE_THUNK_DATA is just one single row of that table. It stores the information needed to identify a specific imported function — either by its name or by its ordinal number.</p><p>Every function that a program imports from a DLL has its own dedicated IMAGE_THUNK_DATA entry. It is a union, meaning the same structure holds different things depending on the situation. Before Windows loads the program, each entry holds either an RVA pointing to an IMAGE_IMPORT_BY_NAME structure which contains the function name and a hint value, or a direct ordinal number if the function is imported by ordinal rather than name. The moment Windows loads the program, it replaces each entry with the real runtime memory address of that function. From that point on, every time your program calls an imported function, it jumps through that IMAGE_THUNK_DATA entry in the IAT to reach the actual function in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*nO5GmJBOK3NfQ4KRQXhUhQ.png" /></figure><p>IMAGE_THUNK_DATA is a union that can hold one of three things depending on the context. Before loading, it holds either AddressOfData, which is an RVA pointing to an IMAGE_IMPORT_BY_NAME structure containing the function name and hint, or an ordinal number stored in the lower bits with the highest bit set as a flag to indicate it is an ordinal import. After loading, it holds Function, which is the actual runtime virtual address of the imported function that Windows has resolved and patched in. The <strong>IAT itself</strong> is simply the full array of these IMAGE_THUNK_DATA entries sitting sequentially in the .idata or .rdata section of the PE file, terminated by a null entry. So IMAGE_IMPORT_DESCRIPTOR tells Windows which DLL to load, and IMAGE_THUNK_DATA tells Windows which specific functions to find inside that DLL.</p><h3><strong>IAT (Import Address Table) IMP</strong></h3><p>The Import Address Table (IAT) is simply a collection of IMAGE_THUNK_DATA entries arranged sequentially in memory, terminated by a null entry. Each entry in this collection represents one single imported function. Before Windows loads the program, each IMAGE_THUNK_DATA entry inside the IAT holds either a function name reference or an ordinal number. The moment Windows loads the program, it walks through every single entry in the IAT and replaces each one with the real runtime memory address of that function. From that point on, every time your program calls an imported function, it jumps through the corresponding entry in the IAT to reach the actual function in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*Ytr6cSYvGj5Vv4GPCv2rUg.png" /><figcaption>Import Address Table</figcaption></figure><p>The IAT physically lives inside the .idata or .rdata section of the PE file and can be located in two ways — either through the FirstThunk field inside IMAGE_IMPORT_DESCRIPTOR, or directly through DataDirectory[12] in the Optional Header. Both point to the same location in memory. There is one IAT per imported DLL, meaning if your program imports from three DLLs, there are three separate IAT arrays — one for each DLL. In simple terms, the IAT is the final destination where Windows writes all the real function addresses, making it possible for your program to actually call imported functions at runtime. I will cover this in much more detail in a future module.</p><h3>WIN_CERTIFICATE</h3><p>WIN_CERTIFICATE is a structure in a PE file that stores the digital signature attached to an executable, meaning it contains the cryptographic proof that verifies who created the program and that it has not been tampered with since it was signed. It basically stores the certificate data that Windows uses to decide whether a program can be trusted before running it. Unlike most other PE structures which are defined in &lt;winnt.h&gt;, WIN_CERTIFICATE is defined in <strong>&lt;wintrust.h&gt;</strong> because it belongs to the Windows Trust and Verification subsystem — the part of Windows responsible for handling code signing, certificate validation, and publisher trust decisions.</p><p>Now, to understand this better, think about something simple. When you download software from the internet and run it, Windows sometimes shows a UAC prompt saying “Verified publisher: Microsoft Corporation” with a blue shield, or sometimes shows a warning saying “Unknown Publisher” with an Red shield. That difference comes entirely from whether the executable has a valid digital signature stored in its WIN_CERTIFICATE structure or not.</p><p>When a software company wants to sign their executable, they generate a cryptographic hash of the entire file contents and encrypt it using their private key. This signature, along with their certificate information, is then stored in the WIN_CERTIFICATE structure and embedded into the PE file. When Windows or a security tool loads that executable, it reads this structure, decrypts the signature using the publisher&#39;s public key, recomputes the hash of the file, and compares the two. If they match, the file is verified as authentic and untampered. If they do not match, it means the file was modified after signing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*BilZTXwzmtIKNNWltgKVTA.png" /></figure><p>Looking at the structure definition in the above image, WIN_CERTIFICATE contains the following fields. dwLength is the total size of the entire certificate structure in bytes. wRevision indicates the certificate version. wCertificateType tells what kind of certificate data is stored — the most common value is WIN_CERT_TYPE_PKCS_SIGNED_DATA meaning the signature follows the PKCS7 standard. And finally bCertificate[ANYSIZE_ARRAY] is a flexible array that holds the actual raw certificate data itself — its real size is determined by dwLength at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*cLfxvij_Xlrx1Hgqqw0NyQ.png" /></figure><p>One important thing that makes WIN_CERTIFICATE different from every other Data Directory entry is that its value in DataDirectory[4] is a <strong>file offset</strong>, not an RVA like all the other entries. This is because the certificate data is appended at the very end of the PE file after all the sections, and it is never mapped into memory when the image is loaded — Windows reads it directly from disk for verification purposes only.</p><p>Till now, we have covered the most important Data Directory entries that are directly relevant to malware development and reverse engineering. The remaining directories are equally interesting and will be covered in future blogs when we reach the techniques that actually use them.</p><p>For now, let’s take what we have learned and see how it actually looks inside a real PE file. The image below shows the Data Directory as viewed in PE-bear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*FPJrOV6rmWzDcqqoHADfpA.png" /></figure><p>At this point, we have walked through the most critical Data Directory entries from a malware development and reverse engineering perspective. But you might be wondering — why did we skip several entries and focus only on specific ones? The answer is simple: not all 16 entries are equally relevant to what we are building toward.</p><p>Each directory we covered was chosen deliberately because it plays a direct role in real-world offensive and defensive techniques:</p><ul><li><strong>IMAGE_EXPORT_DIRECTORY</strong> — Essential when writing custom GetProcAddress-style functions. Techniques like Hell’s Gate and SysWhispers walk the export directory of ntdll.dll manually to resolve syscall stubs without calling the standard Windows API, which helps avoid userland hooks placed by EDRs and AVs.</li><li><strong>IMAGE_IMPORT_DESCRIPTOR &amp; IAT</strong> — The Import Address Table is one of the primary things Antivirus and EDR solutions inspect to detect malicious behavior. By analyzing which functions a PE imports, security tools can flag suspicious activity before the program even runs. Understanding the IAT is also the foundation for IAT hooking, a technique used both by malware and security products alike.</li><li><strong>WIN_CERTIFICATE</strong> — Understanding the certificate structure is important when working with techniques like Reflective PE Loading or when stripping/spoofing signatures to bypass trust-based verification checks that some security solutions rely on.</li></ul><p>The remaining directories — such as Exception, TLS, Load Config, and Base Relocation — are equally important and will be covered in upcoming modules when we reach the techniques that actually use them. Everything in this series is built intentionally, so when those topics arrive, you will already have the PE knowledge needed to understand them deeply.</p><p>For now, what you have learned about the Data Directory is more than enough to move forward. Let’s take a look at how all of this looks inside a real PE file.</p><p>In this blog, we explored the Data Directory in detail, which is one of the most critical components of the Optional Header inside a Portable Executable (PE) file. We began by understanding its overall layout, including what the IMAGE_DATA_DIRECTORY structure is, how it works as a fixed array of 16 entries, and how each entry uses a VirtualAddress and Size to point to a completely different and specific structure inside the PE file.</p><p>We then focused on the most important entries individually. We covered the Export Directory and how Windows uses it to locate exported functions inside a DLL at runtime. We explored the Import Descriptor and the Import Address Table and saw how Windows wires up a program’s dependencies before execution even begins. We also looked at the Resource Directory and how embedded resources like icons and dialogs are organized, and finally the WIN_CERTIFICATE structure and how digital signatures are stored and verified.</p><p>Through both theoretical explanation and practical analysis using real PE-bear values, we saw how these entries act as a lookup table that the Windows loader relies on to navigate through a PE file efficiently.</p><p>This blog was designed to build a strong and clear foundation around the Data Directory. However, the remaining entries such as Base Relocation, TLS, Exception, and Load Config will be covered in future blogs when we reach the techniques that directly use them.</p><p>This knowledge becomes especially powerful when analyzing malware samples, bypassing security checks, understanding EDR detection logic, or writing your own low-level tools and loaders.</p><p><strong>Note: </strong>This content is intended for educational and defensive cybersecurity purposes only. Always use this knowledge ethically.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d2d26cfbcbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to NT-Headers (PE)-Nir(8)]]></title>
            <link>https://0xnirsec.medium.com/introduction-to-nt-headers-pe-nir-8-adbae96b7413?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/adbae96b7413</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sat, 25 Jul 2026 07:21:43 GMT</pubDate>
            <atom:updated>2026-07-25T07:41:59.471Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Cybersecurity enthusiasts and white hat hackers !!</p><p>In our previous blog, we explored the DOS Header and DOS Stub in detail. Now, in today’s blog, we are going to dive into the most important part of the PE structure — the <strong>NT Header</strong>.</p><p>Once again, the image below represents the overall structure of a PE file. As we already learned, after the DOS Header and DOS Stub, the system uses the e_lfanew field to locate the NT Header. This field provides the exact offset where the NT Header begins, allowing Windows to navigate to it and continue the execution process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*sJQw3WT1Hx2qmhLt.png" /></figure><p>In this blog, we are going to take a practical approach. For that, we need a tool to analyze PE files. I will be using <strong>PE-bear</strong> to demonstrate and explore these structures step by step.</p><h3>What is NT Header?</h3><p>NT Header is the most important structure in a Portable Executable (PE) file. It contains all the critical information that windows needs to properly load and execute the program. While the DOS Header is mainly use for initial validation, the NT header is where the actual execution logic begins.</p><p>NT Header is a <a href="https://beej.us/guide/bgc/html/split/structs.html#structs">structure </a>defined in the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32">winnt.h</a> header file in Windows. It is represented as <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32">IMAGE_NT_HEADERS32</a> for 32-bit executables. [There is 64 bit version structure for this which has <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers64">IMAGE_NT_HEADERS64</a>]</p><p>If we look at its definition, we get the following structure:</p><pre>typedef struct _IMAGE_NT_HEADERS {<br>  DWORD                     Signature;<br>  IMAGE_FILE_HEADER         FileHeader;<br>  IMAGE_OPTIONAL_HEADER32   OptionalHeader;<br>} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;</pre><p>This structure clearly shows that NT Header is divided into three main parts.</p><ul><li>Signature</li><li>FileHeader (<a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header">IMAGE_FILE_HEADER</a>)</li><li>OptionalHeader (<a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32">IMAGE_OPTIONAL_HEADER32</a>)</li></ul><p>This means that the NT Header consists of three components. Among these, the File Header and Optional Header are themselves separate structures that contain additional fields and detailed information required for execution. The NT Header acts like a container, where each part holds specific data that helps Windows understand and run the executable properly.</p><p>Let’s also confirm this using PE-bear.</p><p>When we load any executable file into the PE-bear tool, we can clearly see the structure of the NT Header. As shown in the image, the NT Header is divided into three parts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*sPD_uNh0yUEfBwPyLZxydQ.png" /></figure><p>This confirms what we discussed earlier — the NT Header consists of three different components, and each of them plays a specific role in the execution of the PE file.</p><p>Let’s start with each section explanation one by one</p><h3>NT Header (Signature)</h3><p>Let’s start with the first component of the NT Header, which is the <strong>Signature</strong>.</p><p>The Signature is a <strong>4-byte value</strong> that marks the beginning of the NT Header. Its value is always:</p><pre>50 45 00 00 → “PE\0\0”</pre><p>This is similar to how the DOS Header uses the &quot;MZ&quot; signature. In the same way, the NT Header uses the &quot;PE&quot; signature to confirm that the file is a valid <strong>Portable Executable (PE)</strong>. When Windows loads an executable file, it first follows the e_lfanew offset to locate the NT Header. Once it reaches that location, it checks the Signature value.</p><ul><li>If the value is &quot;PE&quot; → the file is considered valid, and execution continues</li><li>If the value is incorrect → the file is treated as invalid, and execution fails</li></ul><p>Even though the DOS Header already checks the &quot;MZ&quot; signature, the NT Header performs another check.</p><p>This second check ensures two things:</p><ul><li>The file is truly a valid <strong>PE file</strong> (not just any file with &quot;MZ&quot;)</li><li>We have reached the <strong>correct location (NT Header)</strong> using e_lfanew</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Erq3w6JceHLSEBeCNXQnIw.png" /></figure><p>As shown in the above image, we opened an executable file (file.exe) in a PE analysis tool and navigated to the <strong>NT Header → Signature</strong>.</p><p>At the offset pointed by e_lfanew, we can clearly observe the bytes:</p><pre>50 45 00 00  →  &quot;PE\0\0&quot;</pre><p>This confirms the presence of the <strong>PE Signature</strong>, which is used for validation.</p><h3>NT Header (File Header)</h3><p><strong>File Header</strong> is a structure that contains important information about the PE file. Just like normal files have <strong>metadata</strong>, the File Header stores <strong>essential metadata</strong> required by the Windows loader to understand and execute the PE file.</p><p>This structure is defined in the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header">winnt.h</a> header file as:</p><pre>typedef struct _IMAGE_FILE_HEADER {<br> WORD     Machine;<br> WORD     NumberOfSections;<br> DWORD    TimeDateStamp;<br> DWORD    PointerToSymbolTable;<br> DWORD    NumberOfSymbols;<br> WORD     SizeOfOptionalHeader;<br> WORD     Characteristics;<br>} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;</pre><p>Machine</p><p>Specifies the target CPU architecture for which the executable is compiled. This field can contain multiple values, but the most commonly encountered are: 0x8664 → AMD64 (x64) and 0x14c → Intel 386 (x86). Additional values also exist; for a complete list, refer to the<a href="https://learn.microsoft.com/en-us/windows/win32/debug/pe-format"> official documentation</a>.</p><p>NumberOfSections</p><p>The number of sections in PE files . Specifies the <strong>total number of sections</strong> present in the PE file. This value determines the size of the <strong>Section Table</strong>, which is located immediately after the headers. The Windows loader uses this information to process and load each section.</p><p>TimeDateStamp</p><p>Represents the <strong>timestamp of the image</strong>, indicating when the executable was created by the linker. It is stored as the <strong>low 32 bits</strong> of a Unix timestamp, representing the number of seconds elapsed since <strong>January 1, 1970 (00:00:00 UTC)</strong>, based on the system clock.</p><p>PointerToSymbolTable &amp; NumberOfSymbols</p><p>These fields specify the file offset to the COFF symbol table and the number of entries within it. In modern PE files, both fields are typically set to <strong>0</strong>, indicating that no symbol table is present. This is because COFF-based debugging information is now <strong>deprecated</strong> and has been replaced by more advanced debugging formats (such as PDB files).</p><p>SizeOfOptionalHeader</p><p>Specifies the size (in bytes) of the <strong>Optional Header</strong> that follows the File Header. This field is important because it tells the loader where the section table begins. In executable (PE) files, this value is always non-zero, while in object files it is typically set to <strong>0</strong>.</p><p>Characteristics</p><p>Defines the attributes and properties of the file using a set of <strong>flags</strong>. These flags describe how the file should be interpreted and loaded by the system, such as whether it is executable, a DLL, a system file, or if it supports specific features. <a href="https://learn.microsoft.com/en-us/windows/win32/debug/pe-format">Multiple flags</a> can be combined to represent different characteristics of the image.</p><p>From the provided image, we can interpret the <strong>File Header fields</strong> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NLWRflRlq_GEu9Jbiy7wCw.png" /></figure><p><strong>Machine (CPU Architecture)</strong></p><p>The value is <strong>0x8664</strong>, which corresponds to <strong>AMD64 (x64 architecture)</strong>. This means the executable is compiled for <strong>64-bit systems</strong> and will run on modern 64-bit Windows environments.</p><p><strong>Number of Sections</strong></p><p>The value is <strong>10 (0xA)</strong>. This indicates that the PE file contains <strong>10 sections</strong>, meaning there are 10 entries in the section table that follows the headers.</p><p><strong>TimeDateStamp</strong></p><p>The value <strong>0x69c167b5</strong> translates to: <strong>Monday, 23 March 2026, 16:17:57 UTC .</strong>This represents the <strong>compile time</strong> of the binary (set by the linker).</p><p><strong>PointerToSymbolTable &amp; NumberOfSymbols</strong></p><p>Both values are <strong>0</strong>. This confirms that <strong>no COFF symbol table is present</strong>, which is expected in modern PE files since this format is deprecated.</p><p><strong>SizeOfOptionalHeader</strong></p><p>The value is <strong>0xF0 (240 bytes)</strong>. This indicates the size of the <strong>Optional Header</strong>, which contains important execution-related information (entry point, image base, etc.).</p><p><strong>Characteristics</strong></p><p>The value is <strong>0x22</strong>, which corresponds to:</p><ul><li><strong>0x02 → Executable Image. </strong>The file is a valid executable (no unresolved references)</li><li><strong>0x20 → Large Address Aware. </strong>The application can use <strong>more than 2GB of memory.</strong></li></ul><h3>NT Header (Optional Header)</h3><p>Although every part of the PE structure is important to understand, the <strong>Optional Header</strong> is the most critical component. Despite its name suggesting that it is “optional,” in practice it is <strong>essential for executable files</strong>. This header contains key information required by the Windows loader, such as the entry point, image base, memory layout, and execution settings. Without it, the operating system would not be able to correctly load and run the executable.</p><p>The Optional Header is a structure that holds critical information used by the Windows loader, such as memory layout, entry point, and execution parameters, which are necessary to properly load and run the PE file.</p><p>This structure is defined in the <a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><em>winnt.h</em></a> header file as:</p><pre>typedef struct _IMAGE_OPTIONAL_HEADER64 {<br> WORD                Magic;<br> BYTE                MajorLinkerVersion;<br> BYTE                MinorLinkerVersion;<br> DWORD               SizeOfCode;<br> DWORD               SizeOfInitializedData;<br> DWORD               SizeOfUninitializedData;<br> DWORD               AddressOfEntryPoint;<br> DWORD               BaseOfCode;<br> ULONGLONG           ImageBase;<br> DWORD               SectionAlignment;<br> DWORD               FileAlignment;<br> WORD                MajorOperatingSystemVersion;<br> WORD                MinorOperatingSystemVersion;<br> WORD                MajorImageVersion;<br> WORD                MinorImageVersion;<br> WORD                MajorSubsystemVersion;<br> WORD                MinorSubsystemVersion;<br> DWORD               Win32VersionValue;<br> DWORD               SizeOfImage;<br> DWORD               SizeOfHeaders;<br> DWORD               CheckSum;<br> WORD                Subsystem;<br> WORD                DllCharacteristics;<br> ULONGLONG           SizeOfStackReserve;<br> ULONGLONG           SizeOfStackCommit;<br> ULONGLONG           SizeOfHeapReserve;<br> ULONGLONG           SizeOfHeapCommit;<br> DWORD               LoaderFlags;<br> DWORD               NumberOfRvaAndSizes;<br> IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];<br>} IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;</pre><p>Although it is not necessary to understand every field of the Optional Header in depth at this stage, it is important to recognize that it is the <strong>most critical header in a PE file</strong>. It contains all the essential information required by the Windows loader to correctly load and execute the program.</p><p>For now, we will focus only on the <strong>basic understanding of its members</strong>, and in future sections, each field will be explained in detail as needed.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>Magic</strong></a></p><p>The Magic field in the PE Optional Header is a crucial value that determines the type of Portable Executable (PE) file. It is a 2-byte (WORD) identifier that tells the system whether the file is a 32-bit or 64-bit executable. Specifically, a value of 0x10B indicates a PE32 (32-bit) file, while 0x20B represents a PE32+ (64-bit) file, and 0x107 is used for ROM images, which are rarely encountered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*7MuP4d-l4kXeXLx7c3frgw.png" /></figure><p>In addition, this check exists as part of a layered validation process in PE parsing. First, the MZ signature is verified to confirm the file is an executable. Then, the PE signature is checked to ensure it follows the Portable Executable format used by Windows. After that, the Magic field is examined to determine whether the file is 32-bit or 64-bit. This sequence is necessary because each step answers a different question: <em>Is this an executable? Is it a valid PE file? What type of PE file is it?</em> By performing these checks in order, the system or parser can safely and accurately interpret the file structure without errors.</p><p>In the image below, the <strong>Magic</strong> field is shown with a value of 0x20B. This value indicates that the executable is a <strong>PE32+ (64-bit)</strong> binary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*xdSIS4RN3C6kUUy3kgEvvQ.png" /></figure><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>MajorLinkerVersion and MinorLinkerVersion</strong></a></p><p>MajorLinkerVersion and MinorLinkerVersion store the <strong>version number of the linker tool</strong> that was used to create the PE file.A <strong>linker</strong> is a part of the compilation process. After the compiler converts source code into object files (.obj), the linker combines those object files with required libraries and creates the final executable file (.exe, .dll, .sys). The version is divided into two parts:</p><ul><li><strong>MajorLinkerVersion</strong> → Represents the major version of the linker.</li><li><strong>MinorLinkerVersion</strong> → Represents the minor version or smaller updates of the linker.</li></ul><p>This indicates that the PE file was created using linker version <strong>14.30</strong>, which is commonly associated with Microsoft Visual C++ toolchains.</p><p>These fields are mainly useful for <strong>identification and analysis</strong>. They can help analysts understand the possible build environment and tools used to create the PE file. However, Windows does not use these values during execution and does not verify the linker version before running the program.</p><p>Since these fields are stored inside the PE header and are not protected, attackers can modify them easily. By changing these values, attackers can make analysis more difficult or provide false information about the toolchain used to build the file. Therefore, analysts should not rely only on linker version information as proof of the compiler or development environment. It should be combined with other PE characteristics during analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*zJ0_EExxmQRF2LN1yUS_9w.png" /></figure><p>In the image above, the <strong>MajorLinkerVersion</strong> is shown as E and the <strong>MinorLinkerVersion</strong> as 32. Since these values are stored in hexadecimal format, E corresponds to <strong>14</strong> in decimal, while 32 corresponds to <strong>50</strong> in decimal. This means the linker version used to build this PE file is <strong>14.50</strong>. This version is typically associated with modern Microsoft Visual C++ toolchains, indicating that the executable was likely compiled using a relatively recent development environment.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>SizeOfCode, SizeOfInitializedData, SizeOfUninitializedData</strong></a></p><p><strong>SizeOfCode</strong> stores the total size of all sections in the PE file that contain executable instructions. Normally, this refers to the .text section, where the program&#39;s machine code is stored. This value helps identify how much space the actual executable code occupies inside the PE file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*NobeoKnQzXhkVKP9mL7Hgw.png" /><figcaption>Example Of Sections</figcaption></figure><p><strong>Note:</strong> PE Sections store the actual contents of the PE file, including executable code, data, imports, resources, and relocation information. (Detailed explanation of each section will be covered in later blogs.)</p><p><strong>SizeOfInitializedData</strong> stores the total size of initialized data sections. These sections contain global and static variables that already have a value assigned before the program starts. For example:</p><pre>int count = 10;<br>char name[] = &quot;Hello&quot;;</pre><p>The values of these variables are stored inside the PE file because they are already initialized.</p><p><strong>SizeOfUninitializedData</strong> stores the size of uninitialized data sections, usually the .bss section. This section contains global and static variables that are declared but do not have an initial value. For example:</p><pre>int counter;<br>char buffer[100]</pre><p>This data does not need to be stored inside the PE file because it does not contain any meaningful value yet. When Windows loads the PE file into memory, the loader creates this space and initializes it with zeros.</p><p>In simple terms:</p><ul><li><strong>SizeOfCode → Size of executable instructions</strong></li><li><strong>SizeOfInitializedData → Size of data with predefined values</strong></li><li><strong>SizeOfUninitializedData → Size of data reserved in memory but initialized as zero</strong></li></ul><p>These fields help the Windows loader understand the layout and memory requirements of the PE file. They are also useful during reverse engineering because unusual values can sometimes indicate packed, obfuscated, or suspicious PE files.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32"><strong>AddressOfEntryPoint (DWORD)</strong></a></p><p>AddressOfEntryPoint stores the <strong>Relative Virtual Address (RVA) of the first instruction that the Windows loader executes after loading the PE file into memory</strong>.It represents the location of the program’s entry point <strong>relative to the beginning of the PE image</strong>, not the actual memory address where the code is located.</p><p>The value stored in AddressOfEntryPoint is an <strong>offset from the PE file&#39;s </strong><strong>ImageBase</strong>. Since the exact memory location where a PE file is loaded can change due to mechanisms like <strong>ASLR (Address Space Layout Randomization)</strong>, the PE file does not store a fixed memory address for its entry point.</p><p>Instead, the PE header stores the RVA value, and when Windows loads the PE file into memory, the loader calculates the actual execution address by adding the ImageBase value and AddressOfEntryPoint.</p><p><strong>Formula:</strong></p><pre>Entry Point Address = ImageBase + AddressOfEntryPoint</pre><p>Example:</p><pre>ImageBase = 0x140000000<br>AddressOfEntryPoint = 0x1000</pre><p>The actual execution address becomes:</p><pre>0x140000000 + 0x1000 = 0x140001000</pre><p>The CPU begins execution from this final virtual address (0x140001500).</p><p>For a normal executable, the AddressOfEntryPoint usually points to the program&#39;s startup code, which later initializes the runtime environment and calls functions such as main() or WinMain().</p><p>However, in packed, protected, or malicious PE files, the entry point may not point directly to the original program logic. Instead, it may point to a <strong>loader stub or unpacking routine</strong> that performs actions such as decrypting, unpacking, or preparing the actual code before transferring execution.</p><p>During reverse engineering, AddressOfEntryPoint is one of the most important fields because analysts commonly use it as the first location to begin analyzing the executable&#39;s behavior. Changes or unusual entry points can also indicate packing, obfuscation, or suspicious modifications in a PE file.</p><p>In the image below, the <strong>AddressOfEntryPoint</strong> is shown as 0x1104B. This value represents the Relative Virtual Address (RVA) of the first instruction that will be executed when the PE file is loaded into memory. Since it is an RVA and not an absolute address, the actual execution address depends on the ImageBase.</p><p>To determine the real memory address where execution begins, we add the ImageBase to the AddressOfEntryPoint. For example, if the ImageBase is 0x140000000, the final execution address would be:</p><p><strong>0x140000000 + 0x1104B = 0x14001104B</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*zPlikUjVBv3xksh8NS9rEA.png" /></figure><h4>Relative Virtual Address (RVA)</h4><p>RVA (Relative Virtual Address) is an address format used inside a PE file to represent the location of data or code <strong>relative to the starting address of the PE image (</strong><strong>ImageBase) when it is loaded into memory</strong>.</p><p>Unlike a normal virtual address, an RVA does <strong>not contain the complete memory address</strong>. Instead, it stores only the <strong>offset from the beginning of the loaded PE image</strong>. The Windows loader uses the ImageBase and RVA value together to calculate the actual virtual memory address.</p><p><strong>Formula:</strong></p><pre>Virtual Address (VA) = ImageBase + RVA</pre><p>Example:</p><pre>ImageBase = 0x140000000<br>RVA = 0x2000</pre><p>The actual memory address becomes:</p><pre>0x140000000 + 0x2000 = 0x140002000</pre><p>This means the data or code located at RVA 0x2000 will be present at virtual address 0x140002000 after the PE file is loaded into memory.</p><h4>Why does PE use RVA instead of storing direct addresses?</h4><p>A PE file cannot always know the exact memory address where it will be loaded. Modern Windows uses <strong>ASLR (Address Space Layout Randomization)</strong>, which allows the operating system to load executables and DLLs at different memory locations for security reasons. Because the ImageBase can change, storing fixed memory addresses would make the PE file unreliable.</p><p>Instead, PE files store locations as RVAs. The loader adjusts them automatically based on the actual loading address.</p><p>Example:</p><p>Without RVA:</p><pre>Entry Point = 0x140001000</pre><p>If Windows loads the PE somewhere else, this address becomes invalid.</p><p>With RVA:</p><pre>ImageBase = 0x140000000<br>RVA = 0x1000</pre><p>If loaded normally:</p><pre>0x140000000 + 0x1000 = 0x140001000</pre><p>If ASLR changes the ImageBase:</p><pre>ImageBase = 0x150000000<br>RVA = 0x1000</pre><p>New address:</p><pre>0x150000000 + 0x1000 = 0x150001000</pre><p>The same code/data can still be found correctly.</p><h4>RVA is commonly used in PE structures</h4><p>Many PE header fields store locations as RVAs, such as:</p><ul><li><strong>AddressOfEntryPoint</strong> → RVA of the first instruction executed</li><li><strong>VirtualAddress in Section Headers</strong> → RVA where a section is loaded</li><li><strong>Import Directory RVA</strong> → Location of imported functions</li><li><strong>Export Directory RVA</strong> → Location of exported functions</li><li><strong>Resource Directory RVA</strong> → Location of resources</li></ul><h4>Difference Between RVA, VA, and File Offset</h4><p>File Offset (RAW Offset) refers to the specific location of data inside the PE file as it exists on the disk, such as 0x600. RVA (Relative Virtual Address) represents the offset from the ImageBase once the file is loaded into memory, for example, 0x2000. Finally, VA (Virtual Address) is the actual absolute memory address where the data resides after loading, calculated by adding the ImageBase to the RVA, resulting in an address like 0x140002000.</p><p>Relationship:</p><pre>VA = ImageBase + RVA</pre><p><strong>RVA → </strong>Distance from the beginning of the loaded PE image.<br><strong>ImageBase → </strong>Starting address of the PE image in memory.<br><strong>VA →</strong> Final memory address calculated by adding ImageBase and RVA.</p><p>RVA allows Windows to correctly locate code, data, imports, and other PE structures even when the PE file is loaded at different memory addresses.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32"><strong>ImageBase (ULONGLONG)</strong></a></p><p>ImageBase stores the <strong>preferred virtual memory address where the PE file wants to be loaded into memory</strong> by the Windows loader.</p><p>When a PE file is executed, Windows creates a process and maps the PE image (headers, sections, code, data, imports, etc.) into the process’s virtual memory space. The address where the PE image starts is called the <strong>Image Base Address</strong>.</p><p>The value stored in the ImageBase field represents the <strong>starting address of the entire PE image in memory</strong>. All other addresses inside the PE file, such as the entry point, sections, imports, and resources, are calculated relative to this address using <strong>RVA (Relative Virtual Address)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*qmDVTAjSBWG_JXowyTfaWQ.png" /><figcaption><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32"><strong>ImageBase (ULONGLONG)</strong></a></figcaption></figure><p>In the image above, the <strong>ImageBase</strong> value is shown as 0x140000000. This field represents the preferred virtual memory address where the Windows loader attempts to map the entire PE file when it is loaded into a process. In 64-bit executables (PE32+), the ImageBase is stored as a 64-bit value (ULONGLONG), allowing the program to reside in a much larger address space compared to 32-bit binaries.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32"><strong>BaseOfCode (DWORD)</strong></a></p><p>BaseOfCode stores the <strong>Relative Virtual Address (RVA) where the executable code section begins inside the PE image</strong>.</p><p>Normally, this value points to the beginning of the <strong>.text section</strong>, which contains the actual machine instructions executed by the CPU.</p><p>The PE file does not store the direct memory address of the code section because the loading address can change. Instead, it stores the location as an RVA relative to the ImageBase.</p><p><strong>Note:</strong><br>PE Sections store the actual contents of the PE file, including executable code, data, imports, resources, and relocation information. (Detailed explanation of each section will be covered in later blogs.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*hNBaCSLQb5MXSmeU5mfwEA.png" /><figcaption><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32"><strong>BaseOfCode (DWORD)</strong></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_yhCGS0bhpbdKyB_KkUWVQ.png" /></figure><p>In the image above, the <strong>BaseOfCode</strong> value is shown as 0x1000. This value represents the Relative Virtual Address (RVA) where the executable code section begins in memory. When we verify this using the section headers (as shown in the second image), we can see that the section with a Virtual Address of 0x1000 corresponds to the <strong>.text</strong> section (sometimes labeled differently like .textbss depending on the tool or packing). This confirms that the BaseOfCode is pointing to the starting location of the code section, which is where the actual executable instructions of the program reside.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>SectionAlignment</strong> &amp; <strong>FileAlignment</strong></a></p><p><strong>SectionAlignment</strong> and <strong>FileAlignment</strong> are important fields in the PE Optional Header that define how the executable is arranged both on disk and in memory. <strong>SectionAlignment</strong> specifies how each section should be aligned when the PE file is loaded into memory by the Windows loader. This means it controls the memory boundary at which sections such as .text, .rdata, and .data are placed after loading. In contrast, <strong>FileAlignment</strong> defines how section data is aligned inside the PE file on disk. Since the layout of a file on disk is different from its layout in memory, these two values help Windows map the file correctly and efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*vecxfkaAi6E8A0bxl29YVQ.png" /></figure><p>In the image, <strong>SectionAlignment</strong> is 0x1000 and <strong>FileAlignment</strong> is 0x200, which means the PE file follows two different alignment rules: one for memory and one for the file on disk. As we already covered in our past blog on <a href="https://medium.com/@0xnirsec/windows-memory-management-nir-5-5460da66aa72?sharedUserId=0xnirsec">memory management</a>, Windows works with fixed-size memory pages, and SectionAlignment = 0x1000 means that when the executable is loaded into memory, each section begins on a <strong>4 KB boundary</strong>. This is because 0x1000 in hexadecimal equals <strong>4096 bytes</strong>, and 4096 ÷ 1024 = 4 KB. This matches the standard Windows page size and is the layout used by the loader at runtime. On the other hand, FileAlignment = 0x200 means that section data inside the actual PE file is aligned on <strong>512-byte boundaries</strong>. Since 0x200 in decimal equals <strong>512</strong>, this defines how the sections are arranged on disk. In simple terms, <strong>SectionAlignment controls the in-memory layout</strong>, while <strong>FileAlignment controls the on-disk layout</strong>. This difference is completely normal and helps Windows map the PE file efficiently from disk into memory.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64">MajorOperatingSystemVersion &amp; MinorOperatingSystemVersion &amp; MajorImageVersion &amp; MinorImageVersion &amp; MajorSubsystemVersion &amp; MinorSubsystemVersion &amp; Win32VersionValue</a></p><p>The fields <strong>MajorOperatingSystemVersion</strong> and <strong>MinorOperatingSystemVersion</strong> specify the minimum version of the operating system required to run the PE file. They indicate the target Windows version in a simple major-and-minor format. Similarly, <strong>MajorImageVersion</strong> and <strong>MinorImageVersion</strong> represent the version number of the image itself, which can be useful for identifying the build or release version of the executable. The <strong>MajorSubsystemVersion</strong> and <strong>MinorSubsystemVersion</strong> fields define the required version of the subsystem, such as the Windows GUI or console environment, and help the loader understand the compatibility expectations of the binary. Finally, <strong>Win32VersionValue</strong> is a reserved field and must always be set to 0. In most cases, these fields are mainly informational and are useful during analysis, but they usually do not affect normal execution on modern Windows systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*nUnaaRkayKI-0Y8nptvsMg.png" /></figure><p>In this case, the <strong>Operating System Version</strong> is set to 6.0, corresponding to Windows Vista, which indicates that the executable is designed to run on, at minimum, a Vista-class environment. The <strong>Subsystem Version</strong> is likewise specified as 6.0, aligning the application with the same generation of Windows runtime behavior and ensuring consistency in how the loader initializes the program. In contrast, the <strong>Image Version</strong> is set to 0.0, which typically signifies that no explicit internal versioning has been defined by the developer. Overall, the OS and Subsystem version fields establish the minimum execution environment, while the Image Version remains largely informational and is frequently left unused. This configuration is standard and reflects a Vista-era compatibility target without explicit internal version metadata.</p><p><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>SizeOfImage &amp; SizeOfHeaders &amp; CheckSum &amp; Subsystem &amp; DllCharacteristics &amp; Stack/Heap &amp; LoaderFlags</strong></a></p><p>The <strong>SizeOfImage</strong> and <strong>SizeOfHeaders</strong> fields define the overall layout of the executable, where SizeOfImage represents the total memory footprint of the loaded PE, and SizeOfHeaders indicates how much space the headers occupy on disk. The <strong>CheckSum</strong> field is used for integrity verification, particularly in system-critical binaries, ensuring that the file has not been altered. The <strong>Subsystem</strong> field specifies the execution environment (such as GUI or console), while <strong>DllCharacteristics</strong> contains important security-related flags that control features like ASLR and DEP. Additionally, <strong>SizeOfStackReserve</strong> and <strong>SizeOfStackCommit</strong> determine how much memory is reserved and initially committed for the thread stack, whereas <strong>SizeOfHeapReserve</strong> and <strong>SizeOfHeapCommit</strong> perform the same role for the process heap. Finally, <strong>LoaderFlags</strong> is a reserved field that is typically set to zero and has no practical use in modern Windows systems. Collectively, these fields define how the PE file is loaded, secured, and executed in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*mVKki_EIfGCfa5mS6Y1kcg.png" /><figcaption><a href="https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64"><strong>SizeOfImage &amp; SizeOfHeaders &amp; CheckSum &amp; Subsystem &amp; DllCharacteristics &amp; Stack/Heap &amp; LoaderFlags</strong></a></figcaption></figure><p>In the image, <strong>SizeOfImage</strong> is 0x25000, which represents the total size of the executable when loaded into memory, including all sections and headers. The <strong>SizeOfHeaders</strong> is 0x400 (1024 bytes), indicating the space occupied by the PE headers on disk. The <strong>CheckSum</strong> is set to 0, which is common for non-system binaries and typically ignored by the Windows loader.</p><p>The <strong>Subsystem</strong> value is 3, which corresponds to a <strong>Windows Console application</strong>, meaning the program is designed to run in a command-line environment. The <strong>DllCharacteristics</strong> value is 0x8160, which includes a combination of security features such as <strong>ASLR</strong>, <strong>DEP</strong>, and other protection flags that enhance the safety of the executable.</p><p>For memory allocation, the <strong>SizeOfStackReserve</strong> is 0x100000 (1 MB), and the <strong>SizeOfStackCommit</strong> is 0x1000 (4 KB), meaning the program reserves 1 MB of stack space but initially commits only one memory page. Similarly, the <strong>SizeOfHeapReserve</strong> is 0x100000 (1 MB), and the <strong>SizeOfHeapCommit</strong> is 0x1000 (4 KB), defining the initial and reserved heap memory for the process. Finally, the <strong>LoaderFlags</strong> is 0, which is expected, as this field is reserved and not used in modern Windows systems.</p><p>Overall, these values are typical for a standard console application and reflect normal memory layout, allocation strategy, and security configuration used by modern PE files.</p><p>In this blog, we explored the NT Header in detail, which is one of the most critical components of the Portable Executable (PE) structure. We began by understanding its overall layout, including the Signature, File Header, and Optional Header, and saw how each part contributes to the loading and execution process of a program. We then focused on key fields inside the Optional Header, such as the entry point, image base, alignment values, versioning information, and memory configuration fields like stack and heap sizes.</p><p>Through both theoretical explanation and practical analysis using real values, we saw how these fields define the structure, behavior, and execution environment of a PE file. From memory alignment to subsystem identification and security-related flags, each field plays a role in how Windows loads and manages the executable in memory.</p><p>This blog was designed to build a strong and clear foundation. However, this is just the beginning. Advanced topics such as Data Directories, Import/Export Tables, Relocations, TLS, and deeper loader internals will further expand your understanding of how PE files work behind the scenes.</p><p>This knowledge becomes especially powerful when analyzing suspicious binaries, identifying obfuscation techniques, or developing low-level tools.</p><p><strong>Note:</strong> This content is intended for educational and defensive cybersecurity purposes only. Always use this knowledge ethically.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adbae96b7413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to DOS Header and DOS Stub (PE)- Nir(7)]]></title>
            <link>https://0xnirsec.medium.com/introduction-to-dos-header-and-dos-stub-pe-nir-7-f96cf73da7a8?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96cf73da7a8</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 16:46:24 GMT</pubDate>
            <atom:updated>2026-04-12T16:56:06.456Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Cybersecurity enthusiasts and white hat hackers!!</p><p>In our previous blog, we learned what a <strong>Portable Executable (PE)</strong> file is and why Windows still uses this format. But in today’s blog, we are going to explore the <strong>DOS Header</strong> and <strong>DOS Stub</strong> in detail.</p><p>When we break down the structure of a PE file, we find that both the DOS Header and DOS Stub are located at the <strong>top of the file</strong>. These are the very first components that the system encounters, as you can see in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*gQ1UoqleRek7zDVGe_aD_Q.png" /></figure><p>In this blog, we are going to take a practical approach. For that, we need a tool to analyze PE files. I will be using <strong>PE-bear</strong> to demonstrate and explore these structures step by step.</p><h3>What is DOS Header?</h3><p><strong>DOS Header</strong> is the first structure in a Windows executable file (.exe / .dll), originally designed for compatibility with <strong>MS-DOS (Disk Operating System)</strong>. In the early days, when Microsoft built MS-DOS, programs were meant to run in that environment. As Windows evolved, a more advanced format called the <strong>Portable Executable (PE)</strong> was introduced.</p><p>This PE structure helps the operating system and kernel understand what to execute, how to execute it, and how the file is organized internally. Even though modern systems are much more advanced, the DOS Header is still present for backward compatibility.</p><p>The DOS Header is <strong>64 bytes in size</strong> and is mainly used to:</p><ul><li>Identify the file as a valid executable using the <strong>“MZ” signature</strong></li><li>Store an offset (e_lfanew) that points to the actual PE Header</li></ul><p>The first <strong>64 bytes of the file</strong> represent the DOS Header. As shown in the image, the highlighted portion corresponds to these initial 64 bytes of the PE file (FILE.exe).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*2ppFamuzxWiQcD1HeuNKxg.png" /></figure><h3>What Does This 64 Bytes Contain?</h3><p>Now the question is: <strong>what exactly is stored inside these 64 bytes, and why?</strong></p><p>Below is the actual structure that defines what the DOS Header can hold. This structure comes from the <strong>Portable Executable (PE)</strong> format and shows all the fields present inside those 64 bytes:</p><pre>typedef struct _IMAGE_DOS_HEADER {      // DOS .EXE header<br>    WORD   e_magic;                     // Magic number<br>    WORD   e_cblp;                      // Bytes on last page of file<br>    WORD   e_cp;                        // Pages in file<br>    WORD   e_crlc;                      // Relocations<br>    WORD   e_cparhdr;                   // Size of header in paragraphs<br>    WORD   e_minalloc;                  // Minimum extra paragraphs needed<br>    WORD   e_maxalloc;                  // Maximum extra paragraphs needed<br>    WORD   e_ss;                        // Initial (relative) SS value<br>    WORD   e_sp;                        // Initial SP value<br>    WORD   e_csum;                      // Checksum<br>    WORD   e_ip;                        // Initial IP value<br>    WORD   e_cs;                        // Initial (relative) CS value<br>    WORD   e_lfarlc;                    // File address of relocation table<br>    WORD   e_ovno;                      // Overlay number<br>    WORD   e_res[4];                    // Reserved words<br>    WORD   e_oemid;                     // OEM identifier (for e_oeminfo)<br>    WORD   e_oeminfo;                   // OEM information; e_oemid specific<br>    WORD   e_res2[10];                  // Reserved words<br>    LONG   e_lfanew;                    // File address of new exe header<br>  } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;</pre><p>These are the actual values that fill the <strong>64-byte DOS Header space</strong>. Most of these fields were originally used by <strong>MS-DOS</strong> for execution and memory management.</p><p>However, in modern Windows systems, <strong>almost all of these fields are ignored</strong> because Windows does not execute programs in DOS mode anymore.</p><p>For us, from a cybersecurity and PE analysis perspective, only <strong>two fields are important to understand</strong>:</p><ul><li>e_magic → Identifies the file as a valid executable (MZ signature)</li><li>e_lfanew → Points to the actual PE Header (entry to real execution)</li></ul><p>Don’t worry about memorizing all fields right now. Focus only on the important ones — the rest are mainly <strong>legacy fields kept for compatibility</strong>.</p><h3>What is e_magic?</h3><p>e_magic is a field inside the DOS Header that stores a <strong>magic number</strong>, which is used by Windows to identify the file type. Just like we humans use file extensions (like .exe, .txt) to understand what kind of file it is, the operating system uses these magic numbers internally to recognize and validate files.</p><p>In simple terms:<br> e_magic tells the system, <strong>“What type of file is this?”</strong> before execution begins.</p><p>This field is placed at the very <strong>beginning of the file</strong>, because the system needs to quickly verify whether the file is valid or not. For executable files, the value of e_magic is <strong>&quot;MZ&quot;</strong>.</p><p>So when Windows starts processing a file:</p><ul><li>If the signature is <strong>“MZ”</strong> → It understands that this is a valid executable file</li><li>If the signature does not match → The file is considered invalid and execution will fail</li></ul><p>This is the <strong>first checkpoint</strong> in the execution process of a PE file.</p><p>Now let’s verify the e_magic field practically using <strong>PE-bear</strong>.</p><p>As you can see in the image, at the <strong>offset</strong> 0x00 <strong>(very beginning of the file)</strong>, the first two values are:</p><ul><li>4D</li><li>5A</li></ul><p>These two values together make <strong>2 bytes</strong>, which represent the e_magic field.</p><p>Now, when we convert this <strong>hex value (</strong>4D5A<strong>) into text</strong>, it becomes:<br> &quot;MZ&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7oyi_l1CUMimKb6D-vsuQA.png" /></figure><p>This confirms that the file is a <strong>valid executable</strong>, because Windows expects the e_magic <strong>signature to be &quot;MZ&quot;</strong>.</p><p>Even though PE-bear already shows this conversion, I used an online tool to convert 4D5A into text just to <strong>cross-check and demonstrate</strong> how this signature works internally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*dVdhGKIGuo7HjLFwqQ_ozQ.png" /></figure><p>This is a very important concept:</p><ul><li>Hex view → 4D 5A</li><li>Text view → MZ</li></ul><p>This is how Windows quickly verifies that the file is an executable before moving further in the PE structure.</p><h3>What Happens If We Change e_magic?</h3><p>Now, what if we change this signature and try to verify whether the program will still work or not?</p><p>To perform this, we will use <strong>PE-bear</strong>. Using this tool, we can edit the <strong>magic number (</strong>e_magic<strong>)</strong> of the executable file and then try to run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*LxuAvN9cGh_jMBZXpB-LFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*wptLDv00yldfcfa69Xlo4A.png" /></figure><p>As you can see, I created a new file named <strong>CH-Signature(FILE).exe</strong>, where the e_magic value of the executable is modified (incorrect).</p><p>When we try to run this program with the wrong signature, it throws an error. Let’s understand why:</p><p>Windows checks the <strong>magic number</strong> at the very beginning of the file. Since the signature does not match <strong>“MZ”</strong>, Windows cannot recognize it as a valid executable file.</p><p>As a result, when we try to run it, we get an error like:<br> <strong>“This app can’t run on your PC”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*5QumucQgOLzNwTvdQwI72g.png" /></figure><p>As we already know, the correct e_magic value is <strong>&quot;MZ&quot;</strong>. If this value is changed, the program will not execute because Windows fails to validate the file.</p><p>This shows how important the e_magic <strong>field</strong> is for program execution. In the same way, other members of the PE structure are also important, as each one plays a role in proper execution.</p><h3>What is e_lfanew?</h3><p>As we know, the first important member in the DOS Header is e_magic, and the <strong>last member is </strong><strong>e_lfanew</strong>. This field is <strong>4 bytes in size</strong> and is used to locate the next important header in the PE structure.</p><p>In simple terms:<br> e_lfanew stores the <strong>offset (location)</strong> of the next header in the file.</p><p>Just like the DOS Header uses e_magic to verify the file signature, the PE file contains multiple headers such as:</p><ul><li>NT Headers</li><li>Rich Header</li><li>Optional Header</li><li>Section Headers</li></ul><p>Execution works in a proper flow. After verifying the <strong>magic number (</strong><strong>e_magic)</strong> and processing the DOS Header, the system needs to move to the next stage, which is the <strong>Portable Executable NT Header</strong>.</p><p>But to move there, the system must know the exact location of that header. This is where e_lfanew comes into play.</p><p>It tells the system:<br> <strong>“Jump to this offset to continue execution.”</strong></p><p>For example, as shown in the image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpC7fZ8QiA4D90IlBXo84g.png" /></figure><ul><li>If e_lfanew = 0xF0</li><li>Then the system will move to offset <strong>0xF0</strong></li><li>And at that location, it will find the <strong>NT Header</strong></li></ul><p>So, e_lfanew acts like a <strong>pointer or navigation guide</strong> that directs the system to the next important part of the PE file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*0g039jb2yV7ibdkSirCp5A.png" /></figure><p>Now you might have a question — where does the DOS Stub fit in this execution flow?</p><p>The <strong>DOS Stub</strong> is a small program inside the executable that simply prints an error message. It was introduced for compatibility with <strong>MS-DOS</strong>. In earlier days, executables were designed for MS-DOS, and the DOS Header structure comes from that environment. Later, Windows introduced the modern <strong>Portable Executable (PE)</strong> format, but it still kept the DOS structure for compatibility.</p><p>Now assume you have a modern PE file and you try to run it on an MS-DOS system. The DOS system will successfully read the DOS Header because it understands that format, but after that, it cannot understand the modern PE structure. This would normally cause the program to crash.</p><p>To prevent this, the DOS Stub is included. When a modern PE file is executed in a DOS environment, the system runs the code inside the DOS Stub, which simply prints: <strong>“This program cannot be run in DOS mode.”</strong> and then exits safely. This avoids crashes and provides a proper message to the user.</p><p>In modern Windows systems, the DOS Stub is completely ignored, but it is still kept for backward compatibility. Additionally, from a security perspective, this area can sometimes be abused to store hidden or malicious data (like encrypted content or shellcode), since it is not used during normal execution.</p><h3>Understanding e_lfanew Practically</h3><p>Now let’s continue with our e_lfanew example.</p><p>As we already learned, e_lfanew stores the <strong>address (offset) of the NT Header</strong> inside the PE file. This is very important because it tells the system where to move next after processing the DOS Header.</p><p>As shown in the image, at <strong>offset</strong> 0x3C, we can find the value of e_lfanew. In this case, the value is F0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*9dTCz4goJrLKUt1VU_xCvA.png" /></figure><p>This means:</p><ul><li>The NT Header is located at offset <strong>0xF0</strong></li><li>If we navigate to this offset in the file, we will find the <strong>NT Header</strong></li></ul><p>And as you can see in the next image, when we jump to offset <strong>0xF0</strong>, we get the <strong>PE signature (</strong>50 45 00 00 <strong>→ &quot;PE&quot;)</strong>, which confirms that we have successfully reached the NT Header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTL_gYkTAApXOAt0sVyNMA.png" /></figure><p>This clearly shows how e_lfanew acts as a <strong>pointer</strong>, guiding the system from the DOS Header to the actual PE structure where execution continues.</p><p>This image represents the <strong>complete execution flow of a PE file</strong>, combining everything we have learned so far. It clearly shows how both <strong>old MS-DOS logic</strong> and <strong>modern Windows PE loading</strong> coexist in a single executable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*3fdo6EMO4UbS6g-ZmRo2Uw.png" /></figure><p>I hope you found this introduction to the <strong>PE structure, DOS Header, and DOS Stub</strong> helpful. The goal of this blog was to give you a clear understanding of how a Windows executable starts, how it is validated using e_magic, and how the execution flow moves forward using e_lfanew.</p><p>If you are new to this topic, don’t worry if some parts feel confusing at first. With practice and more exposure to PE analysis tools, these concepts will become much clearer and more intuitive.</p><p>In the upcoming blogs, we will move deeper into the <strong>Portable Executable (PE)</strong> structure and explore advanced topics such as NT Headers, memory layout, and how executables are actually loaded and executed in Windows.</p><p><strong>Note:</strong> This content is created for learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96cf73da7a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Portable Executable — NIR(6)]]></title>
            <link>https://0xnirsec.medium.com/introduction-to-portable-executable-nir-6-4187050a7111?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4187050a7111</guid>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 16:17:51 GMT</pubDate>
            <atom:updated>2026-04-05T16:17:51.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Cybersecurity ethusiasts and white hat hackers !!</p><h4>What is PE (Portable Executable) ?</h4><p>&gt; PE is the standard file format that Windows uses to run programs. Using this format, Windows runs our program. There are different types of PE files like executables (.exe), dynamic-link libraries (.dll), kernel modules (.sys), control panel applications (.cpl), and many others — all of these are PE files.</p><p>A PE file is a data structure that holds the information needed by the loader to load our application into memory and execute it.</p><p>To build malware, this is one of the most important things to understand. This knowledge will help you a lot in understanding malware concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*47ftxBpyHa1PfL9LgZRacg.png" /><figcaption>Structure of PE</figcaption></figure><p>The above represents the structure of a PE file. This might look confusing at first — what all these things are — but believe me, these are some of the most interesting concepts I’ve learned in my malware development journey.</p><p>I’ve decided to share in-depth knowledge — what I know and what I’ve managed to learn — and present it to you in an interesting way. This is a vast topic, so I’m going to explain it in parts, with each blog covering one or more sections in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sQP1HKxD6Tq4MC2o3RhOGg.png" /></figure><h4>Why PE Exists</h4><p>So, why does PE exist in our system?</p><p>Windows needs a standard format to run any program, and along with that, Windows also requires a proper structure to properly load the program into memory and execute it.</p><p>Without a standard format like PE, Windows would not know:</p><ul><li>Where the code starts (entry point)</li><li>What libraries (DLLs) are required</li><li>How memory should be allocated</li><li>Which parts are code, data, or resources</li></ul><p>The PE format solves this problem by providing a <strong>well-defined structure</strong> that the Windows loader can understand. It acts like a <strong>map or blueprint</strong> that tells the OS exactly how to handle the file.</p><h4>What Happens When we Run a Program</h4><p>&gt;When you run a program, Windows does not just execute it directly — it first reads the PE structure, loads the required sections into memory, resolves dependencies, and then transfers control to the entry point.</p><p>So execution is not direct — it follows a proper structured process.</p><p>This is exactly why understanding PE is so important in malware development — because every executable you analyze, modify, or create follows this format.</p><h4>Where PE Actually Starts (MS-DOS)</h4><p>&gt;To understand PE properly, we need to go back to the time of MS-DOS.</p><p>Before Windows, systems were running on MS-DOS, and executables were simple and directly executed.</p><p>When Windows came, it needed a more advanced format to support modern features like memory management and dynamic linking, but it also wanted to maintain compatibility with older systems.</p><p>That’s why PE still contains a part of MS-DOS inside it.</p><p>Every PE file starts with a DOS Header, and the first two bytes are:</p><blockquote><strong>MZ</strong></blockquote><p>This is the DOS signature. Even today, every .exe file begins with this.</p><p>&gt;This is exactly why understanding PE is so important in malware development — because every executable you analyze, modify, or create follows this format.</p><p>Once you understand PE deeply, you stop seeing an .exe as just a file. You start seeing how things are structured, how execution happens, and how malware hides, injects, and executes its payload inside this structure.</p><p>&gt;This blog was just a build-up — a starting point to give you a rough idea about the PE file and how things are structured.</p><p>You don’t need to understand everything perfectly right now. The goal here was just to explore and get familiar with the concept.</p><p>From the next blogs, we will go much deeper into each part of the PE structure and understand things in detail.</p><p><strong>Note: </strong>Made for <strong>learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</strong></p><p><em>— Nirvana</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4187050a7111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Memory Management — NIR(5)]]></title>
            <link>https://0xnirsec.medium.com/windows-memory-management-nir-5-5460da66aa72?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5460da66aa72</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 12:21:52 GMT</pubDate>
            <atom:updated>2026-03-29T12:21:52.474Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, white-hat hackers and cybersecurity enthusiasts!</p><p>In today’s blog, we’re going to explore <strong>Windows Memory Management</strong>.<br>We’ve already learned <em>how to allocate memory in Windows</em>, but now we’ll go deeper and understand the <strong>logic behind how Windows actually manages memory internally</strong>.</p><h3>Problems with Memory ?</h3><p>&gt;In any computer system, RAM (Random Access Memory) is a limited resource, but modern applications require a large amount of memory to run efficiently. Applications like games, browsers, and development tools can easily consume gigabytes of memory, which creates a problem when the total memory required exceeds the available physical RAM.</p><p>For example, if your system has 4 GB of RAM and you try to run multiple applications at the same time, the total memory demand can go beyond 4 GB. In a simple system without any memory management technique, this situation would cause programs to crash or prevent new applications from running.</p><p>This creates a fundamental challenge for the operating system: how to efficiently manage limited physical memory while still allowing multiple processes to run smoothly and independently. To solve this problem, operating systems use a concept called <strong><em>Virtual Memory</em></strong>, which allows better utilization of available resources and ensures system stability even under high memory demand.</p><h3>What is Virtual Memory ?</h3><p><strong>Virtual Memory </strong>is a memory management technique used by the operating system to give each process the illusion that it has a large, continuous block of memory, even though the actual physical RAM is limited. Instead of directly giving RAM to a process, the OS provides a virtual address space, which the process uses as if it were real memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*GCQ4u5uBV6a_TN4Hs16t8A.png" /></figure><p>When a process like <em>notepad.exe</em> starts, the operating system does not directly assign physical RAM to it. Instead, it provides a <strong>virtual address space</strong>, which acts as a private memory region where the process performs its tasks. This virtual memory is isolated, meaning each process believes it has its own continuous block of memory, even though the actual physical memory is shared among all processes.</p><p>In the above diagram, you can see that <strong>Process A</strong> starts with its own separate virtual memory. This means that the memory assigned to it is exclusively for that process, and no other process can directly access or interact with it.</p><h4>Advantage of Virtual Memory</h4><p>Let’s understand this with a real example. Assume you have a system with a <strong>64-bit architecture</strong> and<strong> 4 GB of RAM</strong>. Now you start running multiple applications at the same time.</p><p>For example:</p><ul><li>A game like GTA uses around <strong>3 GB</strong></li><li>A browser like Chrome uses around <strong>300 MB</strong></li><li>A music player uses around <strong>1 GB</strong></li></ul><p>Now, the total memory requirement becomes:</p><ul><li>3 GB + 0.3 GB + 1 GB = <strong>4.3 GB</strong></li></ul><p>This exceeds the available <strong>4 GB RAM</strong>. Ideally, this situation should cause the system to crash or stop running new applications because the required memory is greater than the physical limit.</p><p>However, due to the concept of <strong>virtual memory</strong>, the system is still able to run all these applications. The operating system manages memory efficiently by moving some data to disk when needed.</p><p>Although the system continues to work, it may experience <strong>lag or slower performance</strong>, because accessing data from disk is much slower than accessing it from RAM.</p><h3>Introduction to Paging</h3><p>Now assume you have a basic understanding of virtual memory. The next concept is <strong>Paging</strong>, which makes this system actually work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*UaGYdGmDFLpEXGSs.jpg" /></figure><p>As discussed, virtual memory can be very large, and we can still run multiple applications without crashing. This is possible because of paging.</p><p>Paging divides virtual memory into <strong>small fixed-size blocks called pages</strong>. In most systems, the page size is <strong>4 KB</strong>. This means virtual memory is not managed as one large continuous block, but as many small manageable units.</p><p>In the above diagram, <strong>Process A</strong> has its own isolated virtual memory space. Inside that memory, the small boxes you see represent <strong>pages</strong>. These pages are the <strong>building blocks of virtual memory</strong>.</p><p>The total number of pages depends on how much virtual memory a process requires. So, the larger the virtual memory allocated to a process, the greater the number of pages it will contain.</p><h4>Let’s Take an Example</h4><p>If a process uses <strong>1 GB of virtual memory</strong>, then it is internally divided into pages as follows:</p><ul><li>Total Memory = <strong>1,048,576 KB (1GB)</strong></li><li>Page Size = <strong>4 KB</strong></li></ul><p>Number of Pages = Total Memory / Page Size</p><pre>Pages = 1,048,576 / 4 = 262,144 pages</pre><p>So, <strong>1 GB of virtual memory consists of 262,144 pages</strong>.</p><p>When a process is running, it does <strong>not use all its pages at once</strong>. Only some parts of the program are active at any given time, while the rest remain unused temporarily.</p><p>For example, if you are using Chrome with <strong>10 tabs open</strong>, you are not interacting with all 10 tabs simultaneously. Usually, you work with only <strong>2–4 tabs at a time</strong>, and the remaining tabs stay inactive.</p><p>In this situation:</p><ul><li>Active tabs → their pages stay in <strong>RAM</strong></li><li>Inactive tabs → their pages are moved to <strong>Disk (secondary storage)</strong></li></ul><p>This process of moving pages between RAM and disk is called <strong>Paging (or swapping)</strong>.</p><p>When you switch to a tab that was previously inactive:</p><ul><li>The OS <strong>brings its pages back from disk to RAM</strong></li><li>At the same time, some currently inactive pages are <strong>moved from RAM to disk</strong></li></ul><p>This continuous movement ensures that only the required data stays in RAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*UaGYdGmDFLpEXGSs.jpg" /></figure><p>In the diagram, both <strong>Process A and Process B</strong> have their own virtual memory spaces, each divided into pages (1, 2, 3, 4, 5, 6). These pages are mapped to the <strong>physical memory (RAM)</strong>, but not necessarily in a sequential or ordered manner. Some of these pages are currently present in RAM, while others are stored in the <strong>disk (swap space)</strong> because they are not actively being used. This mapping also shows that pages are placed <strong>non-contiguously in RAM</strong>, meaning they can be scattered across different locations in physical memory. Additionally, some pages are completely absent from RAM and reside on disk until they are needed. The operating system dynamically decides which pages should remain in RAM and which should be moved to disk based on usage. This clearly demonstrates how paging enables <strong>efficient memory management</strong> by ensuring that only the necessary data is kept in fast-access memory.</p><h3><strong>What is Frame (Physical Memory) ?</strong></h3><p>Just like virtual memory is divided into <strong>pages</strong>, the physical memory (RAM) is also divided into fixed-size blocks called <strong>frames</strong>. A frame is simply a chunk of RAM that can hold exactly one page. This means <strong>page size = frame size</strong>, which is typically <strong>4 KB</strong>.</p><p>When the operating system loads a process into memory, it does not load the entire process at once. Instead, it takes individual <strong>pages from virtual memory</strong> and places them into available <strong>frames in RAM</strong>. Each frame can store one page, and these frames can exist anywhere in physical memory.</p><p>For example, if your system has <strong>4 GB of RAM</strong> and each frame is <strong>4 KB</strong>, then:</p><ul><li>4 GB = 4,294,967,296 bytes</li><li>Total frames = <strong>4,294,967,296 / 4096 = 1,048,576 frames</strong></li></ul><p>So, RAM is divided into <strong>1,048,576 frames</strong>, and the OS dynamically uses these frames to store pages from different processes.</p><p>The important point here is that frames do <strong>not need to be continuous</strong>. The OS can place pages of a process into <strong>any available frame</strong> in RAM. This makes memory management highly flexible and avoids fragmentation issues.</p><blockquote><strong>Page = Virtual memory unit</strong><br> <strong>Frame = Physical memory unit</strong></blockquote><h3>Page ↔ Frame Mapping</h3><p>Now comes the most important part — how <strong>virtual pages</strong> are connected to actual <strong>physical frames in RAM</strong>.</p><p>This mapping is handled by a structure called the <strong>Page Table</strong>, which is maintained by the operating system for each process.</p><p>Whenever a process generates a memory request, it uses a <strong>virtual address</strong>. This virtual address is divided into two parts:</p><ul><li><strong>Page Number</strong> → identifies which page</li><li><strong>Offset</strong> → exact location inside that page</li></ul><p>The OS uses the page number to look into the <strong>page table</strong> and find the corresponding <strong>frame number</strong> in RAM. Then it combines the frame number with the offset to get the final physical address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*Tb7pNud984jSb-N5.jpg" /></figure><p>In the diagram, you can see how <strong>virtual memory, page table (memory map), physical memory, and disk</strong> are connected.</p><p>On the left side, we have <strong>virtual memory</strong>, which is divided into multiple pages (page 0, page 1, page 2 … page v). These pages represent the logical view of memory from the process perspective.</p><p>In the middle, there is a <strong>memory map (page table)</strong>. This acts as a bridge between virtual memory and physical memory. It stores information about <strong>which page is located in which frame</strong>.</p><p>Next, we have <strong>physical memory (RAM)</strong>, which is divided into frames. Some pages from virtual memory are currently loaded into these frames.</p><p>On the right side, we have the <strong>disk</strong>, where pages are stored when they are not currently needed in RAM.</p><h3>Practical</h3><p>Now we read this all but now lets find this on our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*zQfOkpwbP7-sWb_1ZJSYCQ.png" /></figure><p>Here, we have a running process, and as you can see, these are the memory regions assigned to it by the operating system. Each entry represents a portion of the process’s virtual memory, managed and organized internally by the OS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*ni8OsIveWDHuY7RzOU8M7g.png" /></figure><p>In the above screenshot, we can see the detailed memory statistics of a process in Process Hacker. One important value here is the <strong>Virtual Size</strong>, which shows the total virtual memory allocated to the process (around <strong>4.05 GB</strong>). However, if we compare this with the <strong>Working Set</strong> (around <strong>2.16 MB</strong>), we can clearly see that only a very small portion of this memory is actually present in RAM.</p><p>This difference proves that the process is not using physical memory directly but is instead operating in a <strong>virtual address space</strong>. The operating system only keeps active data in RAM and manages the rest through paging. Additionally, values like <strong>Page Faults</strong> indicate how often memory had to be loaded into RAM from disk, further confirming that paging is actively happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*OUUwOqelfzdPzdfBCj1GSg.png" /></figure><p>In the above screenshot from VMMap, we can see a detailed breakdown of how a process (brave.exe) uses memory. This tool provides a much deeper view compared to Task Manager or Process Hacker.</p><p>The <strong>Committed</strong> memory represents the total virtual memory allocated to the process, which can be considered as the total number of pages reserved by the process. The <strong>Working Set (WS)</strong> shows the portion of memory that is currently active and loaded in RAM. This means these are the <strong>active pages</strong> that the process is actively using.</p><p>The difference between committed memory and the working set represents the <strong>inactive pages</strong>, which are not currently in RAM and may be stored on disk. Additionally, VMMap categorizes memory into sections like <strong>Image, Heap, Stack, and Private Data</strong>, showing how different types of memory are managed internally.</p><p>This clearly demonstrates that a process may allocate a large number of pages, but only a small portion of them are actually active in RAM at any given time, while the rest are managed by the operating system through paging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*TkotjTyLClO1gXYTlM7yLw.png" /></figure><p>we can reliably obtain the page size using [System.Environment]::SystemPageSize, which returns the actual memory page size used by the system. In most cases, this value is <strong>4096 bytes (4 KB)</strong>, confirming that memory is divided into fixed-size pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*8-83lbasbd9Y5WxbT_plWQ.png" /></figure><p>In the above screenshot from <strong>Windows Resource Monitor</strong>, we can observe how memory is managed in real time. The <strong>Hard Faults/sec</strong> column represents how often a process needs to load data from disk into RAM. A hard fault occurs when a required page is not present in physical memory and must be fetched from disk, which is a clear indication of paging.</p><p>We can also see values like <strong>Commit</strong>, which represents the total virtual memory allocated, and <strong>Working Set</strong>, which shows the actual memory currently present in RAM. Additionally, the physical memory section displays how memory is divided into <strong>In Use, Standby, and Free</strong>, showing how the OS dynamically manages memory.</p><p>This provides strong practical evidence that virtual memory and paging are continuously working behind the scenes to efficiently manage system memory.</p><p>In this blog, we explored how modern operating systems manage memory, starting from the limitation of RAM to the concept of virtual memory, which gives each process the illusion of a large, continuous space. We then saw how paging breaks memory into fixed-size pages, how only active pages stay in RAM while others move to disk, and how frames and page tables work together to map virtual addresses to physical memory.</p><p>These concepts form the foundation of memory management. However, this is just the beginning — advanced topics like TLB, multi-level paging, page table entries, and page replacement algorithms go even deeper, along with Windows-specific implementations. This blog was focused on building a clear and practical base so you can confidently move toward those advanced concepts.</p><h3>Importance of Memory Management</h3><p>Memory management is a core concept in operating systems. By understanding virtual memory, paging, and mapping, you now know how processes actually use memory behind the scenes.</p><p>This knowledge is important for advanced topics like buffer overflows, process injection, and memory-based attacks.</p><p><strong>Note</strong>: Made for learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</p><p>— Nirvana</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5460da66aa72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Architecture: How Windows Executes API Calls — NIR(4)]]></title>
            <link>https://0xnirsec.medium.com/windows-architecture-how-windows-executes-api-calls-nir-4-ced348909335?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced348909335</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[malware-development]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 06:08:43 GMT</pubDate>
            <atom:updated>2026-03-24T06:08:43.808Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, white hat hackers and cybersecurity enthusiasts!</p><p>Today, we are going to explore <strong>Windows Architecture in more depth</strong>. In my previous blog, I explained the concepts of <strong>User Mode and Kernel Mode</strong>. In this blog, we will understand how the <strong>actual flow of execution happens from user mode to kernel mode</strong>.</p><p>As we know, a user-mode process cannot directly interact with hardware or perform privileged operations. To execute such tasks, it must <strong>request the kernel through Windows APIs</strong>.</p><p>The diagram below represents a <strong>high-level flow of how a request moves from user mode to kernel mode</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0VOkbnvTPlqSrY_s7GwWQ.png" /><figcaption><strong>Figure 1:</strong> High-level Windows architecture flow</figcaption></figure><h4>1. User Processes</h4><p>&gt; This refers to the processes running on our system, such as <strong>notepad.exe, Google Chrome, or YouTube (browser process)</strong>.Now assume our Notepad process wants to create a file. For that, it needs to send a request to the kernel. But in reality, it is <strong>not that simple to directly reach the kernel</strong>.</p><p>So, to create a file, the request from the user process first goes to <strong>Subsystem DLLs</strong>.</p><h4>2. Subsystem DLLs</h4><p>&gt; Subsystem DLLs are system libraries that are already present in Windows and provide functions (APIs) to perform tasks. There are many DLL files in the system, and each one is responsible for specific functionalities. For now, just remember:<br><strong>DLLs contain functions that help applications perform tasks.</strong></p><p>Like for example kernel32.dll (located at C:\Windows\System32). This DLL contains a function called <strong>CreateFile</strong>.<br>So, when our user process wants to create a file, it calls the <strong>CreateFile function from kernel32.dll</strong> instead of directly interacting with the kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*cL_ia5icD5e7X4v0tyMu3g.png" /></figure><h4>3. NTDLL.DLL</h4><p>&gt; This is another DLL, but it is <strong>special and very important</strong> compared to others. This is the <strong>last user-mode DLL</strong> that gets involved before execution moves to the kernel. Even though multiple DLLs may be used during execution, the flow eventually reaches <strong>ntdll.dll</strong>. Why?</p><p>Because it contains:</p><ul><li><strong>Native API (NTAPI)</strong> functions</li><li><strong>System call (syscall) stubs</strong></li></ul><p>These syscalls are responsible for <strong>communicating with the kernel and requesting it to perform specific tasks</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*YN0DXhDoR4ndAIxrLHY0RA.png" /></figure><h4>Function Call Flow</h4><p>Let’s understand the flow with a simple example. Suppose we are creating a file using Notepad. Notepad is a user process, so it cannot directly communicate with the kernel. Instead, it calls a suitable API from a DLL, such as <strong>CreateFile</strong> in <strong>kernel32.dll</strong>. However, in modern Windows, kernel32.dll mostly acts as a forwarding layer and does not perform the actual work. It forwards the request to <strong>kernelbase.dll</strong>, where the real implementation of the function exists.</p><p>From kernelbase.dll, the execution eventually reaches <strong>ntdll.dll</strong>, which contains the low-level function <strong>NtCreateFile</strong>. This function is responsible for preparing and issuing a <strong>system call (syscall)</strong>. The syscall then transfers execution from <strong>user mode to kernel mode</strong>, where the Windows kernel performs the actual task of creating the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coy5TwgPaeW_lKYKr_Zc-Q.png" /><figcaption><strong>Figure 2:</strong> API execution flow diagram</figcaption></figure><h3>Important Note on the Flow</h3><p>It is important to understand that this diagram represents a <strong>simplified and common execution flow</strong>, not a fixed or strict path. In real-world scenarios, there may be <strong>multiple DLLs involved</strong> during execution, and the flow can vary depending on the API, Windows version, and internal implementation.</p><p>For example, in modern Windows systems, <strong>kernel32.dll often forwards requests to kernelbase.dll</strong>, and additional internal functions may be called before reaching <strong>ntdll.dll</strong>. However, regardless of these variations, the execution flow will <strong>eventually reach ntdll.dll</strong>, where a system call is generated to transition from <strong>user mode to kernel mode</strong>.</p><p>Note: CreateFile is a macro that maps to CreateFileW (Unicode version), so both are functionally the same—the difference is only in string encoding.</p><h3>Practical Demonstration</h3><p>Let’s perform this practically.</p><ol><li>User Process (File.exe)</li></ol><p>&gt; In this example, our <strong>user process is </strong><strong>FILE.exe</strong>.<br>I created this simple program to make the internal flow easier to understand. Although we could use applications like Notepad, they introduce unnecessary complexity.</p><p>When we run this program, it creates a file named <strong>test.txt</strong>.<br>So, this executable acts as our <strong>user application (user-mode process)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*AWoVqxzYOGejHnddbhrViw.png" /></figure><p>2. Loaded DLLs in the Process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhlYsbSZjBa4suz4AMo2Qg.png" /></figure><p>After running the program, we inspect it using a tool like <strong>Process Explorer</strong>.</p><p>Here, we can clearly observe that the process has loaded multiple important DLLs:</p><ul><li>kernel32.dll</li><li>kernelbase.dll</li><li>ntdll.dll</li></ul><p>This confirms that:</p><ul><li>The execution does not involve just one DLL</li><li>Multiple layers are involved before reaching the kernel</li></ul><p>3. API Call from User Application</p><ul><li>When we debug the program, we can observe the following instruction:</li></ul><pre>call qword ptr ds:[&lt;&amp;CreateFileW&gt;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*MVt0wG1UFmnwD4Wqo9vRTQ.png" /></figure><p>This shows that:</p><ul><li>The application is calling <strong>CreateFileW</strong></li><li>The call is made through the <strong>Import Address Table (IAT)</strong></li><li>Arguments (like &quot;test.txt&quot;) are passed via registers</li></ul><p>4. Transition to kernelbase.dll</p><p>After this call, execution moves into <strong>kernel32.dll</strong>, which then forwards the request to <strong>kernelbase.dll</strong>.</p><p>Inside kernelbase.dll, the actual implementation of the API exists.<br>Here, multiple internal function calls are executed to prepare the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*wtPfGdDnVbDYZcNLKBKyCA.png" /></figure><p>5. Reaching ntdll.dll and Syscall</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQEPVOK1cxtoKaHul7SF9w.png" /></figure><p>Eventually, the execution reaches <strong>ntdll.dll</strong>, specifically the function:</p><ul><li><strong>NtCreateFile</strong></li></ul><blockquote><em>The syscall transfers execution to the Windows kernel (ntoskrnl.exe), where the actual operation is handled by kernel components and drivers.</em></blockquote><p>Final code here : <a href="https://github.com/NirvanaOn/Maldev-Medium/blob/main/Windows%20Architecture%3A%20How%20Windows%20Executes%20API%20Calls%E2%80%8A-%E2%80%8ANIR(4).cpp">NIR-CODE</a></p><h3>Final Execution Flow</h3><pre>FILE.exe (User Process)<br>   ↓<br>CreateFileW (IAT Call)<br>   ↓<br>kernel32.dll (Forwarding Layer)<br>   ↓<br>kernelbase.dll (Actual Implementation)<br>   ↓<br>ntdll.dll (NtCreateFile)<br>   ↓<br>syscall<br>   ↓<br>Windows Kernel (ntoskrnl.exe)</pre><h3>Importance of Understanding API Execution Flow</h3><p>Understanding how Windows executes API calls is a <strong>fundamental concept in cybersecurity and malware development</strong>. If you have followed this blog, you now know how a simple API call travels from <strong>user mode to kernel mode</strong>, passing through layers like kernel32.dll, kernelbase.dll, and ntdll.dll.</p><p>This knowledge will be extremely useful in advanced topics such as <strong>API hooking, EDR evasion, direct syscalls, and reverse engineering of malware behavior</strong>. It also helps in understanding how security tools monitor and intercept API calls.</p><p>I hope this blog gave you a <strong>clear and practical understanding of Windows API execution flow</strong>. In this blog, we explored how functions like CreateFile internally transition through multiple layers before reaching the kernel via a syscall.</p><h3>Task for You</h3><p>Try to debug another Windows API, such as:<br>WriteFile or ReadFile</p><p>Your task is to:</p><ul><li>Trace the complete flow</li><li>Identify the transition from kernel32 → kernelbase → ntdll</li><li>Locate the <strong>syscall instruction</strong></li></ul><p>Note : This content is shared <strong>for educational and defensive cybersecurity purposes only</strong>. Stay curious, stay ethical.</p><p><em>— Nirvana</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced348909335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Windows Architecture — NIR(3)]]></title>
            <link>https://0xnirsec.medium.com/windows-architecture-nir-3-16c5669510fd?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/16c5669510fd</guid>
            <category><![CDATA[windows-hacking]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 04:59:28 GMT</pubDate>
            <atom:updated>2026-03-22T04:59:28.407Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, cybersecurity enthusiasts and white hat hackers!!</p><p>In our previous blog, we learned how to create simple malware and how to allocate memory using different methods. However, I know that many things might still be confusing. Don’t worry — I’ll go deeper into these topics to bring more clarity and explain everything I know in a simple way.</p><p>First, if you want to become a malware developer or learn how to bypass antivirus and security mechanisms, you need to truly understand the fundamentals. Don’t rush — take your time and focus on deeply understanding how things actually work. For me, exploring how systems work internally is very exciting and full of curiosity. So, let’s start learning something amazing.</p><h3>Windows Architecture</h3><p>&gt; Have you ever wondered how Windows actually performs tasks?<br>For example, when you save a file, what really happens in the background?</p><p>To understand this, we first need to understand how Windows is designed internally.</p><p>Windows operates using <strong>two main execution modes</strong>:</p><ul><li><strong>User Mode</strong> → Where normal applications run <em>(Limited Access)</em></li><li><strong>Kernel Mode</strong> → Where core operating system functions run <em>(Full Access)</em></li></ul><h4>What is User Mode ?</h4><p>&gt;User Mode is the environment where all normal applications run, such as browsers, editors, or even malware. Whenever we open a program, it executes in User Mode. This environment is restricted and controlled to ensure system safety and stability. Programs running in User Mode have limited privileges (limited access), meaning they cannot directly access hardware or critical parts of the operating system.</p><p>Now, this raises an important question: if User Mode has limited access to hardware and the system core, then how are tasks actually performed on the system?</p><p>For example, when you create a file and write data into it, the file is successfully created and stored. So where does the concept of User Mode come into play here?</p><p>The key idea is that User Mode does not perform these operations by itself. Instead, it sends a request to the operating system. The actual work happens behind the scenes in Kernel Mode, which has full access to hardware and system resources.</p><p>Therefore, User Mode programs run with limited privileges and cannot perform critical system operations on their own — they always rely on Kernel Mode to execute them</p><h4>What is Kernel Mode ?</h4><p>&gt; Kernel Mode is the environment where the core components of the operating system run. It has full control over the system and is responsible for performing all critical operations.</p><p>Unlike User Mode, Kernel Mode is not restricted. Programs and components running in this mode have complete access to hardware, memory, and all system resources. This allows the operating system to manage tasks efficiently and maintain overall system functionality.</p><p>Now, connecting this with our previous example — when a User Mode application requests to create a file, that request is passed to Kernel Mode.</p><p>Before performing the task, the operating system may apply certain checks, such as validating permissions and ensuring the request is legitimate. Once everything is verified, Kernel Mode takes control and performs the actual operation.</p><p>For example, in the case of file creation:<br>Kernel Mode interacts directly with the file system and hardware (disk), allocates the required resources, and writes the data in a proper and structured way.</p><p>This is why Kernel Mode is considered the most powerful part of the operating system. It executes all critical tasks that User Mode programs are not allowed to perform directly.</p><p>Therefore, Kernel Mode acts as the executor of the system, handling all sensitive operations and ensuring that everything runs securely and efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*-svh836QU9vNqzslObnNTQ.png" /></figure><p>Let’s understand the flow again. As discussed earlier, when we are in User Mode, we cannot directly perform hardware-level operations.</p><p>For example, consider a user process like Notepad. If you try to create a file and save it to disk, the Notepad application (running in User Mode) cannot perform this task on its own. Instead, it sends a request to the operating system to handle it.</p><p>Now, between the User Mode application and the Kernel, there are multiple layers and components involved in this process. These act as a path through which the request travels. We will explore each of these components in detail in the next blog.</p><p>For now, focus on understanding the overall flow: once the request from the User Mode process reaches the Kernel, the Kernel performs the actual file creation operation. Since the Kernel has direct access to hardware, it writes the data to the disk and completes the task.</p><p>As a result, the file is successfully created and saved on your system.</p><h4>Why this modes exist ?</h4><p>Now, think about this: what if every process had direct access to hardware?</p><p>If that were the case, it would create serious problems. For example, malware would have a much easier time gaining full control over the system and accessing hardware directly. This would make the system highly vulnerable to attacks.</p><p>In addition, if a single process crashed while interacting with hardware, it could affect other processes or even crash the entire system. There would be no proper isolation or protection.</p><p>Another issue is complexity. If multiple processes tried to access the same hardware resource at the same time, it would become very difficult for the system to manage and coordinate everything efficiently.</p><p>This is why operating systems use two separate modes:</p><ul><li><strong>User Mode</strong> for running applications with limited access</li><li><strong>Kernel Mode</strong> for handling critical operations with full control</li></ul><p>This separation ensures <strong>security, stability, and proper resource management</strong> within the system.</p><p>I hope this blog gives you a clear understanding of Windows architecture and how User Mode and Kernel Mode work together behind the scenes. In this blog, we learned how applications run in a restricted environment and how the kernel performs critical operations on behalf of them.</p><p><strong>Task for you:</strong><br>Try to observe this flow in real life. When you open an application or save a file, think about how the request moves from User Mode to Kernel Mode. Try to relate this concept with different actions you perform on your system.</p><p><strong>Note:</strong> Made for learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</p><p><em>-Nirvana</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c5669510fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Allocation in Windows (Malware Perspective) — NIR(2)]]></title>
            <link>https://0xnirsec.medium.com/memory-allocation-in-windows-malware-perspective-nir-2-67dfb477313d?source=rss-f2838142e6d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/67dfb477313d</guid>
            <category><![CDATA[maldev]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[thecybernirvana]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[NIRVANA]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 08:32:54 GMT</pubDate>
            <atom:updated>2026-03-18T08:35:12.782Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, Cybersecurity enthusiasts and white hat hackers !</p><p>In today’s blog, we are going to learn how memory allocation works in Windows.<br>To get the most out of this blog, I recommend going through my previous <a href="https://thecybernirvana.medium.com/introduction-to-malware-development-nir-1-037ff50f3925">blog </a>first, where we performed local shellcode execution.</p><h4>What is Memory Allocation ?</h4><p>&gt; In Windows, when a program needs space to store data or execute code, it must request memory from the operating system.</p><p>But why do we need this memory?</p><p>If you remember from the previous blog, we used this concept during local shellcode execution. We had shellcode, but in order to run it, we needed to allocate space in memory where the CPU could execute it. This Line calc_memory = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);</p><p>In this blog, we will explore different methods used to allocate memory in Windows and understand their purpose and differences.</p><ul><li>HeapAlloc — allocates memory from the process heap</li><li>malloc — a C runtime wrapper over heap allocation</li><li>VirtualAlloc — allocates memory directly from the virtual address space with full control over permissions</li></ul><p>Each of these methods serves a different purpose, and understanding their differences is essential for both software development and malware analysis.</p><h3>What is HeapAlloc?</h3><p>Before understanding HeapAlloc, we first need to understand what a <strong>heap</strong> is.</p><blockquote><em>The heap is a memory area inside a process that is used to store dynamically allocated data (data allocated at runtime).</em></blockquote><p>When a program runs, it becomes a <strong>process</strong>, and Windows allocates memory to it so it can execute its tasks.</p><p>This memory is mainly divided into two important parts:</p><ul><li><strong>Stack</strong> → used for function calls, local variables, and temporary data</li><li><strong>Heap</strong> → used for memory that is manually allocated during runtime</li></ul><p>The key difference is:</p><ul><li>Stack memory is managed automatically by the system</li><li>Heap memory is <strong>managed by Windows internally</strong>, but it is <strong>used by the programmer when explicitly requested</strong>.</li></ul><p>When a program needs to allocate memory manually during execution, it can request that memory from the heap.</p><p>This is where HeapAlloc comes in.</p><p>HeapAlloc is a Windows API function that allows a program to allocate memory from the process heap.</p><p>Want to know more : <a href="https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc">Link</a></p><p>Now you know what is heap, So let’s write our first program using HeapAlloc</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br><br>int main() {<br>    char data[] = &quot;Hello Nirvana!&quot;;<br>    // Allocate 100 bytes<br>        PVOID pAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 100);<br>        printf(&quot;Allocated memory at: %p\n&quot;, pAddress);<br>    // Write data<br>        RtlMoveMemory(pAddress, data, sizeof(data));<br>    // Print what we wrote<br>        printf(&quot;Data in memory: %s\n&quot;, (char*)pAddress);<br>        return 0;<br>}</pre><p>In the above code, we used HeapAlloc to allocate memory in the current process heap.</p><pre>LPVOID HeapAlloc(<br> IN HANDLE hHeap,<br> IN DWORD dwFlags,<br> IN SIZE_T dwBytes<br> );</pre><pre>PVOID pAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 100);</pre><ul><li><strong>hHeap</strong> = Handle to the heap from which memory will be allocated. <br>In this program, we use <strong><em>GetProcessHeap()</em></strong> to get the default heap of the current process.</li><li><strong>dwFlags</strong> = Controls how memory is allocated. <br>In this program, we use <strong><em>HEAP_ZERO_MEMORY</em></strong>, which initializes the allocated memory with zeros.</li><li><strong>dwBytes </strong>= Specifies how much memory to allocate (in bytes). <br>In this example, we allocate <strong><em>100 bytes</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TF4TnX9F7c9lxhxyd7CFJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*RYglh_hnm8RDlpQgv65DAw.png" /></figure><p>Once we run this program, we get a pointer to the allocated heap memory. When we inspect this address, we can see the data stored in the heap.</p><p>This demonstrates how memory allocation using <strong>HeapAlloc</strong> works in C++.</p><p>Now that we understand <strong>HeapAlloc</strong>, let’s move on to understanding <strong>VirtualAlloc</strong>.</p><h4>What is VirtualAlloc?</h4><p>Before understanding <strong><em>VirtualAlloc</em></strong>, we first need to understand what <strong>virtual memory</strong> is.</p><p>&gt; Virtual memory is a memory management system used by Windows that provides each process with its own virtual address space.</p><p>Each process behaves as if it has its own isolated memory, even though the actual physical memory (RAM) is shared by the system.</p><p>Unlike heap memory, which is managed by the Windows heap manager, virtual memory provides more <strong><em>direct control</em></strong> over how memory is allocated and used.</p><ul><li><strong>Heap</strong> → managed memory (used for data)</li><li><strong>Virtual Memory</strong> → directly controlled memory (used for data + execution)</li></ul><p>When a program needs more control over memory — such as specifying allocation type or memory permissions — it can request memory directly from virtual memory.</p><p>This is where <strong>VirtualAlloc </strong>comes in.</p><p>Now that we understand the concept, let’s look at a program using VirtualAlloc.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br><br>int main() {<br><br>    char data[] = &quot;Hello Nirvana!&quot;;<br><br>    // Allocate 100 bytes using VirtualAlloc<br>    PVOID pAddress = VirtualAlloc(<br>        NULL,                // Let the system choose the address<br>        100,                 // Size in bytes<br>        MEM_COMMIT | MEM_RESERVE, // Reserve and commit memory<br>        PAGE_READWRITE       // Memory protection: read/write<br>    );<br><br>    if (pAddress == NULL) {<br>        printf(&quot;VirtualAlloc failed with error %lu\n&quot;, GetLastError());<br>        return 1;<br>    }<br><br>    printf(&quot;Allocated memory at: 0x%p\n&quot;, pAddress);<br><br>    // Copy data into allocated memory<br>    RtlMoveMemory(pAddress, data, sizeof(data));<br><br>    // Print what we wrote<br>    printf(&quot;Data in memory: %s\n&quot;, (char*)pAddress);<br><br>    return 0;<br>}</pre><pre>LPVOID VirtualAlloc(<br>  IN         LPVOID lpAddress,<br>  IN         SIZE_T dwSize,<br>  IN         DWORD  flAllocationType,<br>  IN         DWORD  flProtect<br>);</pre><pre>PVOID pAddress = VirtualAlloc(<br>    NULL,                // Let the system choose the address<br>    100,                 // Size in bytes<br>    MEM_COMMIT | MEM_RESERVE, // Reserve and commit memory<br>    PAGE_READWRITE       // Memory protection: read/write<br>);</pre><ul><li><strong>lpAddress</strong> = Starting address where memory should be allocated.<br>In our program we used NULL, which means Windows will automatically choose the address.</li><li><strong>dwSize</strong> = Size of memory to allocate (in bytes).<br>Here we allocated <strong>100 bytes</strong>.</li><li><strong>flAllocationType</strong> = Defines how memory is allocated.<br>In our program we used MEM_COMMIT | MEM_RESERVE, which means: MEM_RESERVE → reserves address space , MEM_COMMIT → actually allocates memory</li><li><strong>flProtect</strong> = Defines memory permissions.<br>In our program we used PAGE_READWRITE, which means: Memory can be <strong>read and written</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NmUJQDeq00JR4NRVy8Ph4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*uCmpf4ZuXLeYhebsAch-aw.png" /></figure><h3>Difference Between HeapAlloc and VirtualAlloc</h3><p>HeapAlloc is used to allocate memory from the process heap and is mainly used for storing data such as strings or buffers. This memory is managed by Windows and has <strong>read and write permissions</strong>, but it cannot be executed <strong>by default (no execute permission)</strong>. For example, if we allocate memory using HeapAlloc and store a string in it, we can read and modify the data, but we cannot run it as code.</p><p>On the other hand, VirtualAlloc allocates memory directly from the virtual address space and gives us more control over how that memory is used. We can specify memory permissions such as <strong>read, write, and execute</strong>, which makes it useful for advanced tasks like shellcode execution. For example, using VirtualAlloc, we can allocate memory, copy shellcode into it, and then execute it.</p><h3>What is malloc?</h3><p>malloc is a function used in C to allocate memory dynamically from the heap.</p><p>Unlike HeapAlloc, which is a Windows API, malloc is part of the C runtime library and works across different operating systems.</p><p>In simple terms, malloc allows a program to request memory during runtime to store data.</p><p>Example</p><pre>char* buffer = (char*)malloc(100);</pre><p>Final code here : <a href="https://github.com/NirvanaOn/Maldev-Medium/blob/main/Memory%20Allocation%20in%20Windows%20(Malware%20Perspective)%E2%80%8A-%E2%80%8ANIR(2).cpp">NIR-CODE</a></p><h3>Importance of Memory Allocation</h3><p>Memory allocation is a very important part of malware development. If you understood most of the concepts from this blog, it means you now know how to allocate memory, which will be useful for future concepts like Local/Remote Process Injection, Local/Remote Thread Injection, and many more.</p><p>I hope this blog gives you a clear understanding of memory allocation and some Windows basics. In this blog, we learned about <strong>HeapAlloc</strong>, <strong>VirtualAlloc</strong>, and <strong>malloc </strong>methods to allocate memory.</p><p><strong>Task for you</strong>: The explanation and code for <strong>malloc</strong> are missing. It’s your task to create a program that uses <strong>malloc</strong> to allocate memory, store data, and display it.</p><p><strong>Note</strong>: Made for learning and defensive cybersecurity purposes only. Stay curious, stay ethical.</p><p><em>— Nirvana</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67dfb477313d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>