<?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 Abhinav Thakur on Medium]]></title>
        <description><![CDATA[Stories by Abhinav Thakur on Medium]]></description>
        <link>https://medium.com/@compilepeace?source=rss-d9d941443ca6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ZhysMxiSlB7wtgd2pkCzAg.png</url>
            <title>Stories by Abhinav Thakur on Medium</title>
            <link>https://medium.com/@compilepeace?source=rss-d9d941443ca6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 00:03:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@compilepeace/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[Shellcoding 0x4: Packing Presents with Evil Santa]]></title>
            <link>https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85e81aa277a</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 17:49:51 GMT</pubDate>
            <atom:updated>2022-08-12T14:03:47.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mCxJ-pCvzr9vpZX12cajg.png" /></figure><blockquote>One’s reality might be another’s illusion — Itachi Uchiha</blockquote><p>The area of malware research has grown on both sides of offence and defence. Since the early age of Antivirus software till the advent of <a href="https://en.wikipedia.org/wiki/Endpoint_detection_and_response">EDR</a> solutions, detection &amp; evasion has been a continuous cat &amp; mouse chase. To adversaries — while delivering payload at the target endpoint, getting detected/flagged by statically applied filters or filesystem monitoring events (see <a href="https://man7.org/linux/man-pages/man7/fanotify.7.html">fanotify(2)</a>) would be the last thing an attacker wants. An adversary/malware operating solely in memory (volatile storage) has an implicit advantage maintaining minimum digital footprint for forensic/post-mortem analysis (assuming the execution doesn’t crash and core dumps are disabled on target platform). This article talks about the idea of crafting a <strong>packer</strong> (<strong>in-memory runtime decoder stub)</strong> which can be used to bypass <strong>heuristics </strong>as well as<strong> signature-based detection </strong>mechanisms<strong> </strong>while executing solely<strong> in-memory</strong>.<strong> </strong>Approach described here can effectively be applied to <strong>conceal certain sequence of bytes</strong> or <strong>eliminate bad characters</strong> from the payload.</p><p>Even though the article series is written in below mentioned chronological order, feel free to skip to whatever interests you more.</p><ul><li><a href="https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697"><strong>Shellcoding 0x0: An Introduction to Red Pills</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca"><strong>Shellcoding 0x1: Popshell Recipe</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6"><strong>Shellcoding 0x2: Bring Your Own Reverse Shell</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>Shellcoding 0x3: Dropping Multi-stage Payload</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a"><strong>Shellcoding 0x4: Packing Presents with Evil Santa</strong></a></li></ul><h3>Context First</h3><p>Almost all exploitation attempts share a common ground, i.e. the boundary between interpretation of CODE and DATA is ambiguous (see <a href="https://en.wikipedia.org/wiki/Von_Neumann_architecture">von Neumann architecture</a> which is still the foundation of many modern computers). Wherever one could find such ambiguity, there is a possibility of <strong>code execution</strong> (see <a href="https://en.wikipedia.org/wiki/Harvard_architecture#:~:text=The%20Harvard%20architecture%20is%20a,the%20same%20memory%20and%20pathways.">harvard architecture</a> which has clear distinctions for code &amp; data). Since shellcode is frequently delivered in the form of DATA (which can be analyzed as a stream of raw bytes), <strong>filters</strong> can be deployed to detect code (i.e. CPU instructions) being communicated/transmitted in the form of DATA and hence infection/exploitation attempts can be detected. Below diagram depicts a filter placed during shellcode delivery to detect shellcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*7v6tzIb2bkaI0panHV20XQ.png" /></figure><p>Due to the above scenario, an attacker may frequently want to craft a shellcode free from certain byte sequences (depending on the target software being exploited or the policies/filters being bypassed). A filter policy could be detecting a particular strain of shellcode or ensuring that the user-supplied <strong>data</strong> should not contain any <strong>code pattern</strong>. A code pattern can be detected by scanning for byte sequence pertaining to syscall (0f 05), int 0x80 (cd 80) or sysenter (0f 34) instructions which are used to invoke <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca#:~:text=Syscalls%20via%20C%20program">system calls</a> (an interface that almost every meaningful piece of code will use).</p><p>It is hard to imagine doing anything useful without system calls. Therefore, we are left with hiding our intentions. To evade filters placed on user supplied data, one could use arbitrary bytes in place of flagged byte sequence and modify itself at those specific labels to attain its original form during runtime. There can be various ways to approach such implementation (one should try combining arithmetic and bitwise operations creatively).</p><h3>Packing the payload body</h3><p>For the purpose of this article, rather than obfuscating a particular sequence of bytes, we would like to pack the whole payload body and have a decoder stub carry the packed payload. Upon execution, the decoder stub unpacks payload body in memory and transfers control to it. The below diagram depicts the scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opCnIHOaSYMjHtxbRRgerA.png" /></figure><p>To obfuscate payload body, we simply use a property of XOR operation, i.e.</p><pre>(<strong>a ^ k = b</strong>) implies (<strong>b ^ k = a</strong>)</pre><ul><li>a → original payload body</li><li>k → key</li><li>b → packed payload</li></ul><p>Below is how we can quickly write an encoder to obfuscate our payload with key byte 0xbc.</p><pre><br><strong>#define KEY_BYTE 0xbc</strong><br>...<br>    for (unsigned int i = 0; i &lt; shellcode_length; ++i) {<br>        <strong>shellcode[i] ^= KEY_BYTE</strong>;<br>    }<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*NKa5YZcLAZ1JE6imZLVJlQ.png" /><figcaption>XOR encoded shellcode (key → 0xbc)</figcaption></figure><p>The above highlighted sequence of bytes represents the <a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a#:~:text=with%20Evil%20Santa-,Context%20First,-Almost%20all%20exploitation">packed payload body</a> which wouldn’t make sense to the detection programs until it gets to its original form.</p><h3>Santa bought you some presents</h3><p>Since we have a <a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a#:~:text=with%20Evil%20Santa-,Context%20First,-Almost%20all%20exploitation">XOR encoded payload body</a>, its time to craft a corresponding decoder stub. Below mentioned code does it gracefully —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*2-lHIhqClqrEI6uZ-yPGwA.png" /></figure><p>The above code uses a <strong>jmp-call-pop</strong> sequence to retrieve address of encoded shellcode (Line 13–37–20) into register r8.</p><ul><li><strong>main</strong> (Line <strong>20</strong>–<strong>23</strong>): Initialises loop counter to 0 and sets length of encoded payload in eax.</li><li><strong>again</strong> (Line <strong>30</strong>–<strong>34</strong>): a loop code construct which iterates over each byte of encoded payload and XOR’s it with key value of 0xbc. The loop iterates ecx number of times (equal to the length of encoded payload).</li><li><strong>decodeMe </strong>(Line <strong>40</strong>): byte sequence here corresponds to the previously generated XOR encoded shellcode.</li></ul><p><strong>NOTE</strong>: For above shellcode to execute without a crash, the memory segment at which code injection is achieved must have RWX permissions on it. If this is not the case, one would need to first allocate such memory region, perhaps via mmap(2) as described <a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70#:~:text=stage2%3A%20could%20you%20make%20me%20some%20room%20%3F">here</a>.</p><h3>A Closer Look Inside GDB</h3><p>Let’s observe the shellcode under Gdb to confirm it doesn’t carry any bad character or byte sequence which might get flagged by target defense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yG3UIITIGJ2w0Z2KHN1Mg.png" /><figcaption>packed shellcode residing in memory</figcaption></figure><p>Above, we see how packed shellcode body looks like in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJOGrIJqBC9MNYaBfp6DGw.png" /><figcaption>decoding packed shellcode</figcaption></figure><p>Above, we set a <strong>conditional breakpoint </strong>(after counter attains a value of 64)<strong> </strong>such that the code flow breaks as soon as it finishes iterating over (decoding) every byte at <strong>decodeMe</strong> label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zbq9CK5gC_euQsynj29NBw.png" /><figcaption>payload body in its original form</figcaption></figure><p>Finally, we see the disassembled payload body in its original form. This is a dummy payload does nothing more than printing a message to STDOUT and exiting with a return value of 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*3QHyNhYmymnRRWlI6y7QmQ.png" /><figcaption>code execution was a success</figcaption></figure><h3>Land of Detection</h3><p>Signature-based detection does fail on payload body but certainly applies to decoder stub (at least for the above case). Writing a signature (check out <a href="https://github.com/Yara-Rules/rules">YARA rules</a>) for decoder stub can effectively be used to detect a sample using such logic in the wild. However, a <a href="http://virus.wikidot.com/dark-avenger-mutation-engine"><strong>mutation engine</strong></a><strong> </strong>aka<strong> MTE </strong>(search for polymorphic, oligomorphic, metamorphic engines)<strong> </strong>might render the signature-based detection system entirely useless due to having different body structure on each propagation. Therefore, its best to rely on behavioural analysis via manual <strong>human intelligence</strong> or automated analysis under a <strong>sandbox </strong>process (dynamic analysis), keeping in mind a simple fact that <strong>actions never lie</strong>. Since every packed sample would need to unpack itself in memory before it can be executed by the CPU, scanning target’s process address space for malicious artefacts could be one way to deal with evil memory encoders.</p><h3>EPILOGUE</h3><p>This article talks about how detection software might identify a code injection &amp; execution scenario while maintaining a minimum digital footprint by operating solely in-memory. Further, it discusses an approach to craft a packer which allows an attacker to conceal/eliminate certain sequence of bytes while preserving actual behaviour effectively bypasssing signature-based detection mechanism. At last, it briefly discusses ways of detecting such techniques being used in the wild. This is it for the day, I hope this article contributes to someone’s journey into this area.</p><p><strong>DISCLAIMER — </strong>Since the attackers are already making use of this knowledge, it’s the defenders who might find any value to the approach mentioned in this paper.<strong> </strong>This article series is intended for exploit developers, malware researchers, folks indulged in red/blue team operations and independent researchers struggling to find relevant resources into this area. The content is intended to be used solely for educational purposes. Therefore, it doesn’t take responsibility for anyone attracting hell by carrying out malicious intentions. Happy hacking <strong>×_×</strong></p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85e81aa277a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shellcoding 0x3: Dropping Multi-stage Payload]]></title>
            <link>https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdd635fcbf70</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 21:47:41 GMT</pubDate>
            <atom:updated>2022-11-14T15:10:24.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZG9EvkhOSjGZTkYdeZj2Cw.png" /></figure><blockquote>May I bring some friends to this madhouse ?</blockquote><p>Shellcode optimisation (with regards to size) is an important skill that an exploit developer/malware researcher is expected to possess. The problem is, a shellcode that achieves anything useful will need something more than just a few bytes/pages of memory. One may often encounter small memory regions for shellcode which doesn’t serve anything more than trivial purposes. The article describes an approach of crafting a <strong>self-destructing</strong> <strong>shellcode loader </strong>to <strong>bypass accommodation constraint</strong> allowing for huge size shellcode to reside and execute in the target process address space. Later, it describes how an attacker might use these principles to craft a first stage <strong>dropper payload</strong>.</p><p>Even though the article series is written in the below mentioned chronological order, feel free to skip to whatever interests you more.</p><ul><li><a href="https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697"><strong>Shellcoding 0x0: An Introduction to Red Pills</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca"><strong>Shellcoding 0x1: Popshell Recipe</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6"><strong>Shellcoding 0x2: Bring Your Own Reverse Shell</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>Shellcoding 0x3: Dropping Multi-stage Payload</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a"><strong>Shellcoding 0x4: Packing Presents with Evil Santa</strong></a></li></ul><h3>The Constraints</h3><p>Let’s say the target buffer is 45 bytes long and the payload we’re trying to execute is optimised to at most 100 bytes. Below is one way we can achieve execution of a large payload.</p><ol><li>Allocate a large enough address space to accommodate the next stage.</li><li>Read 2nd stage payload in freshly allocated region.</li><li>Transfer code flow to 2nd stage payload.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*QgzM9F-WBc_I6djXJSYppA.png" /></figure><h3>When World is all Sunshine and Rainbows</h3><p>First, we aim to read(2) the next stage payload from standard input (STDIN_FILENO). We might also want a <strong>self destructive </strong>or a <strong>mutated stage1 shellcode</strong>, i.e. it must either <strong>remove itself from memory </strong>(after execution) or <strong>mutate itself to confuse disassemblers</strong>. Designing a self-destruct logic can be as simple as reading stage2 payload in stage1 load address (i.e. overwriting its own self). For this to happen, 2 conditions must be met —</p><ul><li>stage2 payload should have RWX permissions on its resident memory segment.</li><li>stage1 payload must have a base memory address pointing to the relevant part of itself to destruct.</li></ul><p>Assuming the memory region accommodating stage1 is RWX. One can try getting current RIP (base memory address of stage1) by multiple ways including —<strong> lea rsi, [rip]</strong> or <strong>call trampoline; jmp getCurrentRIP; pop &lt;dest_reg&gt;</strong> sequence but these generate NULL bytes (bad characters). Let’s look at a way to get base load address of stage1 (CurrentRIP) without generating bad characters.</p><h4>The RCX Revenge (stage1)</h4><p>As per System V ABI (AMD64 ABI Draft 0.99.6 — July 2, 2012–17:14) —</p><blockquote>A.2.1.2 A system-call is done via the syscall instruction. The kernel destroys registers %rcx and %r11.</blockquote><p>Let’s leverage this to our benefit. The kernel uses %rcx register to store saved-RIP to return after execution of syscall instruction (while RFLAGS is stored in %r11). Therefore, after a system call returns, the address of next instruction (after syscall instruction) can be found in %rcx. This can be used to get current RIP which essentially be used in read(2) syscall. Below is how <strong>syscall; push rcx; pop &lt;dest_reg&gt; </strong>sequence can be leveraged to get current RIP (see line 23,29,30 below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*RWsDX2kSbrFMn6hwjIGizQ.png" /><figcaption>ideal world stage1</figcaption></figure><ul><li><strong>getpid</strong>(2) (line <strong>21</strong>–<strong>23</strong>): simply used because of its small size post assembling.</li><li><strong>read</strong>(2) (line <strong>29</strong>–<strong>35</strong>): reads upto 0xffff bytes of stage2 payload from standard input to its own memory location, effectively clearing stage1 off memory.</li><li>line <strong>42</strong> : padding the remaining region with nop sled.</li></ul><h4>Peaceful Stub (stage2)</h4><p>Below is a harmless stage2 payload that simply writes the string “compilepeace was here x_x\n” to STDOUT_FILENO to confirm successful code execution. Feel free to skip this part or read comments (that explain the write(2) syscall better).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*KWiqo6v6JmLq0PyphYJMWg.png" /><figcaption>harmless stage2 shellcode</figcaption></figure><p><strong>NOTE</strong>: line <strong>54</strong> pads a memory region of size equal to space occupied by stage1, with a nop sled (i.e. junk — stage1 bytes) to ensure the code flow lands on a nop sled and continue down to the second stage. Feel free to pad a larger area as we have 0xffff bytes of wiggle room !</p><h4>Gdb, Let’s put it to test !</h4><p>Let’s see how the shellcode modifies itself using a nop sled (i.e. also used as a padding to second stage payload) under Gdb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*uR8dsINOERYrGIWWcWJIfQ.png" /><figcaption>first stage shellcode</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*kmjBmE2Tgxas8ouB4jazZg.png" /><figcaption>mutated first stage shellcode</figcaption></figure><p>From above test, it is evident that stage1 shellcode read the next stage into its own body (overwritten with a nop sled).</p><h3>Land Far from Ideal World</h3><p>A perfect world where one could afford to inject shellcode in RWX memory region could probably be the world of JIT compilers and Looney Tunes. Memory regions these days are marked with W^X memory permissions, i.e. a memory segment should be either writable or executable but not both (mutually exclusive of each other) under default linker configuration. To bypass this mitigation, an exploit would use byte sequences (instructions) present in executable memory regions and chain them to achieve desired results, a process called <strong>R</strong>eturn <strong>O</strong>riented <strong>P</strong>rogramming (<strong>ROP</strong>).</p><p>The shellcode above assumes the bytes beyond allocated space (45 bytes) fall into the same memory region having RWX memory permissions, this might not always be the case. The sequence read() + jmp stage2; would cause a segmentation fault (signal SIGSEGV) on jmp stage2 if stage2 falls into a memory segment with No-eXecute permissions (RW-) (this could happen for example if the buffer for stage1 lies 45 bytes from the page boundary).</p><h4>stage2: could you make me some room ?</h4><p>Since stage2 requires a RWX memory segment to function properly. We can use <a href="https://man7.org/linux/man-pages/man2/mmap.2.html">mmap(2)</a> to allocate RWX memory pages, inject stage2 shellcode and transfer control flow to it. In order to make syscalls, one might frequently need to reference constants pertaining to a MACRO. Below is how this could be done using grep or strace to trace mmap(2) call—</p><pre><strong>$ grep -r &quot;define PROT_[READ|WRITE|EXEC]&quot; /usr/include</strong><br>/usr/include/x86_64-linux-gnu/bits/mman-linux.h:<br>#define <strong>PROT_READ</strong>       <strong>0x1</strong>             /* Page can be read.  */<br>...</pre><pre>OR</pre><pre>$ <strong>strace</strong> <strong>-e raw=mmap</strong> ./harness.elf    /* NO MACROS for mmap args */<br>...<br><strong>mmap(0, 0xffff, 0x7, 0x22, 0, 0)</strong> = 0x7f3b97554000<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*Ib1OXkXxmLqTnrkOrcNwJg.png" /><figcaption>mmap(2)</figcaption></figure><ul><li><strong>mmap(2) </strong>(line <strong>29</strong>–<strong>41</strong>): Above syscall maps <strong>0xffff</strong> bytes (rounded off to 16 pages) of RWX (<strong>7</strong>) private memory (not shared by any other process) (<strong>0x22</strong>). Here we let the kernel choose an appropriate page-aligned address (<strong>0</strong>–1st arg) and the mapped region is not backed by any file on disk (hence 5th &amp; 6th args are 0).</li><li>(line <strong>40</strong>): pushes RSI (stores the length of mapped memory) which is popped by read(2) invoked next (as below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*TcNafyTBi4Un6-8ajoCDVQ.png" /><figcaption>read(2)</figcaption></figure><ul><li><strong>read(2)</strong> (line <strong>47</strong>–<strong>53</strong>): mmap(2) returns the memory address of mapped region in RAX . Via STDIN_FILENO, we read stage2 into into freshly mapped region (RAX). (line <strong>47</strong>) pop rdx stores size of mapped region (RSI pushed on line 40 in mmap syscall).</li><li>(line <strong>55</strong>–<strong>56</strong>): It simply jumps to stage2 shellcode, i.e. RBX storing stage2 load address (see push and pop on line <strong>49</strong> &amp; <strong>55</strong> respectively)</li><li>(line <strong>62</strong>): places 5 nops to pad upto 45 bytes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*gKGxmhkftUV5OTbaT1wiFw.png" /><figcaption>Stage 1 shellcode</figcaption></figure><p>Above is how a stage1 shellcode would look into memory (see field 2 storing encoded bytes). Stage2 shellcode still the same payload (writes a string constant to STDOUT). Let’s test our shellcode —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*pECVaLH4ieX0xyWaiiVErQ.png" /><figcaption>testing multistage payload</figcaption></figure><p>Finally, we were able to execute a <strong>109 byte</strong> harmless shellcode in an accommodation constraint of <strong>45 bytes</strong>, what a day !</p><h3>Dropper Payload</h3><p>Above shellcode is nice to use for delivery via local POCs/malware but usually an attacker would be at a remote geographical location, meaning the entire communication must happen between target process and attacker machine. To achieve this, a dropper payload would need to read the next stages on a socket rather than standard input. With position independent code, it is now easy to drop next stages into freshly mmaped region and jmp to it. A trivial <strong>dropper agent</strong> might use syscalls in below order to iteratively read and execute shellcode from a C2 server deployed within attacker infrastructure —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvHUQADdOWxettduVWO9Vg.png" /><figcaption>Syscall sequence of a simple multistage dropper</figcaption></figure><h3><strong>EPILOGUE</strong></h3><p>This article crafts a shellcode loader to bypass accommodation constraint in context of code execution by staging a large payload into multiple phases. This allows an ideal room for an ambitiously large parasite. Later it looks into how an attacker could use similar principles with UNIX socket API to craft a memory dropper. I hope this article contributes to your research journey.</p><p><strong>DISCLAIMER — </strong>Since the attackers are already making use of this knowledge, it’s the defenders who might find any value to the approach mentioned in this paper.<strong> </strong>This article series is intended for exploit developers, malware researchers, folks indulged in red/blue team operations and independent researchers struggling to find relevant resources into this area. The content is intended to be used solely for educational purposes. Therefore, it doesn’t take responsibility for anyone attracting hell by carrying out malicious intentions. Happy hacking <strong>×_×</strong></p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdd635fcbf70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shellcoding 0x2: Bring Your Own Reverse Shell]]></title>
            <link>https://systemweakness.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b0efb6e8d6</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 02:54:00 GMT</pubDate>
            <atom:updated>2022-08-12T12:08:24.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*JERaRHB6AN7gdLJ5MU1ciw.png" /></figure><blockquote>Communication is the key to success, let’s talk shell x_x</blockquote><p>In the <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca">previous article</a>, we wrote shellcode to spawn a shell. While this is still useful, it may be more valuable to demonstrate a quick POC exploit that works locally. Till now, we have been dealing with local processes on the target machine but shellcode can be designed to do much more than that. In this article, we will leverage networking API provided by Linux platform to craft shellcode that delivers a shell session (a /bin/sh interface to target machine) to a virtual machine listening over the same network interface (at a certain IP address-port number).</p><p>While this might not sound much interesting but the fact that it can <strong>connect-back</strong> to any machine over internet is what starts to carry attention from adversaries. An attacker after getting its shellcode executed would need a way to control the victim, getting a remote shell starts to sound more like why not!. The payload achieving this effect is loosely called <strong>remote shell</strong>, also known as <strong>connect-back</strong> or <strong>reverse shell</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JezMhp2CtpGZzy8w3I735Q.png" /><figcaption>getting remote access to compromised machine</figcaption></figure><p>Even though the article series is written in the below mentioned chronological order, feel free to skip to whatever interests you more.</p><ul><li><a href="https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697"><strong>Shellcoding 0x0: An Introduction to Red Pills</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca"><strong>Shellcoding 0x1: Popshell Recipe</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6"><strong>Shellcoding 0x2: Bring Your Own Reverse Shell</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>Shellcoding 0x3: Dropping Multi-stage Payload</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a"><strong>Shellcoding 0x4: Packing Presents with Evil Santa</strong></a></li></ul><h3>C Through Logic</h3><p>Network communication between devices happen over endpoints known as sockets. A socket is identified by a pair of IP address and port number (representing machine address and service executing on it). Good news is that Linux kernel provides a rich API to create sockets and deal with network operations. Below is how we design a program that connects back to attacker machine listening on socket (IP address 192.168.1.6 &amp; port 19999 ). Here, we perform a sequence of <strong>socket</strong>() → <strong>connect</strong>() → <strong>dup2</strong>() → <strong>execve</strong>() syscalls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-6Hs5hUU1zoRfjziSBDeA.png" /><figcaption>reverse_shell.c (avoids error checking)</figcaption></figure><ul><li><a href="https://man7.org/linux/man-pages/man2/socket.2.html"><strong>socket</strong> (2)</a> (Line<strong> 28</strong>): creates an internet domain socket (AF_INET) of type SOCK_STREAM (which defines the semantics of network communication). This system call returns a file descriptor representing a socket endpoint which will be used to connect to remote machine.</li><li><a href="https://man7.org/linux/man-pages/man2/connect.2.html"><strong>connect</strong>(2)</a> (Line<strong> 32</strong>–<strong>37</strong>): before we perform connect(2) , we need to specify the IP address and port number of remote machine to connect to. connect(2) takes in a socket address structure of type struct sockaddr, which holds what IP address and port number (service) to connect to (see /usr/include/netinet/in.h for referencing struct sockaddr). We start with declaring and populating evilAddr with address family (AF_INET), remote port to connect to (encoded from host →network byte order) and IP address of remote host (encoded into network-byte-order). Later, we perform a connect(2) to evilAddr.</li><li><a href="https://man7.org/linux/man-pages/man2/dup.2.html"><strong>dup2</strong>(2)</a> (Line <strong>40</strong>–<strong>41</strong>): we run a loop to perform dup2(sockfd, i) syscall over standard I/O file descriptors — 0 (STDIN_FILENO), 1 (STDOUT_FILENO) and 2 (STDERR_FILENO) such that the <strong>file descriptor table</strong> entries (0, 1 and 2) points to sockfd’s (socket file descriptor) <strong>open file description</strong> (within <em>system-wide</em> <strong>open file table</strong>). This has such an effect that the all I/O performed on FDs 0,1 and 2 will indeed be performed on socket.</li><li><a href="https://man7.org/linux/man-pages/man2/execve.2.html"><strong>execve</strong> (2)</a> (Line 44): By default, file descriptors accross an execve() syscall (unless file descriptors are marked with close-on-exec, see <a href="https://man7.org/linux/man-pages/man2/fcntl.2.html">fcntl(2)</a>) which means all I/O performed by the newly loaded program (on FDs 0, 1 &amp; 2) will be happening on attacker-connected socket.</li></ul><p>Below is how the code was tested — <strong>attacker machine</strong> (running kali-linux-2022.1) is listening on IP address 192.168.16 and port number 19999 ( $ nc -lp 19999). Below, the <strong>victim/target machine</strong> (running Ubuntu 21.04) executes reverse_shell.elf (compiled by $ gcc -o reverse_shell reverse_shell.c) and attacker gets a shell running as a process on victim machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*fK2U1XDLJ6Br-cveEdrVQw.png" /><figcaption>Attacker machine (kali — above) talking to victim machine (ubuntu — below)</figcaption></figure><p>Now that we understand the logic at a higher level, nothing stops us from crafting a shellcode for the same.</p><h3>TCP Reverse shell (100 bytes)</h3><p>Before performing a syscall, arguments to syscall should be passed in sequence — rdi, rsi, rdx, r10, r8 and r9 while syscall number in rax (as per <a href="https://wiki.osdev.org/System_V_ABI">System V ABI</a>). Let’s write some code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*NAvS6AEHeNcplIQWqOetWA.png" /><figcaption>socket (2) + connect (2)</figcaption></figure><p>I hope the comments above explain the program well. Just in case they don’t —</p><ul><li><strong>socket</strong>(2) (Line <strong>6</strong>–<strong>13</strong>): uses push-pop sequence using stack to initialise registers with appropriate values to perform socket(2). Line 12 uses cdq instruction to zero out rdx (cdq extends the sign/most-significant bit of eax to all bits of rdx).</li><li><strong>connect</strong>(2) (Line <strong>16</strong>–<strong>28</strong>): saves the return value from socket(2) in edi and clears rdx (using cdq). Next, we push 2 QWORDS (0x10 bytes) onto the stack that represents struct sockaddr_in (lines <strong>18</strong>–<strong>19</strong>). (lines <strong>20</strong>–<strong>22</strong>) moves AF_INET (0x2), port number (19999) and remote IP <strong>192.168.1.6</strong>. (lines <strong>23</strong>–<strong>24</strong>) pushes the address of populated structure and pops it into rsi (2nd argument to connect()). (lines <strong>25</strong>–<strong>28</strong>) sets rdx to sizeof struct sockaddr , rax to syscall number and performs a connect(2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*HufYxza53TStHqGiZnWbIg.png" /><figcaption>dup2 (2) syscall (setting up standard I/O FDs)</figcaption></figure><ul><li>(lines <strong>38</strong>–<strong>47</strong>): To duplicate standard I/O file descriptors, we iterate from rbx = [0,3)performing dup2(sockfd, rbx);. Since edi is already set to sockfd from above, we just need to set rsi (newfd) to 0, 1 and 2 at each iteration performing dup2(2) syscall.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*9KsKlyTtICcF7OuxLQR2hA.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/execve_binsh.s">execve_binsh.s</a></figcaption></figure><p>Above, we perform execve(“/bin/sh”) and exit(7) which have been described in fair depth <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca">here</a>.</p><p>Testing above payload, we take harness.elf as a vulnerable SUID binary, we supply reverse_shell.raw (raw bytes) as input below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*LTdGcazPq_OPA_FEoQBrLA.png" /></figure><h4>Where‘s my root shell ?</h4><p>We got a remote shell, but it isn’t having root privileges. If you read the <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca">previous article</a>, it might have already clicked that shell program drops privilege and we therefore need a suid(0) syscall before execve(“/bin/sh”). Adding this syscall and testing again as shown below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*yNNd0N_5dy_r88AFG0pfYA.png" /><figcaption>adding setuid(0) to reverse shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*2SynnEgAOVVKB9x_NcM89A.png" /><figcaption>reverse root shell</figcaption></figure><p>Finally, we get a <strong>reverse shell with root privileges</strong> !</p><h3>Land of Detection &amp; Prevention</h3><p>Rootkits can make life of a defender tough, but if no rootkit installation took place before initiating connection with attacker C2 infrastructure — such mischief can trivially be <strong>detect</strong>ed by network monitoring tools like netstat . To <strong>prevent</strong> such scenarios, it would be a better idea to run victim software service/application process under a sandbox (under a new <a href="https://man7.org/linux/man-pages/man7/namespaces.7.html">mount namespace</a> instance having no network device <em>mount point</em> to bind attacker’s socket address to) and <a href="https://man7.org/tlpi/code/online/dist/sockets/scm_rights_send.c.html">use passing-the-file descriptor via UNIX domain sockets</a> to pass socket file descriptor keeping victim process’s legitimate/intended connection(s) up while denying any other network activity.</p><h3>Epilogue</h3><p>This article explains the process of getting remote access to compromised machine over a shell. It starts with writing a C program invoking Linux networking syscalls and later implementing a reverse shell in x86–64 assembly. Next, we proceed towards creating <strong>multi-stage shellcode</strong>.</p><p><strong>DISCLAIMER — </strong>Since the attackers are already making use of this knowledge, it’s the defenders who might find any value to the approach mentioned in this paper.<strong> </strong>This article series is intended for exploit developers, malware researchers, folks indulged in red/blue team operations and independent researchers struggling to find relevant resources into this area. The content is intended to be used solely for educational purposes. Therefore, it doesn’t take responsibility for anyone attracting hell by carrying out malicious intentions. Happy hacking <strong>×_×</strong></p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b0efb6e8d6" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6">Shellcoding 0x2: Bring Your Own Reverse Shell</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shellcoding 0x1: Popshell Recipe]]></title>
            <link>https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7e8539c64ca</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 02:03:20 GMT</pubDate>
            <atom:updated>2023-09-11T09:29:17.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*2-JOxSinNHNgRS1VEo8pyw.png" /></figure><blockquote>Hope you’re talking to the CPU like never before x_x</blockquote><p>While writing code, there is almost always that you would like to reuse already existing libraries/frameworks to meet your purposes. This makes programming a lot easier since we do not want to reinvent the wheel. That’s exactly what we can<strong>not</strong> do when we achieve code execution. In this article, we will understand how to leverage functionality provided by operating system and pop our favourite shell along our way.</p><p>Even though the article series is written in the below mentioned chronological order, feel free to skip to whatever interests you more.</p><ul><li><a href="https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697"><strong>Shellcoding 0x0: An Introduction to Red Pills</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca"><strong>Shellcoding 0x1: Popshell Recipe</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6"><strong>Shellcoding 0x2: Bring Your Own Reverse Shell</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>Shellcoding 0x3: Dropping Multi-stage Payload</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a"><strong>Shellcoding 0x4: Packing Presents with Evil Santa</strong></a></li></ul><h3>System Calls</h3><p>Assuming that the application process whose execution flow is now in control of our injected shellcode, is running on top of Linux kernel. Now, we want our shellcode to spawn a shell, which involves <strong>loading</strong> it into memory prior to execution by the processor (i.e. shellcode needs to read shell program file stored on secondary storage device and write it to physical memory chip — RAM). Now, for our shellcode to achieve anything significant on the system, it must have access to system resources. But the application we hacked was spawned as a <em>usermode process</em> (by the kernel) holding the processor in an unprivileged mode, essentially having <strong>restricted/NO-direct access to system resources</strong> (like HDD, RAM, device drivers or any other hardware peripheral).</p><p><strong>NOTE</strong>: A CPU has several operational modes of execution. Broadly, it can be classified as — <strong>thread mode </strong>(aka <strong>usermode</strong>)<strong> </strong>and <strong>handler mode</strong>. Handler mode of execution is always privileged (having access to entire set of system resources) while thread-mode/user-mode is usually configured to restricted access by the OS.</p><p><strong>In usermode state, how can our shellcode access system resources ?<br></strong>Well, an application process running in <strong>usermode</strong> can request access to these restricted resources via standard interfaces provided by kernel called <strong>system calls </strong>(loosely called <strong>syscalls</strong>). In essence, an application can invoke system calls which request the OS to perform privileged operations (like accessing hardware components) on behalf of it. In a way, this makes life of a programmer easy as application developers no longer needs to know how to talk to the hardware components directly, kernel services are always available — just a syscall away !</p><p>For a list of system calls offered by your Linux kernel, refer to syscalls man page ( $ <strong>man syscalls</strong> ). All syscalls are documented under 2nd page of respective manual.</p><h4>Performing Syscalls via C program</h4><p>Now that we understand what syscalls are, let’s look at ways to invoke syscalls. For most syscalls, the GNU C library has a wrapper function around assembly instructions performing syscalls, also we have syscall(2) which can be used in case of newly implemented syscalls or one’s for which no wrapper function is available in C library. Below is how to perform sycalls in C —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*t3Uv352_ROufDxcdbTBKKw.png" /><figcaption>man 2 syscall</figcaption></figure><pre>$ gcc -o exit exit.c<br>$ <strong>strace</strong> ./exit          # trace through syscalls invoked by ./exit<br>execve(&quot;./exit&quot;, [&quot;./exit&quot;], 0x7ffe6b651f20 /* 52 vars */) = 0<br>brk(NULL)                               = 0x55dedee84000<br>.<br>.<br>.<br><strong>exit(7)</strong>                                 = ?<br>+++ exited with 7 +++</pre><p>Alternatively, we could have used the exit(2) wrapper too but it doesn’t perform the desired syscall. Below is how the manual explains it —</p><pre><strong>$ man 2 read<br>...<br>C library/kernel differences</strong><br>In glibc up to version 2.3, the _exit()  wrapper  function  invoked<br>the  kernel  system  call  of  the same name.  Since glibc 2.3, the<br><strong>wrapper function invokes exit_group(2)</strong> ...</pre><h4>Performing System calls via Assembly program</h4><p><a href="https://wiki.osdev.org/System_V_ABI">System V ABI</a> (gabi/psabi having a set of specifications used by major UNIX operating systems including Linux) documents function calling conventions allowing us to invoke syscalls directly by speaking processor’s language. These conventions describe which registers shall be used to pass what arguments, where will the return value go and so on. On x86–64 architecture, the Linux kernel expects syscall arguments to be passed in the following order —</p><pre>Registers: <strong>RAX</strong>    <strong>RDI</strong>   <strong>RSI</strong>   <strong>RDX</strong>   <strong>R10</strong>    <strong>R8</strong>    <strong>R9</strong><br>syscall (SYS_XXX, arg1, arg2, arg3, arg4, arg5, arg6);</pre><p>To perform an exit(7) syscall, we need to set register rax and rdi to values 60 (syscall number) and 7 (exit status) respectively. For syscall numbers, please refer <a href="https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*jN6c5Dczv0xb72M6lL_smQ.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/exit.s">exit.s</a> (<strong>8</strong> bytes)</figcaption></figure><ul><li>push 60; pop rax (3 bytes) is an optimised way of loading 60 into rax (syscall number). Similarly, push 7; pop rdi (3 bytes) is an optimised way of loading 7 into rdi.</li><li><strong>syscall</strong> instruction switches the CPU from usermode to kernel mode and calls to exit() residing in kernel space.</li></ul><p>Below, we use gcc to assemble instructions packing CPU encoded instructions in exit.elf program. objcopy is used to dump raw bytes inside exit.elf’s text section to a file named exit.raw (shellcode). exit.raw is provided as input to harness.elf (which executes those raw bytes). Later, we check the exit status of last executed program (via echo $?) which confirms it executed just fine !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*0lxb6Cir4J5KzP3eAdK14g.png" /><figcaption>build &amp; test</figcaption></figure><p>We typically want to do something more useful than just exit gracefully, let’s pop a shell !</p><h3>Performing rituals</h3><p>Spawning a shell has been a traditional way to get access to a compromised machine. Let’s load “/bin/sh” via execve() syscall, a.k.a program loader. It will cause the calling process address space to be replaced by freshly loaded “/bin/sh” transferring control flow to its entry point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*92Z2ZPB4izO3WgYljcGlrg.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/execve_binsh.s">execve_binsh.s</a> (<strong>22</strong> bytes)</figcaption></figure><p>Below is some explanation —</p><pre>/* syscall number for execve (<strong>rax</strong>) = 59 */<br>int execve (const char *pathname,      /* <strong>rdi</strong> = &quot;//bin/sh&quot; */<br>            char *const argv[],        /* <strong>rsi</strong> = 0 */<br>            char *const envp[]);       /* <strong>rdx</strong> = 0 */</pre><ul><li><strong>[Line 17]</strong> To zero out a register, we could simply use the instruction mov esi, 0; but this instruction gets assembled into be 00 00 00 00(5 bytes). Apart from its size, it has a problem of having 4 NULL bytes (\x00) in its encoding which makes it unfit to be used as shellcode (since NULL byte in mostly cases will fall under the category of bad character). Instead, we use xor esi, esi (31 f6), which is an optimised way to zero out a register without having any NULL byte in its encoding. Here, the register rsi represents argv .</li><li><strong>[Line 18–22]</strong> We want to store &quot;//bin/sh” in memory and get its address in rdi. push rsi pushes a NULL byte on stack (marking the end of string bytes). mov rdi, 0x68732f6e69622f2f; push rdimoves raw bytes of ASCII encoded string from rdi (8 encoded bytes in reverse order due to intel x64 being <a href="https://en.wikipedia.org/wiki/Endianness">little endian</a>) over to the stack segment. push rsp; pop rdi sequence gets the address of string (stored on stack) inside rdi.</li><li><strong>[Line 23–24]</strong> stores 59 into rax (syscall number for execve).</li><li><strong>[Line 25]</strong> cdq sign-extends the most significant bit of eax (i.e. 0) into edx, essentially storing 0 into edx.</li><li><strong>[Line 26]</strong> syscall instruction invokes the syscall.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*ACJIIY4144OgtxrPHioapg.png" /><figcaption>build &amp; test</figcaption></figure><p>We have a problem here, running shellcode gave us an exit status of 0 yet we didn’t receive a shell (notice the same PIDs before and after executing shellcode — 3336). We need to have a closer look to check if the syscall is being performed. Calling strace to the rescue —</p><pre>$ strace ./harness.elf &lt; ./execve_binsh.raw<br>execve(&quot;./harness.elf&quot;, [&quot;./harness.elf&quot;], 0x7ffe49f6f730 /* 52 vars */) = 0<br>.<br><strong>.<br>execve(&quot;//bin/sh&quot;, NULL, NULL)</strong>          = 0<br>.<br>.<br><strong>read</strong>(0, &quot;&quot;, 8192)                       = 0<br><strong>exit_group</strong>(<strong>0</strong>)                           = ?<br>+++ exited with 0 +++<br>$</pre><p>Looking at the strace output, we can confirm that execve(“//bin/sh”, NULL, NULL); succeeded to load shell which read() 8192 bytes from STDIN but got nothing and exited with a status code of 0.</p><p>This happens because read() receives an EOF (end of file) on STDIN (standard input stream). To avoid this, we need to remain connected to STDIN (i.e. keeping the file descriptor open) to be able to continue giving commands and the output should continue getting passed to STDOUT (piped to ./harness.elf). There is this neat trick with /usr/bin/cat that solves our purpose as shown below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*slCHpkbijNlXZNY2SBx2mw.png" /><figcaption>little cat trick</figcaption></figure><p>Let’s check if this shellcode works on SUID programs as well. Let’s change the owner of ./harness.elf to root (via chown) and set <strong>SUID bit</strong> on it (via chmod). A program with SUID bit set will run with effective privileges of its owner (which in our case will be root).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*EmfoQX7Ymo0D9cL9ziPOIw.png" /><figcaption>Damnnnn !</figcaption></figure><p>We can see the shell spawned, but with dropped privileges :(</p><h3>Dealing with Dropped Privileges</h3><p>Some programs including shell drops privileges by default when loaded &amp; executed. To retain root privileges, we need to perform a setuid(0) syscall before performing an execve(“/bin/sh”) . A setuid(2) is used to set the effective UID of calling process, below we set it to UID 0 (root). I hope below mentioned comments explain the program better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*FOfzTan1M0jXiYw10Ltv4w.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/setuid_execve_binsh.s">setuid_execve_binsh.s</a> (<strong>29</strong> bytes)</figcaption></figure><p><strong>NOTE</strong>: Alternatively, -p flag can be passed to argument list while execve’ing shell to retain privileges !</p><p>Let’s build &amp; test our shellcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqcRmHwBbkbT0XwEXJHg8g.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/setuid_execve_binsh.s">setuid_execve_binsh.s</a> payload</figcaption></figure><p>Finally, we’re high on shell !</p><h3>Epilogue</h3><p>This article explains the need to perform direct syscalls and describes an approach for writing shell spawning machine code. Later, it demonstrates how to overcome challenges related to dropped privileges, i.e. faced during development and execution of the most commonly used shellcode . Next, we proceed towards crafting a shellcode that talks to other machines over internet !</p><p><strong>DISCLAIMER — </strong>Since the attackers are already making use of this knowledge, it’s the defenders who might find any value to the approach mentioned in this paper.<strong> </strong>This article series is intended for exploit developers, malware researchers, folks indulged in red/blue team operations and independent researchers struggling to find relevant resources into this area. The content is intended to be used solely for educational purposes. Therefore, it doesn’t take responsibility for anyone attracting hell by carrying out malicious intentions. Happy hacking <strong>×_×</strong></p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7e8539c64ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shellcoding 0x0: An Introduction to Red Pills]]></title>
            <link>https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1557ac075697</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 12:47:37 GMT</pubDate>
            <atom:updated>2023-09-11T09:01:18.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*-2Sa5MwL9bqdbTOWEGndvg.png" /></figure><blockquote>I wonder what would you choose, blue or red x_x</blockquote><p>Hello folks, through a series of articles I plan to describe the area of Linux shellcoding (intel x86–64 CPU architecture) in enough depth to be able to bypass static based detections applied at defensive side (at least). This article intends to cover some fundamentals around this area. It starts with providing a context introducing <strong>code injection</strong>, building a simple assembly program (performing system calls is explained in <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca#:~:text=Own%20Reverse%20Shell-,System%20Calls,-To%20be%20able">next article</a>) and later talks about different ways to test shellcode (each one having its own limitations and advantages).</p><p>Even though the article series is written in the below mentioned chronological order, feel free to skip to whatever interests you more.</p><ul><li><a href="https://compilepeace.medium.com/shellcoding-0x0-an-introduction-to-red-pills-1557ac075697"><strong>Shellcoding 0x0: An Introduction to Red Pills</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca"><strong>Shellcoding 0x1: Popshell Recipe</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x2-bring-your-own-reverse-shell-1b0efb6e8d6"><strong>Shellcoding 0x2: Bring Your Own Reverse Shell</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>Shellcoding 0x3: Dropping Multi-stage Payload</strong></a></li><li><a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a"><strong>Shellcoding 0x4: Packing Presents with Evil Santa</strong></a></li></ul><h3>Prerequisites</h3><ul><li>Familiarity with <a href="https://compilepeace.medium.com/memory-malware-part-0x1-introduction-to-the-binary-world-1b26c0478846#:~:text=process%20actually%20goes%20%3F-,Compilation,-The%20source%20code">compilation process</a> is assumed throughout the article series (mainly assembling phase).</li><li>Familiarity with Intel x86–64 assembly (check out OST2’s <a href="https://p.ost2.fyi/courses/course-v1:OpenSecurityTraining2+Arch1001_x86-64_Asm+2021_v1/about">Arch. 1001</a> which does it better job teaching it) will be helpful but not strictly necessary as I plan fill in some gaps on the fly.</li></ul><h3>Context First</h3><p>Since code injection starts with exploitation and ends at post-exploitation phase (which is a later phase in any <a href="https://en.wikipedia.org/wiki/Kill_chain">kill-chain</a> model), this article series implicitly assumes a code injection &amp; execution scenario -</p><blockquote>The vulnerable software being targeted is running with root privileges (effective UID 0 without any process isolation techniques in place) on a Linux platform and intel x86–64 processor architecture. The attacker exploiting the software managed to inject data in an executable region of target software’s process address space and was successful is hijacking the code flow, achieving a state called <strong>arbitrary code execution </strong>(ACE)<strong> </strong>or<strong> remote code exection </strong>(RCE if any network software is being exploited remotely).</blockquote><p>In context to the above scenario, we plan to craft the <strong>injected data</strong>, i.e. <strong>shellcode</strong> a.k.a<strong> payload</strong> to which an attacker may want to transfer hijacked code flow.</p><p><strong>NOTE</strong>: Due to mitigations like <strong>DEP</strong>/<a href="https://en.wikipedia.org/wiki/NX_bit"><strong>NX</strong></a> (applied at both software &amp; hardware layers), it is no more possible to execute shellcode in DATA regions of memory (unless you’re dealing with some JIT compilation or similar software using RWX memory region in its address space). One uses <strong>Return Oriented Programming</strong> (ROP) to bypass such mitigation by chaining sequence of instructions (called gadgets) that can be interpreted from raw bytes residing in CODE segment (having R-X permissions).</p><h4>So, why bother learn shellcoding ?</h4><p>Malware researchers need to be able to understand/write shellcode for <a href="https://compilepeace.medium.com/malware-engineering-part-0x1-that-magical-elf-5be3556ecb2b">obvious reasons</a>. For exploit developers, since an exploit becomes limited to gadgets present in target process’s CODE segment and leveraging it isn’t as flexible as writing shellcode, the first strategy one might want to apply is to create a RWX memory region and bring shellcode in it for execution (in a <a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70"><strong>staged</strong> manner</a> which we discuss later). Also, since ROP is an evolution to classical shellcoding, it seems reasonable to practice running before beginning to parkour (hoping that’s enough talk to get some context).</p><p>Before proceeding forward, there must be enough understanding to differentiate between source code and compiled code, you might want to read <a href="https://compilepeace.medium.com/memory-malware-part-0x1-introduction-to-the-binary-world-1b26c0478846#:~:text=%5BSource%20Code%5D%3A%20CPU%2C%20do%20you%20ever%20feel%20me%20%3F">this</a> highlighted topic.</p><h3>Shellcode — Code Suitable for Injection</h3><p>What we intend to craft is a <strong>self-sufficient</strong> <strong>program</strong> which is able to execute regardless of its base load address in memory (a relocatable piece of code that doesn’t require linking), that’s what we call shellcode. Shellcode is a <strong>position-independent code</strong> (<a href="https://en.wikipedia.org/wiki/Position-independent_code#:~:text=In%20computing%2C%20position%2Dindependent%20code,regardless%20of%20its%20absolute%20address.">PIC</a>) comprising stream of data bytes which corresponds to valid instructions when interpreted by the target CPU. From an attacker’s perspective, it can be understood as CPU instructions (in the form of hexadecimal encoded bytes) crafted under <strong>certain constraints </strong>meant to gain foothold over a compromised machine. Below is what your to-be-favourite shellcode may look like (highlighted in RED)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*gEqT3bvdqTWP8RkFXbat5w.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/execve_binsh.s">execve_binsh.s</a></figcaption></figure><h4>Wait, did you just say constraints ?</h4><p>While crafting shellcode one has to <strong>overcome certain restrictions</strong> (depending upon how it is delivered and interpreted by the target software) which when violated can get the shellcode corrupted before it reaches target address space. Apart from target-specific restrictions, we must ensure that shellcode is —</p><ul><li><strong>position-independent</strong> (<a href="https://en.wikipedia.org/wiki/Position-independent_code#:~:text=In%20computing%2C%20position%2Dindependent%20code,regardless%20of%20its%20absolute%20address.">PIC</a>) in nature. This is usually achieved via relative addressing and clever use of CPU instructions.</li><li><strong>self-sufficient</strong> in itself, i.e. it should not rely on <strong>any external API </strong>(other than<strong> APIs provided by the OS</strong>), since no standard C library functions are available to leverage. A shellcode capable of finding libc base address may allow calling its API, later we’ll see an implementation to this approach.</li><li>restricted to <strong>smallest possible size</strong>. This is largely dependent on the <em>state of exploitation</em> as the point of injection may not have enough wiggle room to accommodate the payload. Later, we learn to craft <a href="https://compilepeace.medium.com/shellcoding-0x3-dropping-multi-stage-payload-fdd635fcbf70">multistage payloads</a> to deal with space constraints.</li><li>free from <strong>bad characters</strong>. Bad characters may be a byte or a sequence of bytes which (if existing inside our shellcode) may get our shellcode corrupted by the time it reaches target’s address space and therefore may result in unintended behaviour (usually resulting into illegal instructions and crashes). In the context of defense evasion, bad chars may be a sequence of bytes whose existence or execution is filtered/flagged by defensive software (AV/EDR/firewalls etc.). Currently, we will be treating only NULL byte (‘\x00’) as a bad character (slowly adding more bytes to this list) and later, we’ll see <a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a">ways to bypass such detections</a>.</li></ul><p>Throughout the article series, we will see techniques that can be leveraged to overcome each of these constraints !</p><p><strong>NOTE</strong>: An optimised shellcode can be made even smaller if we can <em>leverage CPU state </em>at the point when code execution is achieved. Since we can’t predict it in advance, we assume a garbage state for each register we use in this article series.</p><h3>Lets Get Our Hands Red</h3><p>There are many tools/assemblers ([NYFM]asm) which can do the job really well. In this series, I’ll be using GCC which relies on Gas (GNU Assembler as backend) to assemble my shellcode. Below is a program that performs No OPeration and breaks — nop and int 3 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*6oIlCBMh3-7Oh0HHKYTO8g.png" /><figcaption>nop.s</figcaption></figure><p>A brief overview —</p><ul><li><strong>[Line 1–4]</strong> : multi-line comments (C-style) begins with /* and ends at */.</li><li><strong>[Line 6–8]</strong>: .global (defines a global symbol) and .intel_syntax are assembler directives. Assembler directives are not instructions to the CPU (and therefore doesn’t generate any machine code) rather just suggestions for the assembler to take some action. They are not much relevant for the moment, but for those interested, a list of GNU assembler directives can be found <a href="https://ftp.gnu.org/old-gnu/Manuals/gas-2.9.1/html_chapter/as_7.html">here</a>. On <strong>[Line 7]</strong>, we have _start: symbol (a label), which can be thought of as a way to refer to this memory location. The linker (ld) uses this symbol as an entry point for the program.</li><li><strong>[Line 11–12]</strong>: The program constitutes 2 instruction — nop and int 3 . nop stands for No OPeration which is merely used to waste a CPU cycle while int 3 instruction triggers a debug exception handler.</li></ul><p>Next, we see how Gas (GNU Assembler at backend of GCC) can be leveraged to pack these instructions into an executable ELF binary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*zkzYzl_b4_6qX81BbPG2_A.png" /><figcaption>./nop.elf</figcaption></figure><p>Above we see a <strong>Trace/breakpoint trap</strong> because CPU, while executing instructions, landed on 0xcc byte which indicates our shellcode runs just fine. Some flags given to GCC toolchain that needs explanation—</p><ul><li><strong>-Wl,-N</strong> : asks the linker to set RWX permissions for TEXT segment (required for testing <a href="https://compilepeace.medium.com/shellcoding-0x4-packing-presents-with-evil-santa-a85e81aa277a">self-modifying code</a>, more about such code in upcoming articles).</li><li><strong>-nostdlib</strong> : do not link to standard C library.</li><li><strong>-static</strong>: generate a statically linked binary.</li></ul><p><strong>NOTE</strong>: nop is actually an alias for <strong>xchg rax, rax </strong>(having opcode 0x90)on x86-64 architecture. Also, int 3 (having opcode 0xcc) is the way most debuggers allow us set breakpoints.</p><h3>Debugging shellcode</h3><p>Writing code implicitly gives birth to bugs, this demands a need for testing. The idea is to transfer code flow to shellcode and trace through its execution to ensure it works as intended. There may be many ways to debug shellcode, most commonly using —</p><ul><li>Strace</li><li>GCC packed shellcode (as seen above)</li><li>Harness program</li></ul><h4><a href="https://man7.org/linux/man-pages/man1/strace.1.html">Strace</a></h4><p>It is used to trace system calls invoked by a program. You might want to checkout its manual to look for all features it has to offer (thank me later). Below is the output we get while strace’ing exit.elf program which has a sole purpose of performing exit() <a href="https://compilepeace.medium.com/shellcoding-0x1-popshell-recipe-b7e8539c64ca#:~:text=Own%20Reverse%20Shell-,System%20Calls,-To%20be%20able">system call</a> (which is one way to ask the Linux kernel to terminate a process).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*-ZegyynM3sNad_15kLImYQ.png" /><figcaption>strace ./exit.elf</figcaption></figure><p><strong>NOTE</strong>: strace will drop privileges while executing a SUID program, which means any operation requiring privilege will fail with an error code EPERM (operation not permitted).</p><h4>GCC packed shellcode</h4><p>Strace is a quick way to know what syscalls are performed by a program but doesn’t let us trace program by stepping through instructions. This approach allows us to debug shellcode as a regular ELF program taking advantage of any debugging information (added via -g flag). Please note that debugging information is stored in a different section of ELF binary, therefore doesn’t have interference with CODE section (where shellcode bytes are present). Below is the binary under gdb stopped at _start —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*M4AoXplyilT8Zqx4o0QuZw.png" /><figcaption>loading ./nop.elf inside gdb</figcaption></figure><h4>Harness</h4><p>While the above approach of debugging may sound promising yet it suffers from a drawback of <strong>assuming a clear CPU state</strong> (all registers set to store 0) at the beginning of shellcode execution which can be seen when loaded under Gdb. A shellcode assuming a clear CPU state is far from being practical as CPU state is sure to be different each time any vulnerability gets triggered (checkout publicly available shellcode, you’ll find a couple of samples presuming a clear register state).</p><p>Optionally, we can confirm <strong>its not Gdb that’s clearing off register state right before shellcode execution</strong>. This can be done by running our program outside Gdb context and examining CPU state right before executing first shellcode instruction. To do this, modify the binary by placing the opcode byte for int3 (0xcc) at the beginning of .text section. Launch ./exit.elf and wait till the CPU falls to 0xcc (int3), after it terminates, the process address space (core) is dumped. Now, we see the dumped core under gdb (via -c &lt;core_path&gt;) which confirms that the registers were 0 at the time of crash. Below are the respective steps -</p><pre># get the offset of 1st byte in .text section<br>$ readelf -S --wide ./exit.elf  <br>There are 12 section headers, starting at offset 0x328:<br>...</pre><pre>[Nr] Name  Type     Address          Off    Size   ES Flg Lk Inf Al<br>[ 2] .text PROGBITS 00000000004000d4 0000d4 000008 00 WAX  0   0  1<br>...</pre><pre># overwrite a byte at offset 0xd4 to value 0xcc (i.e. opcode for int3 instruction)<br>$ hexedit ./exit.elf</pre><pre># (Ubuntu users)<br># check &amp; ensure a core dump in current working directory<br>$ cat /proc/sys/kernel/core_pattern<br>|/usr/share/apport/apport -p%p -s%s -c%c -d%d -P%P -u%u -g%g -- %E<br>$ echo &quot;core_%e.%p_%t&quot; | sudo tee /proc/sys/kernel/core_pattern</pre><pre># run the program<br>$ ./exit.elf<br>Trace/breakpoint trap (core dumped)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*_KFnOOuhmw4bre9SG-i_dQ.png" /><figcaption>cleared register state (from dumped core) when shellcode begins to execute</figcaption></figure><h3>Hello Harness</h3><p>Lets create a program that reads in shellcode at a RWX memory region, clobbers up registers rax, rdi, rsi, rdx, r10, r8 and r9 (ensuring the shellcode doesn’t presume any CPU state) and transfers code flow to base address at which shellcode is read. This creates a more realistic &amp; robust environment to test the effectiveness of our shellcode. I hope the below mentioned source code is self-explanatory (see comments).</p><p><strong>NOTE</strong>: The kernel interface expect syscall arguments to be passed in sequence — rdi, rsi, rdx, <strong>r10</strong>, r8, r9 while the glibc syscall wrappers are passed with arguments in rdi, rsi, rdx, <strong>rcx</strong>, r8, r9 order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*aJkSn1Y_GpVYQswWAqrhjQ.png" /><figcaption><a href="https://github.com/compilepeace/SHELLCODING_INTEL_x86-64/blob/master/harness.c">harness.c</a></figcaption></figure><p>Here, clobberContext[] is a byte-array that stores assembled instructions (to clobber CPU state). The idea is to inject this byte array before shellcode such that these instructions mess up CPU state just before code flow reaches our shellcode. Below is how we confirm this actually happens using Gdb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*tDVWFUve68pTJAmvVe3c1Q.png" /><figcaption>building exit.raw and harness.s</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*k3ET1vlX6k0g5X0f562yBA.png" /><figcaption>memory region where shellcode is stored</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*xkkZ5Iv8XwiQrqYpC82mBA.png" /><figcaption>Clobbered CPU state just before executing supplied shellcode</figcaption></figure><h3>Epilogue</h3><p>This article marks as an introduction to the world of machine code and lays a logical foundation to the area of code injection. It describes a few tools and approach one can leverage to debug shellcode. Later, it describes the significance of a harness program needed to test the effectiveness of shellcode. I hope this gets you familiar with the respective area, next we move on to writing some meaningful shellcode. Feel free to grab a beer before proceeding forward !</p><p><strong>DISCLAIMER — </strong>Since the attackers are already making use of this knowledge, it’s the defenders who might find any value to the approach mentioned in this paper.<strong> </strong>This article series is intended for exploit developers, malware researchers, folks indulged in red/blue team operations and independent researchers struggling to find relevant resources into this area. The content is intended to be used solely for educational purposes. Therefore, it doesn’t take responsibility for anyone attracting hell by carrying out malicious intentions. Happy hacking <strong>×_×</strong></p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1557ac075697" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reverse Engineering: Diffusing Phase 6]]></title>
            <link>https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fc8293dbceb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 11:27:47 GMT</pubDate>
            <atom:updated>2022-04-11T11:42:14.150Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_XHLtRJNpWn39go6fwM5w.png" /></figure><blockquote>Baby, I hate little secrets you keep from me x_x</blockquote><p>The article continues the <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c">previous one</a> where we diffused phase 5 of bomb binary. Let’s get started with diffusing the last one, phase 6 on <strong>Linux</strong> platform using <strong>GNU Gdb</strong>.</p><p>This writeup is a part of the article series —</p><ul><li><a href="https://compilepeace.medium.com/software-reverse-engineering-ripping-apart-bomb-binary-25cf63dc39d5"><strong>Software Reverse Engineering: Ripping Apart Bomb Binary</strong></a> (<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d"><strong>Software Reverse Engineering: Diffusing Phase 1</strong></a>(<strong>GNU GDB</strong>: Linux)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc"><strong>Software Reverse Engineering: Diffusing Phase 2</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec"><strong>Software Reverse Engineering: Diffusing Phase 3</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4"><strong>Software Reverse Engineering: Diffusing Phase 4 </strong></a>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c"><strong>Software Reverse Engineering: Diffusing Phase 5</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb"><strong>Software Reverse Engineering: Diffusing Phase 6</strong></a><strong> </strong>(<strong>GNU GDB</strong>: Linux)</li></ul><h3>Rescue Mission: Phase_6</h3><p>The disassembly for phase_6() is unsurprisingly long enough to be explained in a single shot. Let’s look disassembly for phase_6() (<strong>diass phase_6</strong>) to gain a broader coverage and subsequently digging into smaller fragments to gain clarity.</p><pre>0x000055555555585b &lt;+0&gt;: endbr64             <em>; </em><strong><em>CET instruction</em></strong></pre><pre><em>; </em><strong><em>callee saved regs</em></strong><br>0x000055555555585f &lt;+4&gt;: push   %r14         <br>0x0000555555555861 &lt;+6&gt;: push   %r13<br>0x0000555555555863 &lt;+8&gt;: push   %r12<br>0x0000555555555865 &lt;+10&gt;: push   %rbp<br>0x0000555555555866 &lt;+11&gt;: push   %rbx</pre><pre><em>; </em><strong><em>stack cookie trying to cover from stack corruption just in case</em></strong><br>0x000055555555586b &lt;+16&gt;: mov    %fs:0x28,%rax   <br>0x0000555555555874 &lt;+25&gt;: mov    %rax,0x58(%rsp)  <br>0x0000555555555879 &lt;+30&gt;: xor    %eax,%eax</pre><pre><strong><em>; read_six_numbers() taking input on top of stack<br></em></strong>0x000055555555587b &lt;+32&gt;: mov    %rsp,%r13       <em> </em><br>0x000055555555587e &lt;+35&gt;: mov    %r13,%rsi       <br>0x0000555555555881 &lt;+38&gt;:  call  0x555555555c11 &lt;<strong>read_six_numbers</strong>&gt;<br>...<br>0x0000555555555891 &lt;+54&gt;:  call  0x555555555be5 &lt;explode_bomb&gt;<br>...<br>0x00005555555558aa &lt;+79&gt;:  call  0x555555555be5 &lt;explode_bomb&gt;<br>...<br>0x00005555555558e0 &lt;+133&gt;: lea  0x3919(%rip),%rdx  # &lt;<strong>node1</strong>&gt;<br>0x00005555555558e7 &lt;+140&gt;: cmp   $0x1,%ecx<br>...<br>0x000055555555595a &lt;+255&gt;: call  0x555555555be5 &lt;explode_bomb&gt;<br>...<br>(more disassembly here)</pre><p>Function prologue shows compiler saving registers (callee-saved registers RBP, RBX, r12-r15 pushed onto the stack) for their use in this function, stack canary being placed, calling read_six_numbers(const char *ips, int *nums); which expects 6 integers as input placing them on top of stack and a few calls to explode_bomb() which we need to avoid. read_six_numbers() is the same routine that we reversed while <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc">diffusing phase 2</a>. Apart from that there is a symbol <strong>node1</strong> which indicates that the program probably uses some sort of <strong>aggregate data type</strong> (like linked list, hash table, tree, graph etc.). Let’s analyze this function in smaller fragments. Below is the pseudocode for this prologue.</p><pre>void phase_6 (const char *ips) {<br>    int nums[6];</pre><pre>    read_six_numbers (ips, nums);</pre><pre>...<br>}</pre><h3>First fragment of phase_6</h3><p>First approach to this output was to deduce which of the <strong>callee saved registers</strong> was used for what purposes. I guess stepping through the below disassembly is the quickest way to infer this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*VUSnUjW2hUIqcULo7qqxEg.png" /><figcaption>Iterative comparison among integer input</figcaption></figure><p>After stepping through the code and tracing some values, I could infer the following —</p><ul><li>registers RSP, RSI, R13, R12 and RBP point to the top of the stack.</li><li>RBX and R14d are used as counters.</li></ul><p>Below is the pseudocode I crafted for this fragment —</p><pre>// Variable <strong>i   </strong>is <strong>r14d</strong><br>// Variable <strong>ptr</strong> is <strong>r13</strong><br>// Variable <strong>j</strong>   is <strong>ebx</strong></pre><pre>int *ptr = &amp;nums[0], i = 1;<br>while ((unsigned int )(*ptr - 1) &lt;= 5) {    // phase_6+94</pre><pre>    if (i &gt; 5) {     // termination condition for this loop: r14d<br>         // phase_6+<strong>120<br>         ....</strong></pre><pre>    }</pre><pre>    // <strong>duplicate integer check</strong><br>    for (int j = i /* <strong>ebx = r14d</strong> */; j &lt;= 5; ++j) {            &#39;<br>        if (*ptr == nums[j]) {<br>             explode_bomb ();<br>        }        <br>    }                <br>    ++i;        // ++r14d<br>    ++ptr;      // (r13 += 4) <strong>modification expression for loop</strong></pre><pre>    explode_bomb();<br>}</pre><p>Yeah, we now encountered <strong>nested loops !</strong></p><p>The <strong>outer while loop</strong> iterates over the user supplied integers ensuring that the each of the input integer is in range <strong>[0–6]</strong> while the <strong>inner for loop </strong>ensures that there is no duplicate number supplied by user. Value of i is incremented to till 5 until which it checks for duplicate integers, but what’s after that ?</p><h3>Cheers to more !</h3><p>Using same approach, we deduce the purpose of some registers by tracing them while stepping through each instruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*PBuxHSTfI3nTKrRBn0uwPA.png" /><figcaption>reversing data structure in phase_6</figcaption></figure><p>This snippet of code seems to be working on a <strong>liked list</strong> where —</p><ul><li><strong>RSI</strong> is index into nodes[]</li><li><strong>EAX</strong> is count.</li><li><strong>ECX</strong> is current number from input integers.</li><li><strong>RDX</strong> points to the current node.</li></ul><pre>for (int rsi = 0 ; rsi != 6; ++rsi) {</pre><pre>    ecx = nums[rsi];    // user-supplied integer<br>    eax = 1;            // count<br>    rdx = head_node;    // initially points to the head node element</pre><pre>    if (ecx &gt; 1) {<br>        do {                // <strong>phase_6+145</strong><br>            rdx = rdx-&gt;next;<br>            ++eax;<br>        } while (ecx != eax);<br>    }</pre><pre>// store it into nodes[] array (on stack)<br>nodes[rsi] = rdx;<br>++rsi;<br>}</pre><pre>// link all nodes on stack (create a linked list)<br>nodes[0]-&gt;next = nodes[1];<br>nodes[1]-&gt;next = nodes[2]<br>nodes[2]-&gt;next = nodes[3];<br>nodes[3]-&gt;next = nodes[4];<br>nodes[4]-&gt;next = nodes[5];<br>nodes[5]-&gt;next = 0;</pre><p>Logically, the initial loop creates list nodes by iterating over the user supplied integers (nums[]) and subsequently putting it onto the allocated memory in stack segment (i.e. at <strong>nodes[]</strong> array). It then links all nodes together to form a linked list of user supplied integers (see phase_6+171).</p><p>A node structure is —</p><pre>struct node {    <br>    int data;           // ???? this is getting compared for checks<br>    int num;<br>    struct node *next;<br>}</pre><h3>So far, so good !</h3><p>Let’s look at the remaining disassembly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*4PlBwgqnLmIDAMYe4_WkOA.png" /></figure><p>After linking all nodes, let’s examine our how our nodes look like.</p><pre>(gdb) <strong>until *phase_6+171<br></strong>(gdb)<strong> x/10xg $rsp</strong><br>0x7fffffffdf90: 0x0000000200000001 0x0000000400000003<br>0x7fffffffdfa0: 0x0000000600000005 0x0000000000000000<br>0x7fffffffdfb0: <strong>0x0000555555559200</strong> <strong>0x0000555555559210</strong><br>0x7fffffffdfc0: <strong>0x0000555555559220 0x0000555555559230</strong><br>0x7fffffffdfd0: <strong>0x0000555555559240 0x0000555555559110</strong></pre><p>As we change the order of our input, we see the change in arrangement of these nodes which would are linked accordingly.</p><pre>(gdb) <strong>until *phase_6+171<br></strong>(gdb)<strong> x/10xg $rsp</strong><br>0x7fffffffdf90: 0x0000000400000005 0x0000000100000003<br>0x7fffffffdfa0: 0x0000000600000002 0x0000000000000000<br>0x7fffffffdfb0: <strong>0x0000555555559240</strong> <strong>0x0000555555559230</strong><br>0x7fffffffdfc0: <strong>0x0000555555559220</strong> <strong>0x0000555555559200</strong><br>0x7fffffffdfd0: <strong>0x0000555555559210</strong> <strong>0x0000555555559110</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*yJET8BrL0dntAFFe2OAZKg.png" /><figcaption>data values in each node</figcaption></figure><p>It seems that every number we enter from 1–6 is having predefined value for ‘data’ member. The data member of struct node is a value which we <strong>do NOT control</strong> but the order of arrangement of nodes is what <strong>we can control </strong>here, nodes should be created in descending order of their values stored in data member.</p><p>The instruction at phase_6+251 compares the value of in current node to that in the next node pointed to by the current node. It expects a descending order of their data value. If not given, the bomb explodes !</p><pre>0x0000555555555950 &lt;+245&gt;: mov    0x8(%rbx),%rax<br>0x0000555555555954 &lt;+249&gt;: mov    (%rax),%eax<br>0x0000555555555956 &lt;+251&gt;: cmp    %eax,(%rbx)</pre><p>Here are the values associated with each user input number:</p><pre>1: <strong>0x212<br></strong>2: <strong>0x1c2<br></strong>3: <strong>0x215<br></strong>4: <strong>0x393<br></strong>5: <strong>0x3a7<br></strong>6: <strong>0x200</strong></pre><p>Ordering them in from largest to smallest we get — 5 4 3 1 6 2 . Let’s try this sequence of input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*37BS4ZvACJeEnAhuvcgNZg.png" /><figcaption>phase_6 diffused x_x</figcaption></figure><h3>Pseudocode for phase_6()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*zLUJ4YxodOaEKsrYg5zgDQ.png" /><figcaption>Pseudocode for phase_6()</figcaption></figure><h3><strong>Epilogue</strong></h3><p>This challenge involved reverse engineering <strong>linked list </strong>(as well as its operations including creating, linking and comparing nodes)<strong> </strong>, <strong>nested loops </strong>and<strong> if-else code constructs</strong>. We also had to deal with understanding <strong>mathematical expressions</strong>, <strong>pointer arithemetic </strong>and deducing the usage of callee saved registers by tracing code flow. This is it for the night gentlemen, I guess we just saved the world !</p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><p>Connect on<strong> </strong><a href="https://www.linkedin.com/in/abhinav-thakur-795a96157/"><strong>Linkedin</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fc8293dbceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reverse Engineering: Diffusing Phase 5]]></title>
            <link>https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9da96eec2c</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 11:22:46 GMT</pubDate>
            <atom:updated>2022-04-11T11:40:51.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_XHLtRJNpWn39go6fwM5w.png" /></figure><blockquote>Baby, I hate little secrets you keep from me x_x</blockquote><p>The article continues the <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4">previous one</a> where we diffused phase 4 of bomb binary. Let’s get started with phase 5 on Windows platform using Windbg.</p><p>This writeup is a part of the article series —</p><ul><li><a href="https://compilepeace.medium.com/software-reverse-engineering-ripping-apart-bomb-binary-25cf63dc39d5"><strong>Software Reverse Engineering: Ripping Apart Bomb Binary</strong></a> (<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d"><strong>Software Reverse Engineering: Diffusing Phase 1</strong></a>(<strong>GNU GDB</strong>: Linux)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc"><strong>Software Reverse Engineering: Diffusing Phase 2</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec"><strong>Software Reverse Engineering: Diffusing Phase 3</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4"><strong>Software Reverse Engineering: Diffusing Phase 4 </strong></a>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c"><strong>Software Reverse Engineering: Diffusing Phase 5</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb"><strong>Software Reverse Engineering: Diffusing Phase 6</strong></a><strong> </strong>(<strong>GNU GDB</strong>: Linux)</li></ul><h3>Rescue Mission: Phase_5</h3><p>Looking at the disassembly for phase_5() (<strong>uf bomb!phase_4</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*I3TXHQ9Ejo5xgQRHmiGOKQ.png" /><figcaption>uf phase_5</figcaption></figure><p>We see a similar call for sscanf() while diffusing phase_4() . Let’s quicky have a look at the format string so that we know what type of user input it expects.</p><pre>0:001&gt; <strong>da 00007ff6`0377c220</strong><br>00007ff6`0377c220  <strong>&quot;%d %d&quot;</strong></pre><p>Nice, it expects 2 integers as input and stores them at [rbp+64] (let’s say a) and [rbp+84h] (let’s say b) respectively. If we enter 2 or more than 2 integer as inputs the program takes the jump — jge bomb!phase_5+0x79 (00007ff6`037724d9) otherwise it calls explode_bomb() .</p><pre>int a, b;</pre><pre>// rbp+0x1a0 is &amp;input_string[0]<br>if (sscanf ( input_string, &quot;%d %d&quot;, a, b) &lt; 2)<br>    explode_bomb();</pre><pre>a = a &amp; 0x0f;<br>if (a[0] == 0xf) explode_bomb();     // <strong>check #2</strong></pre><pre>[rbp+4] = [rbp+24] = 0;</pre><p><strong>check #2</strong> constraint forces the user to enter any value except 0xf (15) as the first integer in input string.</p><h3>Validating Input</h3><p>We now know where integer inputs are getting stored, [rbp+64h] is a and [rbp+84h] is b . We aim to reverse the below disassembly.</p><pre>202 00007ff6`037724f6   cmp   dword ptr [rbp+64h],0Fh<br>202 00007ff6`037724fa   je    bomb!phase_5+0xc4 (<strong>00007ff6`03772524</strong>)<br>...<br>208 <strong>00007ff6`03772524</strong>   cmp   dword ptr [rbp+4],0Fh<br>208 00007ff6`03772528   jne   bomb!phase_5+0xd5 (<strong>00007ff6`03772535</strong>)</pre><pre>208 00007ff6`0377252a   mov   eax,dword ptr [rbp+84h]<br>208 00007ff6`03772530   cmp   dword ptr [rbp+24h],eax<br>208 00007ff6`03772533   je    bomb!phase_5+0xda (00007ff6`0377253a)<br>...<br>209 <strong>00007ff6`03772535</strong>   call  bomb!ILT+945(explode_bomb)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Sd0okuuJLX2u83zoVarx-A.png" /><figcaption>A safe way out</figcaption></figure><p>We find a safe way out. To identify the inputs, we need to increment [rbp+4] until it reaches 0xf and peek into the value of [rbp+24] when the code flow reaches the SAFE EXIT.</p><p>There is one obstruction here, before reaching SAFE EXIT, it has to pass through if (a == 0xf) condition. The question now is —</p><p>How can a possibly store the value of 0xf after it passes check #2 (as seen before) ?</p><h4>Solving &#39;a&#39; mystery</h4><p>Demystifying more disassembly —</p><pre>203 00007ff6`037724fc   mov     eax,dword ptr [rbp+4]<br>203 00007ff6`037724ff   inc     eax<br>203 00007ff6`03772501   mov     dword ptr [rbp+4],eax<br>204 00007ff6`03772504   movsxd  rax,dword ptr [rbp+64h]<br>204 00007ff6`03772508   lea   rcx,[bomb!n1+0x20 (00007ff6`0377f1d0)]<br>204 00007ff6`0377250f   mov     eax,dword ptr [rcx+rax*4]<br>204 00007ff6`03772512   mov     dword ptr [rbp+64h],eax<br>205 00007ff6`03772515   mov     eax,dword ptr [rbp+64h]<br>205 00007ff6`03772518   mov     ecx,dword ptr [rbp+24h]<br>205 00007ff6`0377251b   add     ecx,eax<br>205 00007ff6`0377251d   mov     eax,ecx<br>205 00007ff6`0377251f   mov     dword ptr [rbp+24h],eax<br>206 00007ff6`03772522   jmp     bomb!phase_5+0x96 (00007ff6`037724f6) <strong>way_out</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*fydmlzLdOrXBNGs-b8QDKg.png" /><figcaption>Tr</figcaption></figure><p>Our pseudocode till now uses <strong>goto statements </strong>with <strong>labels</strong>. Let’s write a final pseudocode that replaces this <em>goto control-flow-transfers</em> into <strong>do-while</strong> loop code construct.</p><h3>Pseudocode for phase 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*u0yMVIxd1Zl_FDtkFlsEyQ.png" /><figcaption>Pseudocode for bomb!phase_5</figcaption></figure><p>This is how I managed to identify a<strong> do-while loop </strong>code construct. This loop <strong>increments</strong> [rbp+4] on each iteration and terminates using SAFE EXIT when a == 0xf . This is all we wanted, we just need to make sure that the loop iterates exactly 0xf times (i.e. expected value of [rbp+4] for SAFE EXIT) which depends on value of a .</p><h3><strong>Escape through the SAFE EXIT, fast !</strong></h3><p>To reach SAFE EXIT we need —</p><ul><li>To ensure that loop iterates exactly 0xf times. To control the number of iterations we need to control the value inside a.</li><li>Initial value of a is in our control whereas further value of a is controlled directly by value inside base[a].</li></ul><p>Therefore, the first integer we input (value of a) will act as an index into base[] after which the value read from base[a] will act as index for the next iteration (somewhat like base[base[a]]).</p><p>Let’s have a look at first 0xf values (that we can leverage to iterate the loop) at location base[].</p><pre>0:001&gt; <strong>dd 00007ff6`0377f1d0 Lf</strong><br>00007ff6`0377f1d0  0000000a 00000002 0000000e 00000007<br>00007ff6`0377f1e0  00000008 0000000c 0000000f 0000000b<br>00007ff6`0377f1f0  00000000 00000004 00000001 0000000d<br>00007ff6`0377f200  00000003 00000009 00000006</pre><p>We now need to <strong>chain the indices</strong> of these 15 values in such a way that 0x0000000f is indexed at last. A smart approach will be to start backwards, from value 0x0000000f itself. Remember, this value will mark as an index from this base (00007ff6`0377f1d0) itself. Initial value of a (index) will be 6 (base[5]).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*VKsWeFGtcdZoXHOYiPQMyQ.png" /><figcaption>Index Chain (reverse order)</figcaption></figure><p>Therefore, to reach value of 0xf after 15 iterations, we need to supply an initial value of index : a = 5 . Let’s supply value of a and break at instruction — 00007ff6`03772530 cmp dword ptr [rbp+24h],eax which compares [rbp+24h] with user-supplied integer in b (stored inside eax here). I am supplying a dummy string of <strong>5 7337</strong> to phase_5 as input. Let’s examine the value at [rbp+24] to find the exact value it compares with b .</p><pre>0:000&gt; <strong>.restart</strong><br>0:000&gt; <strong>bp bomb!phase_5</strong><br>0:000&gt; <strong>g</strong><br>0:000&gt; <strong>pa 00007ff6`03772530</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*-VD1-REhC0TEjqNA0V17Cw.png" /><figcaption>value for second integer input</figcaption></figure><p>There we see, it compares eax (0x1ca9 or 7337) with <strong>0x73</strong> (<strong>115</strong> in decimals). Let’s try giving this as input !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*ql9ShsLhn3V28abQ4kb5WQ.png" /><figcaption>phase_5 diffued x_x</figcaption></figure><p>Finally, we successfully diffuse phase_5() of bomb binary.</p><h3>Epilogue</h3><p>Phase 5 was more interesting than phase 4 that involved us to not only identify a <strong>do-while loop </strong>but also forced us to control the code flow of the loop by <strong>examining memory</strong> and <strong>analyzing </strong>how our input can effect the <strong>chain of memory reads </strong>to escape through a SAFE EXIT. <strong>Controlling code flow is the most important attribute of a true attacker</strong> x_x</p><p>Let’s continue right into the writeup for <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb">diffusing phase_6</a>.</p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><p>Connect on<strong> </strong><a href="https://www.linkedin.com/in/abhinav-thakur-795a96157/"><strong>Linkedin</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9da96eec2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reverse Engineering: Diffusing Phase 4]]></title>
            <link>https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4112619ac2b4</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 11:17:28 GMT</pubDate>
            <atom:updated>2022-04-11T11:39:49.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_XHLtRJNpWn39go6fwM5w.png" /></figure><blockquote>Baby, I hate little secrets you keep from me x_x</blockquote><p>The article continues the <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec">previous one</a> where we diffused phase 3 of bomb binary. Let’s get started with phase 4 on Windows platform using Windbg.</p><p>This writeup is a part of the article series —</p><ul><li><a href="https://compilepeace.medium.com/software-reverse-engineering-ripping-apart-bomb-binary-25cf63dc39d5"><strong>Software Reverse Engineering: Ripping Apart Bomb Binary</strong></a> (<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d"><strong>Software Reverse Engineering: Diffusing Phase 1</strong></a>(<strong>GNU GDB</strong>: Linux)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc"><strong>Software Reverse Engineering: Diffusing Phase 2</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec"><strong>Software Reverse Engineering: Diffusing Phase 3</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4"><strong>Software Reverse Engineering: Diffusing Phase 4 </strong></a>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c"><strong>Software Reverse Engineering: Diffusing Phase 5</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb"><strong>Software Reverse Engineering: Diffusing Phase 6</strong></a><strong> </strong>(<strong>GNU GDB</strong>: Linux)</li></ul><h3>Rescue Mission: Phase_4</h3><p>Looking at the disassembly for phase_4() (<strong>uf bomb!phase_4</strong>). We see sscanf() call exactly the same way as in phase_3() , i.e. expecting 2 integers. Therefore, we’ll be following an initial approach similar to <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec">previous phase</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*TKCjak1UWPjjsUfnR2MWWA.png" /><figcaption>uf phase_4</figcaption></figure><pre>0:001&gt; <strong>da 00007ff6`0377c220</strong><br>00007ff6`0377c220  &quot;%d %d&quot;</pre><h3>Validating user input</h3><p>Let’s statically analyze how it validates user input.</p><pre>0:001&gt; uf phase_4<br>...<br>135 00007ff6`037723c1  cmp  dword ptr [rbp+4],0<br>135 00007ff6`037723c5  jl   bomb!phase_4+0x7d (<strong>00007ff6`037723cd</strong>)  <br>135 00007ff6`037723c7  cmp   dword ptr [rbp+4],0Eh<br>135 00007ff6`037723cb  jle   bomb!phase_4+0x82 (00007ff6`037723d2)  <br>136 <strong>00007ff6`037723cd</strong>  call  bomb!ILT+945(explode_bomb) <br>...</pre><p>This simply says that user input should be — 0 &lt; [rbp+4] &lt; 0xe (14) (where [rbp+4] is first integer of user input) for bomb to not explode.</p><p>Next, we see a call to func4() whose return value decides whether bomb explodes or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*7Q3-XsAsgj81fW7_QLuZpA.png" /><figcaption>call site of func4()</figcaption></figure><ul><li>0x00007ff6`037723e9 to 0x00007ff6`037723f2 : return value (in eax) is checked against [rbp+64] (first integer input), if it isn’t equal explode_bomb() is called.</li><li>00007ff6`037723f4 to 00007ff6`037723fa : explodes bomb if [rbp+24] (second integer input) is not equal to [rbp+64]. We have to peek into rpb+64 to find out this value.</li></ul><pre>0:000&gt; <strong>dd rbp+64 L1</strong><br>00000038`b74ff974  <strong>0000000a</strong></pre><p>Therefore, we are sure that the correct value for second integer in input string is 10. The question is how can we make func4() return a value of 0xa ?</p><h3>Analyzing func4</h3><p>Let’s analyze what parameters it takes by stepping to call instruction for func4().</p><pre>0:001&gt; <strong>pa 00007ff6`037723e4<br></strong>0:000&gt; <strong>r rcx, rdx, r8</strong><br>rcx=<strong>0000000000000002</strong> rdx=<strong>0000000000000000</strong> r8=<strong>000000000000000e</strong></pre><p>which makes function prototype for func4 to be —</p><pre>int func4 (my_int, a, b);         // <strong>a</strong> = 0, b = <strong>0xe</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*hR7z05FEdyQZy7r8BlWyZg.png" /><figcaption>uf func4</figcaption></figure><p>This function references its parameters via RBP, a stack diagram therefore would give us more clarity over what it refers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*50tE6VA7Xo9XsJ9SQ8WE0Q.png" /></figure><p>Therefore, [rbp+100] is <strong>first </strong>parameter, whereas [rbp+108] and [rbp+110] are <strong>second </strong>and <strong>third </strong>parameter. First part of the disassembly does some math which should make sense after understanding the stack diagram —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*B4zDV0p4jNkw0nRrbwlp8A.png" /><figcaption>some math</figcaption></figure><pre>eax = (((signed qword typecast)(b - a)) - a)/2;<br>*(rbp+4) = ecx = a + eax</pre><p>[rbp+4] is then compared to first parameter of func4() (i.e. first integer in our input string). Accordingly, the corresponding block of code is executed.</p><pre>121 00007ff6`03771f75   <strong>cmp    dword ptr [rbp+4],eax</strong><br>121 00007ff6`03771f78   jle    bomb!func4+0x8a (<strong>00007ff6`03771f9a</strong>)<br><br>...<br>123 <strong>00007ff6`03771f9a</strong>   mov     eax,dword ptr [rbp+100h]<br>123 00007ff6`03771fa0   <strong>cmp     dword ptr [rbp+4],eax</strong><br>123 00007ff6`03771fa3   jge     bomb!func4+0xb5 (<strong>00007ff6`03771fc5</strong>)<br>else<br>124 00007ff6`03771fa5   mov     eax,dword ptr [rbp+4]<br>124 00007ff6`03771fa8   inc     eax<br>124 00007ff6`03771faa   mov     r8d,dword ptr [rbp+110h]<br>124 00007ff6`03771fb1   mov     edx,eax<br>124 00007ff6`03771fb3   mov     ecx,dword ptr [rbp+100h]<br>124 00007ff6`03771fb9   call    bomb!ILT+725(func4) (00007ff6`037712da)<br>124 00007ff6`03771fbe   add     eax,dword ptr [rbp+4]<br>124 00007ff6`03771fc1   jmp     bomb!func4+0xb8 (<strong>00007ff6`03771fc8</strong>)</pre><pre>...<br>126 <strong>00007ff6`03771fc5</strong>  mov     eax,dword ptr [rbp+4]    <strong>// BASE CASE</strong><br>127 <strong>00007ff6`03771fc8</strong>  lea     rsp,[rbp+0E8h]<br>127 00007ff6`03771fcf  pop     rdi<br>127 00007ff6`03771fd0  pop     rbp<br>127 00007ff6`03771fd1  ret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*dyE2E2cQDaYiL4C4-kN9Iw.png" /><figcaption>func4() base case and if code construct</figcaption></figure><p>Disassembly code for else case is as follows —</p><pre>122 00007ff6`03771f7a  mov     eax,dword ptr [rbp+4]<br>122 00007ff6`03771f7d  dec     eax<br>122 00007ff6`03771f7f  mov     r8d,eax<br>122 00007ff6`03771f82  mov     edx,dword ptr [rbp+108h]<br>122 00007ff6`03771f88  mov     ecx,dword ptr [rbp+100h]<br>122 00007ff6`03771f8e  <strong>call    </strong>bomb!ILT+725(<strong>func4</strong>) (00007ff6`037712da)<br>122 00007ff6`03771f93  add     eax,dword ptr [rbp+4]<br>122 00007ff6`03771f96  jmp     bomb!func4+0xb8 (<strong>00007ff6`03771fc8</strong>)<br>...<br>127 <strong>00007ff6`03771fc8</strong>  lea     rsp,[rbp+0E8h]<br>127 00007ff6`03771fcf  pop     rdi<br>127 00007ff6`03771fd0  pop     rbp<br>127 00007ff6`03771fd1  ret</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*gHaom4fQUfvR4AZhWh9cag.png" /><figcaption>func4() else code construct</figcaption></figure><p>Therefore, final pseudocode for func4 becomes —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*gC-HEmJkQO3AM9ddz0vWLQ.png" /><figcaption>Pseudocode for func4()</figcaption></figure><p><strong>NOTE</strong>: Disassembly of func4() for Linux version of bomb binary differs a bit from this one (generated by Microsoft’s VS compiler). You can find the pseudocode crafted for Linux version of bomb <a href="https://github.com/compilepeace/SYSTEM_PROGRAMMING/blob/master/NOTES/binary_bomb_lab/reversed_bomb_lab.c">here</a>.</p><h3>Understanding Reccursive Calls</h3><p>Below are a few attributes I observed while analyzing this function —</p><ul><li>There is a<strong> reccursive call</strong> to func4() with distinct 2nd and 3rd parameter (a and b) but constant 1st parameter (first integer from our input string).</li><li><strong>Base case</strong> for <strong>reccursion </strong>here is: <strong>*(rbp+4) == my_int .</strong></li><li>Mathematically the expression —((b-a)-a)/2 + a is evaluated (and stored in *(rbp+4))and compared with my_int . Depending on the value of my_int , the control flow is transfered for next func4() call.</li><li>Value inside a &amp; b can be controlled via value in my_int .</li></ul><p>Initially, the expression evaluates to a value of 7. My initial approach was to create a call tree to find a pattern , but as I created the first level …</p><pre><strong>func4 (x, 0, 14)</strong> [<strong>expr = 7</strong> (i.e. (14-0-0)/2 + 0)]<br>|<br>|<br>|-&gt; if(x &gt; 7): call func4(x, <strong>7+1</strong>, <strong>14</strong>): [<strong>expr = 7</strong> (i.e. (14-16)/2+8)]<br>|<br>|-&gt; if(x &lt; 7): call func4(x, <strong>0</strong>, <strong>7-1</strong>):  [<strong>expr = 3</strong> (i.e. (6-0)/2+0)]</pre><p>The second level (when x &lt; 7) returns us a value of 3, if we provide an integer of 3 as input it will fall into the base case (i.e. x == expr). The return value of 3 when added to initial evaluation of expression, i.e. 7 returns a value of <strong>10</strong>(i.e. eax += *(rbp+4); return eax; in the end of our func4() pseudocode) as needed by phase_4(). Let’s try a value of 3 as our input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*yP-Vqys6sN_z93rayT-vag.png" /><figcaption>phase_4 diffused</figcaption></figure><h3>Epilogue</h3><p>Phase 4 was interesting as it involved reverse engineering simple <strong>mathematical expressions</strong>, <strong>if-else code constructs, reccursion </strong>and drawing<strong> stack diagram </strong>as done for func4()&#39;s stack frame. Let’s continue right into the writeup for <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c">diffusing phase_5</a>.</p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><p>Connect on<strong> </strong><a href="https://www.linkedin.com/in/abhinav-thakur-795a96157/"><strong>Linkedin</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4112619ac2b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reverse Engineering: Diffusing Phase 3]]></title>
            <link>https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7d4d1846dec</guid>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 11:14:07 GMT</pubDate>
            <atom:updated>2022-04-11T11:38:11.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_XHLtRJNpWn39go6fwM5w.png" /></figure><blockquote>Baby, I hate little secrets you keep from me x_x</blockquote><p>The article continues the <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc">previous one</a> where we diffused phase 2 of bomb binary. Let’s get started with phase 3 on Windows platform using Windbg.</p><p>This writeup is a part of the article series —</p><ul><li><a href="https://compilepeace.medium.com/software-reverse-engineering-ripping-apart-bomb-binary-25cf63dc39d5"><strong>Software Reverse Engineering: Ripping Apart Bomb Binary</strong></a> (<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d"><strong>Software Reverse Engineering: Diffusing Phase 1</strong></a>(<strong>GNU GDB</strong>: Linux)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc"><strong>Software Reverse Engineering: Diffusing Phase 2</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec"><strong>Software Reverse Engineering: Diffusing Phase 3</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4"><strong>Software Reverse Engineering: Diffusing Phase 4 </strong></a>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c"><strong>Software Reverse Engineering: Diffusing Phase 5</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb"><strong>Software Reverse Engineering: Diffusing Phase 6</strong></a><strong> </strong>(<strong>GNU GDB</strong>: Linux)</li></ul><h3>Rescue Mission: Phase_3</h3><p>Looking at the disassembly for phase_3() (<strong>uf bomb!phase_3</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*bOGnnxXepsUXqWb1GCtXww.png" /><figcaption>uf bomb!phase_3</figcaption></figure><p>I’ve ommited some assembly instructions at the function prologue to hide unnecessary complexity. Anyways, we first need to figure out what kind of input does this function expect. Skimming through it, we find the first function call to sscanf() whose function prototype is —</p><pre>int sscanf(const char *<strong>str</strong>, const char *<strong>format</strong>, ...);</pre><p>If we somehow figure out the <strong>format string</strong> parameter for sscanfI(), we’ll know what input it is expecting from str (drawing stack diagram will confirm it right away that [rbp+160h] here refers to <strong>shadow store</strong> inside main stack frame where the user input string in stored by 1st instruction of phase_3()). As we can see just before the call to sscanf(), its parameters are filled in <strong>RCX, RDX, R8 and R9</strong> in the same order (remember <a href="https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-160#parameter-passing">Microsoft’s x64 calling conventions</a> discussed). Since we want to figure out format string parameter (*format), we need examine the string stored inside <strong>RDX </strong>register before the call to sscanf() as shown below —</p><pre>0:001&gt; uf bomb!phase_3<br>...<br>72 00007ff6`037721ed    lea  rdx,[bomb!`string&#39; (<strong>00007ff6`0377c220</strong>)]<br>72 00007ff6`037721f4    mov  rcx,qword ptr <strong>[rbp+160h]</strong><br>...</pre><pre>0:001&gt; <strong>da 00007ff6`0377c220</strong><br>00007ff6`0377c220  <strong>&quot;%d %d&quot;</strong></pre><p>Since this function expects us to pass 2 integers (as per the format string <strong>“%d %d”</strong> we saw). Let’s give this input and reach the call site of sscanf().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-_QHjV3Hf3v4UbHoFIRyhQ.png" /><figcaption>phase_3 input as per “%d %d”</figcaption></figure><pre>0:001&gt; <strong>.restart</strong><br>0:001&gt; <strong>.reload /f<br></strong>0:001&gt;<strong> bp bomb!phase_3<br></strong>0:001&gt;<strong> g<br></strong>0:001&gt;<strong> pa 00007ff6`037721fb<br></strong>0:000&gt; <strong>da rcx</strong><br>00007ff6`037802a0  <strong>&quot;1 3&quot;</strong></pre><p>Therefore, the call to sscanf() becomes —</p><pre>sscanf (user_input_string, &quot;%d %d&quot;, rpb+0x4, rbp+0x24);</pre><h3>Validating user input</h3><p>After sscanf(), the program checks if it returned 2 (confirming sscanf read 2 integers) and moves forward with validating user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*PF-pjHzZcdIbVznDScnqWg.png" /><figcaption>first integer validation</figcaption></figure><p>Interpreting above instructions, the bomb explodes if the first integer we give is greater than 7. This is followed by some unnecessary instructions which can be skipped over.</p><p><strong>NOTE</strong>: The <strong>ja</strong> instruction suggests that it is to perform an unsigned comparison in contrast to<strong> jg </strong>which would have indicated a signed comparison.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*FvI3dY4RSq5wsmkO0N1rTQ.png" /><figcaption>irrelevant to diffusing phase_3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*9hQvzLGhUAlm_V4tFthAQA.png" /><figcaption>second integer validation</figcaption></figure><p>According to above disassembly, again the bomb explodes if first integer entered by user is greater than 5. The instruction cmp dword ptr [rbp+44h],eax then compares the second integer (inside <strong>eax</strong>) with value at <strong>[rbp+44h] </strong>. Let’s display a DWORD (<strong>dd</strong>) value at [rbp+44h].</p><pre>0:000&gt; <strong>dd rbp+44 L1</strong><br>00000062`aacff3f4  <strong>ffffffe6</strong></pre><p>Since, <strong>0xffffffe6 </strong>is <strong>-26</strong> in signed decimal (i.e. <strong>2’s complement</strong> of <strong>0xffffffe6 </strong>). Therefore, the input becomes (num &lt; 5) -26</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*cm0fHmgGuw9OkrYRnb4ovQ.png" /><figcaption>phase_3 solved</figcaption></figure><p>Pseudocode for phase_3() disassembly is as follows —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*ADOwMeI2sNsXkfoaEUobtw.png" /><figcaption>Pseudocode for phase_3</figcaption></figure><h3>Epilogue</h3><p>While diffusing phase 3, we explored simple <strong>if-else code</strong> construct which involved dealing with <strong>signed/unsigned</strong> comparisons. Let’s continue right into the writeup for <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4">diffusing phase_4</a>.</p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><p>Connect on<strong> </strong><a href="https://www.linkedin.com/in/abhinav-thakur-795a96157/"><strong>Linkedin</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7d4d1846dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Reverse Engineering: Diffusing Phase 2]]></title>
            <link>https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc?source=rss-d9d941443ca6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5230300660dc</guid>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhinav Thakur]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 11:10:00 GMT</pubDate>
            <atom:updated>2022-04-11T11:37:21.843Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_XHLtRJNpWn39go6fwM5w.png" /></figure><blockquote>Baby, I hate little secrets you keep from me x_x</blockquote><p>The article continues the <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d">previous one</a> where we diffused phase 1 of bomb binary. Let’s get started with phase 2 on Windows platform using Windbg.</p><p>This writeup is a part of the article series —</p><ul><li><a href="https://compilepeace.medium.com/software-reverse-engineering-ripping-apart-bomb-binary-25cf63dc39d5"><strong>Software Reverse Engineering: Ripping Apart Bomb Binary</strong></a> (<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-1-827278fa489d"><strong>Software Reverse Engineering: Diffusing Phase 1</strong></a>(<strong>GNU GDB</strong>: Linux)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-2-5230300660dc"><strong>Software Reverse Engineering: Diffusing Phase 2</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec"><strong>Software Reverse Engineering: Diffusing Phase 3</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-4-4112619ac2b4"><strong>Software Reverse Engineering: Diffusing Phase 4 </strong></a>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-5-dd9da96eec2c"><strong>Software Reverse Engineering: Diffusing Phase 5</strong></a><strong> </strong>(<strong>Windbg</strong>:<strong> </strong>Windows)</li><li><a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-6-4fc8293dbceb"><strong>Software Reverse Engineering: Diffusing Phase 6</strong></a><strong> </strong>(<strong>GNU GDB</strong>: Linux)</li></ul><h3>Rescue Mission: Phase_2</h3><p>Looking at phase_2() call site, we see the return value of read_line() being passed to<strong> </strong>phase_2() as parameter. This is similar to how we called phase_1().</p><pre>0:001&gt; <strong>uf main</strong><br>...<br>84 00007ff6`03771b0d    <strong>call</strong>    bomb!ILT+460(<strong>read_line</strong>) <br>84 00007ff6`03771b12    mov     qword ptr [rbp+8],rax<br>85 00007ff6`03771b16    mov     rcx,qword ptr [rbp+8]<br>85 00007ff6`03771b1a    <strong>call</strong>    bomb!ILT+970(<strong>phase_2</strong>) (<strong>00007ff6`037713cf</strong>)<br>...<br>0:001&gt; <strong>.restart</strong><br>0:001&gt; <strong>.reload /f</strong><br>0:001&gt; <strong>bp bomb!phase_2</strong><br>0:001&gt; <strong>g</strong></pre><p>The program breaks at first instruction inside phase_2(). Let’s have a complete overview of disassembly for phase_2 (<strong>uf phase_2</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*ChhVYfIQoVywwrTFHnkhzQ.png" /><figcaption>uf bomb!phase_2</figcaption></figure><p>Here, call to read_six_numbers hints us that this function takes 6 integers as argument. Let’s supply 6 random numbers as input to this phase — 1 2 3 4 5 6 .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*hmzxpP2gxycwWhgSk0MHHQ.png" /><figcaption>phase_2 input: 6 numbers</figcaption></figure><p>The first useful instruction we encounter is call to <strong>read_six_numbers() </strong>. Let’s <strong>step to this address</strong> using pa &lt;address or symbol&gt; (that prints out every instruction it steps over on its way to address) and examine what parameters it takes. If you track a stack diagram carefully, the value in first parameter (RCX) points to the shadow store of caller stack frame, which is where our input string for phase_2 is stored and second parameter also points somewhere inside stack frame of <strong>phase_2() </strong>which could possibly be the space allocated for 6 integers (i.e. 24 bytes).</p><pre>0:000&gt; <strong>da rcx</strong><br>00007ff6`03780250  &quot;1 2 3 4 5 6&quot;<br>0:000&gt; <strong>dd rdx L6</strong><br><strong>00000016`e3f0f638</strong>  cccccccc cccccccc cccccccc cccccccc<br>00000016`e3f0f648  cccccccc cccccccc</pre><pre>0:000&gt; <strong>p</strong><br>0:000&gt; <strong>dd 00000016`e3f0f638 L6</strong><br>00000016`e3f0f638  0000000<strong>1</strong> 0000000<strong>2</strong> 0000000<strong>3</strong> 0000000<strong>4</strong><br>00000016`e3f0f648  0000000<strong>5</strong> 0000000<strong>6</strong></pre><p>We see our input integers being stored on callee stack frame in the same order. Now, we just need to figure out how is this input validated by the program.</p><pre>46 00007ff6`037720e7   mov    eax,4<br>46 00007ff6`037720ec   imul   rax,rax,0<br>46 00007ff6`037720f0   <strong>cmp</strong>    dword ptr <strong>[rbp+rax+28h]</strong>,<strong>1<br></strong>46 00007ff6`037720f5   je     bomb!phase_2+0x6c (<strong>00007ff6`037720fc</strong>)<br>47 00007ff6`037720f7   call   bomb!ILT+945(<strong>explode_bomb</strong>)<br>49 <strong>00007ff6`037720fc</strong>   mov    dword ptr [rbp+4],1</pre><p>Did you notice how this compare instruction performs an array access using a r/mX form (as explained previously). Step over to this intruction and examine that the address points to the first element of where our supplied input is stored on stack. It compares first number entered by us with integer 1.</p><pre>0:000&gt; <strong>dd rbp+rax+28 L1<br></strong>00000016`e3f0f638  00000001</pre><p>Luckily, we choose 1 as the first random number to input taking the jump to (avoiding call to bomb!phase_2+0x6c (<strong>00007ff6`037720fc</strong>) (avoiding call to explode_bomb()). First validation passed.</p><h3>Identifying Loop construct</h3><p>A loop is comprised mainly of 3 parts apart from its body. Below is the example for loop construct.</p><pre>for (<strong>Initialization expr</strong>; <strong>Termination Condition</strong>; <strong>modification expr</strong>) {<br>        // Loop <strong>body</strong><br>}</pre><p>Below we try to identify a loop construct from the below assembly.</p><pre>----------------- <strong>Loop Initialization Expression</strong> ------------------<br>0007ff6`037720fc    mov     dword ptr [rbp+4],1<br>00007ff6`03772103   jmp     bomb!phase_2+0x7d (<strong>00007ff6`0377210d</strong>)</pre><pre>----------------- <strong>Loop Modification Expression</strong> ------------------<br>00007ff6`03772105   mov     eax,dword ptr [rbp+4]<br>00007ff6`03772108   inc     eax<br>00007ff6`0377210a   mov     dword ptr [rbp+4],eax</pre><pre>------------------- <strong>Loop Termination Condition</strong> -------------------</pre><pre><strong>00007ff6`0377210d</strong>   cmp     dword ptr [rbp+4],6<br>00007ff6`03772111   jge     bomb!phase_2+0xa2 (<strong>00007ff6`03772132</strong>) [br=0]</pre><pre>------------------------ <strong>Loop Body </strong>------------------------------<br>00007ff6`03772113   movsxd  rax,dword ptr [rbp+4]<br>00007ff6`03772117   mov     ecx,dword ptr [rbp+4]<br>00007ff6`0377211a   dec     ecx<br>00007ff6`0377211c   movsxd  rcx,ecx<br>00007ff6`0377211f   mov     ecx,dword ptr <strong>[rbp+rcx*4+28h]</strong><br>00007ff6`03772123   <strong>shl     ecx,1</strong><br>00007ff6`03772125   cmp     dword ptr [rbp+rax*4+28h],ecx<br>00007ff6`03772129   je      bomb!phase_2+0xa0 (00007ff6`03772130)<br>00007ff6`0377212b   call    bomb!ILT+945(explode_bomb) <br>00007ff6`03772130   jmp     bomb!phase_2+0x75 (00007ff6`03772105)</pre><pre><strong>00007ff6`03772132</strong> ---&gt; return to caller</pre><p>Some points to note:</p><ul><li><strong>shl</strong> instruction is generated by Microsoft VS compiler when performing multiplication of usually an <strong>unsigned integer</strong> by a <strong>power of 2</strong> (otherwise imul instruction is used). Here shl ecx,1 essentially multiplies ecx by 2.</li><li><strong>[rbp+rcx*4+28h]</strong> is performing <strong>array access</strong> using r/mX form <strong>[base +index*scale + displacement] </strong>as explained earlier.</li></ul><p>Pseudocode for this code construct may be —</p><pre>void phase_2 (const char *ips) {<br>    int nums[6];   // user input is stored here<br>    int i;         // &#39;i&#39; is essentially [rbp+4]</pre><pre>    read_six_numbers (ips, a);</pre><pre>    for (i = 1; i &lt; 6; ++i) {<br>         if ((num[i-1] * 2) != num[i])<br>             explode_bomb();<br>    }<br>}</pre><p>This loop construct ensures that user enter numbers in an <strong>ascending order</strong> such that <strong>every integer we enter is double of the preceeding integer</strong> while the<strong> sequence starts with integer 1</strong>. Therefore, the valid input for phase_2() becomes <strong>1 2 4 8 16 32 </strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*YRzuVSmOzA_v09_9MAkvog.png" /></figure><h3>Pseudocode for read_six_numbers (Optional)</h3><p>Below is the disassembly for read_six_numbers().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*7clou-dEBo5OzieaeE9IRQ.png" /><figcaption>uf read_six_numbers</figcaption></figure><p>We should now be able to reverse this simple disassembly. Below is the pseudocode for your reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*5dRZh5OySkNTRhq_C_SPfQ.png" /></figure><h3>Epilogue</h3><p>While diffusing phase 2, we explored how Microsoft compiler makes use of r/mX form to performs memory access and how to identify a loop construct in the given assembly. Let’s continue right into the writeup for <a href="https://compilepeace.medium.com/software-reverse-engineering-diffusing-phase-3-f7d4d1846dec">diffusing phase_3</a>.</p><p>Cheers,<br><strong>Abhinav Thakur<br><em>(a.k.a </em></strong><a href="https://github.com/compilepeace"><strong><em>compilepeace</em></strong></a><strong><em>)</em></strong></p><p>Connect on<strong> </strong><a href="https://www.linkedin.com/in/abhinav-thakur-795a96157/"><strong>Linkedin</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5230300660dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>