<?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 Wambui Ngige ツツ on Medium]]></title>
        <description><![CDATA[Stories by Wambui Ngige ツツ on Medium]]></description>
        <link>https://medium.com/@wambui-ngige?source=rss-750b60a32819------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xVOVQgw23VpISzO-QdBEiA@2x.jpeg</url>
            <title>Stories by Wambui Ngige ツツ on Medium</title>
            <link>https://medium.com/@wambui-ngige?source=rss-750b60a32819------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:58:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wambui-ngige/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[Patch Diffing .msu files]]></title>
            <link>https://wambui-ngige.medium.com/cve-2019-1388-root-cause-analysis-56f21080fedd?source=rss-750b60a32819------2</link>
            <guid isPermaLink="false">https://medium.com/p/56f21080fedd</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[cve]]></category>
            <category><![CDATA[patch-diffing]]></category>
            <category><![CDATA[vulnerability-research]]></category>
            <dc:creator><![CDATA[Wambui Ngige ツツ]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 11:12:51 GMT</pubDate>
            <atom:updated>2024-05-31T15:15:02.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! If you’ve just stumbled upon this post and you’re wondering, “What on earth is patch diffing?” I’ve got you. For the longest time, I’d hear people throw the term around and it sounded super complicated. But fear not, we’re here to break it down together. In simple terms, patch diffing is all about spotting the differences between two versions of code to see what was changed, often to fix a vulnerability. Think of it like finding out where a band-aid was placed to help something ‘broken’ heal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*7fXhshEAE_zI2a-9mPSyvA.png" /></figure><p>When software vendors find vulnerabilities in their products, they update the faulty code or add safeguards to catch any sneaky ways their code is being exploited. This could be as simple as adding a new exception handler or an if statement, or as complex as changing the implementation logic entirely. Basically, they’re patching things up to ensure everything runs smoothly and securely.</p><p>To demonstrate this, I’ll be using a patch diff I did on a root cause analysis of CVE-2019–1388. This experiment was done on Windows 7 SP1.</p><p>CVE-2019–1388 is a privilege escalation vulnerability that exists in the Windows Certificate Dialog where user privileges are not properly enforced therefore enabling attackers to launch a highly-privileged web browser on the normal desktop. This can be leveraged to execute code in the context of SYSTEM.</p><p>After some probing, I found that this vulnerability was fixed by a patch to a dll called cryptui.</p><h4>How do we find the patched binary?</h4><p>We have to find a vulnerable version of <em>cryptui.dll </em>such as the one in the Windows 7 SP1 machine we used to test earlier as well as a version of the same dll after it was patched. Ideally, you’d want to find the one that came right after the vulnerability was patched so that you don’t have a lot of diffed functions to sort through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*ZR2LfvBlFB9MGUR9LldKcQ.png" /><figcaption>Unpatched cryptui.dllSet</figcaption></figure><ol><li>Search for the CVE on msrc and find the ‘security only’ download for the OS version you are looking into (Windows 7 SP1 in our case)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*UUIS9sPRvgLj3sGiGTrWtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*B7JkvbXboKk2TXFP9gwByg.png" /></figure><ul><li>Make sure you download the update for the right architecture</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*xI3BcpBw2k3ACDK9DSbttw.png" /></figure><p>What we’ve downloaded is a .msu file. This is a microsoft update file — how windows packages it’s updates.</p><p>2. On a windows machine, using powershell, we’re going to use a tool called <strong>expand </strong>(it comes out of the box) to extract our update. Remember, we’re looking for an updated <em>cryptui.dll.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGVDIkObwXyHWYCrLopaFg.png" /></figure><pre>Syntax:<br>      expand —F:* &lt;. msu file&gt; &lt;dest&gt;</pre><p>At the end of this process we need to see an actual dll. This output has a number of files none of which are dlls. We’re interested in the .cab file here because it contains several compressed files in it. How do I know this? Google. So let’s repeat the same process to extract the contents of the .cab file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*dgpDFJYlSJLoPx2GhnqfzQ.png" /><figcaption>extracting contents of the .cab file</figcaption></figure><p>Once all the files have been extracted, we can look through the output for our dll of interest. Be mindful of the architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*FioVBwSkQYZIlkijwlwe4w.png" /></figure><p>We got a hit!</p><p>The next step is to check if our new file has a <strong>later and close</strong> version number to the cryptui.dll in our victim machine before we start diffing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*c6-gE6fY8mXLrOHfi8dFHA.png" /></figure><h4>Great, so how do we perform a patch diff on these two binaries?</h4><ol><li>Load the <strong><em>unpatched</em></strong> binary onto IDA, wait for the analysis to finish then save the idb. Close.</li><li>Load the <strong><em>patched</em></strong> binary onto IDA, wait for the analysis to finish.</li><li>Click File → BinDiff.</li><li>Wait for IDA to finish diffing the two binaries.</li><li>Examine the matched functions tab and sort from least similar.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pCJOcnmqdZW9gTqVdE2Xg.png" /><figcaption>Least similar function: ViewPageGeneral()</figcaption></figure><p>Right click on the least similar function and Click View Flow Graphs to open an instance of Visual Bindiff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*NYh_L0Nr9K_EokGYltmWHQ.png" /><figcaption>View flow graphs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BP1OmFUGu2OVPyteYFGlQw.png" /><figcaption>Visual representation of our diff (the yellow box).</figcaption></figure><p>The function highlighted in yellow is our patch and here’s the assembly code when you click on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*FoOCGGkfmzt91wO2T1K5WQ.png" /></figure><p>And that’s it! Now you can go about reverse engineering your patch to figure out how the vulnerability was fixed. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56f21080fedd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Analysis of Windows Exploit Mitigations —  Import Address Filtering.]]></title>
            <link>https://wambui-ngige.medium.com/dynamic-analysis-of-windows-exploit-mitigations-import-address-filtering-16fc28029529?source=rss-750b60a32819------2</link>
            <guid isPermaLink="false">https://medium.com/p/16fc28029529</guid>
            <category><![CDATA[windows-api]]></category>
            <category><![CDATA[iaf]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[windbg]]></category>
            <category><![CDATA[exploit-mitigation]]></category>
            <dc:creator><![CDATA[Wambui Ngige ツツ]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 17:27:12 GMT</pubDate>
            <atom:updated>2025-09-15T22:47:59.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laying the Groundwork: Parsing PE Files to Understand Windows Exploit Mitigations.</h3><p><em>~ I set out to study Import Address Filtering… got lost in PE Structures instead.</em></p><p>A few months ago, I was trying to figure out how EDRs and Defender work — in a general sense, when I came across a <a href="https://windows-internals.com/an-exercise-in-dynamic-analysis/">post by Yarden</a>. She was analyzing an Exploit mitigation technique. It got me thinking.. why not analyze individual security mitigations rather than the entirety of it ?? Because this was something I’d never done before, and EDRs have so many working parts that felt very intimidating to get into all at once, breaking down the process in this way made the whole process feel A LOT less daunting.</p><p>In this post, we go as far as understanding what executables are, what PE structures look like, how to parse though them as well as how to enable exploit mitigations in Windows.</p><p>A few questions that came to mind when trying to understand this Mitigation were:</p><ol><li>What is an executable?</li><li>What exactly are Imports?</li><li>Where are Imports located within an exe?</li><li>How can Imports be abused?</li><li>So what then is Import Address Filtering and how can we see this mitigation in action?</li><li>How does Windows protect the Import Address Table?</li><li>What happens if the mitigation isn’t enabled?</li></ol><p><strong>TL;DR</strong></p><p>Microsoft classifies certain functions as critical than others. When calls to these functions are made, they are detoured through inspection modules such as PayloadRestrictions.dll which enables exploit guard to perform checks. If all is good, control is passed back to the critical function, else an exception is raised which terminates the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-exDd6uOjtFwFoS08yroA.png" /><figcaption>How Payloadrestrictions.dll intercepts function execution</figcaption></figure><p>Before we can get into Import Address filtering, we need to do some housekeeping and understand a few things.</p><p>I believe, that you can’t really get into exploitation or mitigation of the said exploit if you don’t really understand your target platform.</p><p>In this case, our target platform is a windows executable so we need to know a few things about Portable Executable structures as well as how they are loaded into memory. Feel free to skip this part if you are already familiar with it.</p><h3>What is an executable?</h3><h4>PE Internals — Exploring the PE structure with respect to Imports</h4><p>The first thing I thought when I saw the name of this mitigation was what exactly is an import address? Where is it located exactly within an executable and how can I get to it? Do I even know what a PE structure looks like and how do PE Structures relate to one another?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*9swMz2F-RHjOqKRABFEyIA.png" /><figcaption>PE structure image by Corkami: <a href="https://github.com/corkami/pics/blob/master/binary/pe101/pe101.pdf">https://github.com/corkami/pics/blob/master/binary/pe101/pe101.pdf</a></figcaption></figure><p>For demonstration purposes, I’m using calc.exe and loading it onto <a href="https://github.com/hasherezade/pe-bear">PE Bear</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*YV-gSXnjmRtomCovI3nEHA.png" /><figcaption>calc.exe binary on PE Bear</figcaption></figure><p>An executable is made up of a bunch of parts that can be divided into two main ones:</p><ol><li><strong>Headers</strong>— Contains information about different parts of the exe. Think of it like the table of contents at the start of a book that tells you what is where within that book.</li><li><strong>Sections </strong>— This is the actual contents of your exe. Think of it as the actual chapters of the book that contains all the information you’re trying to read.</li></ol><h3>What exactly are Imports?</h3><p>Applications that run on the Windows OS utilize user mode as well as kernel mode APIs in order to access resources, memory, data or whatever they may need from the OS. As a developer writing a windows application, are you’re gonna be thinking about what APIs you can utilize to achieve certain tasks.</p><p>These APIs are however native to the OS and so your application will, shall I say, borrow some functions from Windows.</p><p>Windows does this by lending libraries and loading them into the application <strong><em>at runtime. </em></strong>Hence the name Dynamically Linked Libraries (DLL).</p><p>These dlls further, are <em>a collection of functions that achieve certain tasks.</em> So, your application imports dlls so it can utilize functions within them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*sKfq5m8AJ92e61Z5OThxvg.png" /><figcaption><em>Illustration of how exes call dlls which then lend them functions</em></figcaption></figure><h3>Where are Imports located within an executable?</h3><p>Simple answer, within the Data Directory Imports Directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUd5vsEdOcQ_m6sY1j2ZMA.png" /><figcaption>Import Directory of calc.exe on CFF Explorer.</figcaption></figure><p><strong><em>So how do we arrive at our imports — Practically?</em></strong></p><p>At this point I should mention that all these headers are just structures and our PE is a large structure that contains a bunch of other structures within it. So, For us to arrive at our Imports we need to traverse certain structures.</p><p>I sketched up the diagram below to kind of show you an overview of the different structures we’re gonna parse through in order to get to not only our imports but the functions our imports export.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etwEwJPCr2LiiyNPcUZ4_Q.png" /><figcaption>Parsing PE structures to get to our IAT</figcaption></figure><p>The flow:</p><p><em>Dos Header (e_lfanew) → Nt Headers → Image Optional Header → Image Data Directory → Image Import Descriptor → Image Import By Name</em></p><ul><li>Get the address of <em>e_lfanew</em> within the DOS Header structure because it’s the same as the address of NT Headers.</li><li>Within the NT Headers structure, access the Image Optional Header structure.</li><li>Access the Image Data Directory structure which is an array of structures and get the relative address of the import directory</li><li>Read it’s Name from the Image Import Descriptor structure.</li></ul><p>To briefly describe the structures in the diagram above:</p><ol><li><strong><em>DOS Header(IMAGE_DOS_HEADER)</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*a5zbxMhz_aYdL3_F09NFtQ.png" /><figcaption>DOS Header structure</figcaption></figure><p>This is the start of a PE file. Contains a bunch of information relevant to the loader but what were going to focus on here is the <em>e_lfanew</em> value that indicates the start of the NT headers.</p><p><strong><em>2. NT Headers (IMAGE_NT_HEADERS)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ZuKb0TFG76VBzrfNDwZ_OQ.png" /></figure><p>There’s two of these structures — 32-bit and 64-bit, the main difference being the optional header structure used by each.</p><p>It contains a signature member as well as a FileHeader. What we’re keen on in this structure, is the OptionalHeader structure that’s going to lead us to the IMAGE_OPTIONAL_HEADER structure.</p><p><strong><em>3. Optional Header IMAGE_OPTIONAL_HEADER</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*r_gu1lVKuRo5jCw9XFGY3w.png" /></figure><p>The IMAGE_OPTIONAL_HEADER<strong><em> </em></strong>structure contains an array of structures called the IMAGE_DATA_DIRECTORY that is relevant to us arriving to our imports. This array is a constant that holds the number of Data Directory structures that can only be a maximum of 16 as is defined in winit.h</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*GWAm-ID5JiNDDdXlF1VmeQ.png" /></figure><p><strong><em>4. Data Directory IMAGE_DATA_DIRECTORY</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*QfNjfzM193aOApBvPJz8tg.png" /></figure><p>It’s a small structure that’s made up of two members : an RVA to the start of the Data Directory in memory and the size of the Data Directory.</p><blockquote>*RVA stands for Relative Virtual Address (we’ll use this quite a bit) and it refers to the address of a file in relation to the base address of the image.</blockquote><p>A Data Directory contains information on a bunch of data directories in it such as the import directory, export directory etc. The image below is a great example to show you the Data Directories look like as well as their RVAs, Size and section (where they’re actually located in memory)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*6cllnIeVWx6csvSDtn00fw.png" /><figcaption>Data Directories in CFF explorer</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*GVZbx7sGeljjQ63MHL9qBg.png" /><figcaption>The same Data Directories RVA and sizes on PE Bear</figcaption></figure><p>5. <strong><em>Import Descriptor (IMAGE_IMPORT_DESCRIPTOR)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*TX4CM320u1_sxSG31QITOA.png" /></figure><p>What’s relevant here is the OriginalFirstThunk and the FirstThunk. The OriginalFirstThunk is an RVA that points to an array of IMAGE_THUNK_DATA struct. One exists for each imported function. We get our exported function names from here.</p><p>The FirstThunk on the other hand is an RVA that points to an array of IMAGE_THUNK_DATAs. These are also RVAs, one for each imported function. We get addresses of exported functions here.</p><h3>Parsing PE Imports.</h3><p>It’s important to put all this theoretical knowledge to practice so let’s write a POC to parse these headers. In the interest of time, I borrowed this POC from <a href="https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++">ired.team</a> and edited a few things to make it relevant to the Import Address table rather than all the PE headers.</p><p>As a side note, I really thought parsing imports would be enough to trigger the mitigation because the definition implies as much but that wasn’t the case as you’ll soon see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*KOHuPFpoCJli7xiWjlJgqg.png" /><figcaption>IAF defiinition under Exploit Protection settings.</figcaption></figure><p>The application takes one argument — an executable whose IAT we want to parse.</p><pre>#include &quot;Windows.h&quot;<br>#include &lt;iostream&gt;<br>int main(int argc, char* argv[]) {<br> const int MAX_FILEPATH = 255;<br> char fileName[MAX_FILEPATH] = { 0 };<br> memcpy_s(&amp;fileName, MAX_FILEPATH, argv[1], MAX_FILEPATH);<br> HANDLE file = NULL;<br> DWORD fileSize = NULL;<br> DWORD bytesRead = NULL;<br> LPVOID fileData = NULL;<br> PIMAGE_DOS_HEADER dosHeader = {};<br> PIMAGE_NT_HEADERS imageNTHeaders = {};<br> PIMAGE_SECTION_HEADER sectionHeader = {};<br> PIMAGE_SECTION_HEADER importSection = {};<br> IMAGE_IMPORT_DESCRIPTOR* importDescriptor = {};<br> PIMAGE_THUNK_DATA thunkData = {};<br> DWORD thunk = NULL;<br> DWORD rawOffset = NULL;<br>// open file<br> file = CreateFileA(fileName, GENERIC_ALL, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);<br> if (file == INVALID_HANDLE_VALUE) printf(&quot;Could not read file&quot;);<br>// allocate heap<br> fileSize = GetFileSize(file, NULL);<br> fileData = HeapAlloc(GetProcessHeap(), 0, fileSize);<br>// read file bytes to memory<br> ReadFile(file, fileData, fileSize, &amp;bytesRead, NULL);<br>// IMAGE_DOS_HEADER<br> dosHeader = (PIMAGE_DOS_HEADER)fileData;<br>// IMAGE_NT_HEADERS<br> imageNTHeaders = (PIMAGE_NT_HEADERS)((DWORD)fileData + dosHeader-&gt;e_lfanew);<br>// get offset to first section headeer<br> DWORD sectionLocation = (DWORD)imageNTHeaders + sizeof(DWORD) + (DWORD)(sizeof(IMAGE_FILE_HEADER)) + (DWORD)imageNTHeaders-&gt;FileHeader.SizeOfOptionalHeader;<br> DWORD sectionSize = (DWORD)sizeof(IMAGE_SECTION_HEADER);<br>// get offset to the import directory RVA<br> DWORD importDirectoryRVA = imageNTHeaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;<br>// print section data<br> for (int i = 0; i &lt; imageNTHeaders-&gt;FileHeader.NumberOfSections; i++) {<br>  sectionHeader = (PIMAGE_SECTION_HEADER)sectionLocation;<br>// save section that contains import directory table<br>  if (importDirectoryRVA &gt;= sectionHeader-&gt;VirtualAddress &amp;&amp; importDirectoryRVA &lt; sectionHeader-&gt;VirtualAddress + sectionHeader-&gt;Misc.VirtualSize) {<br>   importSection = sectionHeader;<br>  }<br>  sectionLocation += sectionSize;<br> }<br>// get file offset to import table<br> rawOffset = (DWORD)fileData + importSection-&gt;PointerToRawData;<br>// get pointer to import descriptor&#39;s file offset.<br> //importdescriptor offset = imageBaseAddress + pointerToRawDataOfTheSectionContainingRVAofInterest + (RVAofInterest - SectionContainingRVAofInterest.VirtualAddress)<br> importDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(rawOffset + (imageNTHeaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress - importSection-&gt;VirtualAddress));<br>printf(&quot;\n******* DLL IMPORTS *******\n&quot;);<br> for (; importDescriptor-&gt;Name != 0; importDescriptor++) {<br>  // imported dll modules<br>  printf(&quot;\t%s\n&quot;, rawOffset + (importDescriptor-&gt;Name - importSection-&gt;VirtualAddress));<br>  thunk = importDescriptor-&gt;OriginalFirstThunk == 0 ? importDescriptor-&gt;FirstThunk : importDescriptor-&gt;OriginalFirstThunk;<br>  thunkData = (PIMAGE_THUNK_DATA)(rawOffset + (thunk - importSection-&gt;VirtualAddress));<br>// dll exported functions<br>  for (; thunkData-&gt;u1.AddressOfData != 0; thunkData++) {<br>   // checking if the function is imported via its ordinal number<br>   if (thunkData-&gt;u1.AddressOfData &gt; 0x80000000) {<br>    //show lower bits of the value to get the ordinal<br>    printf(&quot;\t\tOrdinal: %x\n&quot;, (WORD)thunkData-&gt;u1.AddressOfData);<br>   }<br>   else {<br>    printf(&quot;\t\t%s\n&quot;, (rawOffset + (thunkData-&gt;u1.AddressOfData - importSection-&gt;VirtualAddress + 2)));<br>   }<br>  }<br> }<br>return 0;<br>}<br>--&gt; Edited from: https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/pe-file-header-parser-in-c++</pre><p>The output from running this parser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*67pmkxCnPFUZ_450um-ZhQ.png" /></figure><p>Output: DLLs imported and functions exported from them.</p><h3>So what then is Import Address Filtering and how can we see this mitigation in action?</h3><p>According to Microsoft,</p><blockquote>Import Address Filtering is a windows exploit mitigation technique that prevents a malicious executable from tampering with the Import Address Table of other applications.</blockquote><p>And from what we know so far, an Import address table is an array of pointers that contains dynamic addresses of libraries an applications imports at runtime.</p><p><strong><em>Enabling Import Address Filtering.</em></strong></p><p>Windows Security → App &amp; browser control → Exploit protection settings → Program settings → Add program to customize (calc.exe)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5IzGKMk8xTGyID0vBeZbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*ToVHm27Njmn_XMtEnqoAag.png" /></figure><p>Apply settings then run calc.exe under a debugger — WinDbg. Among the modules loaded is <em>PayloadRestrictions.dll</em>. Without IAF enabled (or any other exploit mitigation at that), the module won’t be loaded into the exe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*9tZmKPRH3jlm0UjTJS-Klg.png" /></figure><p>Hit g after the debugger breakpoint is hit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9I1SLExLw0cjZk4jyXcrQ.png" /></figure><p>Program runs to completion without triggering the mitigation which means that at no point did anything that’s deemed suspicious try to access the IAT .</p><h3>How can the Import Address Table be abused?</h3><p>Now that we know what the Import Address Table is, how can an adversary leverage it to achieve malicious code execution?</p><p>Imagine a scenario where an adversary “tricks” a legitimate executable into loading and executing functions from an illegitimate dll. One way this can be achieved is by adding an illegitimate dll to this executable’s IAT at run time.</p><p>This post is getting really long as it is so we’ll cover triggering the mitigation as well as examining how it actually works in the next post. I hope that you at least got a basic understanding of what an executable is under the hood as well as how to interact with different structures within it.</p><p>:) :)</p><h4>Links &amp; Resources:</h4><p>Corkami PE 102: <a href="https://raw.githubusercontent.com/corkami/pics/master/binary/pe102/pe102.pdf">https://raw.githubusercontent.com/corkami/pics/master/binary/pe102/pe102.pdf</a></p><ul><li><a href="http://sandsprite.com/CodeStuff/Understanding_imports.html">Understanding the Import Address Table</a></li><li><a href="https://www.ired.team/offensive-security/code-injection-process-injection/import-adress-table-iat-hooking">Import Adress Table (IAT) Hooking | Red Team Notes</a></li><li><a href="https://0xrick.github.io/win-internals/pe8/#parsing-imports">A dive into the PE file format - LAB 1: Writing a PE Parser</a></li><li><a href="https://windows-internals.com/an-exercise-in-dynamic-analysis/">An Exercise in Dynamic Analysis</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16fc28029529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Analysis of JScript/VBScript Malware]]></title>
            <link>https://wambui-ngige.medium.com/dynamic-analysis-of-jscript-vbscript-malware-f02a8de923d?source=rss-750b60a32819------2</link>
            <guid isPermaLink="false">https://medium.com/p/f02a8de923d</guid>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[windows-internals]]></category>
            <category><![CDATA[x32dbg]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[windows-api]]></category>
            <dc:creator><![CDATA[Wambui Ngige ツツ]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 17:46:55 GMT</pubDate>
            <atom:updated>2022-09-27T22:37:45.451Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an experiment I did a while back when I started learning Windows Internals. I didn’t really know how debug anything. It was really challenging at the time but now looking back, I think it was a really nice place to start for a complete noob who’s trying to understand how to use a debugger, interact with a little assembly as well as see Windows APIs in action. This is not going to be your typical kind of blog, rather, a somewhat organized write-up of my train of thought borrowed from my notes.</p><p>For this experiment, that I highly credit <a href="https://www.youtube.com/watch?v=uqhBsWXUw7Q">OALabs</a> for, I’m using a java script malware sample to understand how malware works as well as how Windows APIs are interpreted in the Windows environment. This sample doesn’t have much obfuscation on it so analyzing it is pretty straightforward as you’ll see :)</p><p>Tools required:</p><ul><li>x32dbg / x64dbg depending on what architecture you’re using.</li></ul><p>Download the sample from the link below and run it on an virtual machine environment that is completely sandboxed (as you should when running unknown malware). Refer to <a href="https://www.malwaretech.com/2017/11/creating-a-simple-free-malware-analysis-environment.html">this blog</a> if you don’t know how to set up a malware analysis environment.</p><h4><strong>How scripts are interpreted in Windows.</strong></h4><p>Before we try and analyze our script, we need to understand how our script will be executed in our Windows environment. This way, we can try and follow it’s execution later on with some sort of bird’s eye view of what to expect.</p><ul><li>When javascript or vbscript is ran in the MS Office environment as an embedded macro (think of a phishing email with an office document that has malicious vbscript embedded into it), it’s interpreted using the wscript.exe engine, an executable, which calls out to respective Windows APIs on behalf of the script depending on what the script is tasked to do. → What I’m saying in so many words is that MSOffice doesn’t actually run your scripts, it passes it on to wscript.exe for that purpose.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*fXzvZSzzoebIT23Kp4k4xg.png" /></figure><ul><li>Most scripts embedded into office macros can not do much other than download the actual malware that will establish initial access to a victim. This is because of size restrictions, spam filters (if this document was sent as a phishing email) and of course windows defender flagging it as malicious as soon as it’s downloaded by the unsuspecting victim onto disk.</li></ul><p>For these reasons, wscript.exe is our executable of interest for analysis.</p><p>Cool, so now what? A good starting point would be to look at dlls imported by wscript.exe and try to find any that establish internet connection (to download the actual executable) or any that could possibly be used to execute a payload (once the executable is downloaded).</p><blockquote>TLDR; A dll in layman’s terms is a library that is imported (or exported) at run time by an executable in order to ‘borrow’ functionality or give it to another executable (if it’s exported).</blockquote><p>This is where our debugger comes in. But before we get into that, lets actually figure out what dlls we need to look for. A simple google search would lead you to look at <em>shell32.dll</em> and <em>ws2_32.dll</em> as the most commonly abused dlls in our scenario. There are others of course but these two are a great start.</p><p>What we know about the two dlls at this point based on what functionality we assume our script may need:</p><ul><li><strong><em>ws2_32.dll</em></strong> is an internet/socket connection dll for windows that contains the Windows Sockets API. Some of it’s features include: <br>- Resolving hostnames.<br>- Making connections to a host.<br>- Retrieve data from a host.<br> →just search for dlls that do this and you have a good starting point</li><li><strong><em>shell32.dll</em></strong> on the other hand, is a library which contains Windows Shell API functions that are used when opening web pages and files.We’ll look into this later in this post.</li></ul><h4><em>Why not just figure out what the script does by reading through it?</em></h4><p>Well, we can.. but in most cases, embedded vbscript/jscript malware is normally heavily obfuscated in order to prevent being flagged by windows defender or any other anti-virus software via signatures. If you try and open the script, chances are you’ll be met by a bunch of characters that seem scrambled up and make no sense. Of course, this doesn’t mean that you can’t de-obfuscate these scripts, you can, but why go through that hassle when you can just dynamically observe how the script is interpreted by the engine that runs it and pretty much just figure out exactly what it’s doing?</p><p>We can do this by placing breakpoints or hooks on our suspect APIs and then just check for the data that&#39;s sent to those APIs so we can see if they are called and if at all they are called, what data is being sent to and from them. That way we completely eliminate the need to have to look at any of the scripts. What are hooks you may ask? They’re basically detours we place on a function to redirect the flow of a program to for example another function which will perform an operation before returning execution flow back to the original function.</p><p>So it goes without saying, that we are only as good as our hooks right? Meaning that if we hook onto a ‘wrong’ function we won’t get the data we’re looking for. Attackers however, could get creative with the API calls by using less suspect ones or syscalls (directly call kernel APIs) which makes a defender’s work slightly less straight forward.</p><blockquote><strong>PS</strong>: This can also really come in handy when trying to analyze why and where defense mechanisms catch our payloads.</blockquote><h3>Debugging wscript.exe</h3><p>Now comes the fun part! let’s actually put this to practice 😁</p><ol><li>Download the malicious script: <a href="https://malshare.com/sample.php?action=detail&amp;hash=77996383ebb12476d1896eeb8dedf70b">https://malshare.com/sample.php?action=detail hash=77996383ebb12476d1896eeb8dedf70b</a></li><li>Rename it to sample.js (or whatever you wanna call it). How do I know that it’s javascript? I ran strings on it and just looked for anything that could tell me what the function was all about. Googled what eval() did and a bunch of hits told me it was a javascript function, that’s it!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uO07_Ix1lSxHZ7OSUK_7DA.png" /></figure><p>3. Let’s load our malicious script onto wscript on a debugger.</p><p>File →Open</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*LQ0-_HW1rms3lJ4LzW1jAw.png" /></figure><p>File → Change Command Line</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*waYy2GS3EcCXlKLHpDGxoQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*VkX-8FHPePD8qz1aAGNACQ.png" /></figure><p>Okay, so at this point our script has been loaded onto x64dbg and the debugger almost immediately stopped execution at our executable’s (wscript.exe) entry point. Time to look for our two modules of interest <em>shell32.dll</em> and <em>ws2_32.dll. </em>To do this, lets look under the symbols tab to view loaded dlls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*QJABaqH92KDdcJ8qY2XIvw.png" /><figcaption>Loaded modules at entrypoint</figcaption></figure><p>As you can see, our modules have not yet been loaded. Remember: dlls are loaded dynamically (at runtime) meaning, when needed a dll will be called from a function that needs to ‘borrow’ it’s functionality. We’re at the entry point right now andt our script hasn’t been ran yet so no dlls pertaining to the execution of our script have been loaded yet. Obviously.</p><p>On x64dbg, you can set a breakpoint on a dll you anticipate will be loaded at some point during execution. This is a very important step because like I said earlier, if you don’t set the right breakpoints, you won’t get any useful information.</p><p>4. Set breakpoints on <em>ws2_32.dll</em> and <em>shell32.dll.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ied6b411ftF507O4sCJ_rw.png" /></figure><p>→Notice the already set breakpoint on wscript.exe entry point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*luNTF8SPBpyngBWGsCGLjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Pr6uz0ogNtgTajZvkLhTIA.png" /><figcaption><em>shell32.dll and ws2_32.dll breakpoints set</em></figcaption></figure><p>Let’s continue execution on our debugger by hitting run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lqdL0aXkiCI7OX35WsVQlg.png" /></figure><ul><li>We’ve hit a breakpoint at the entry point of one of our dlls of interest — <em>shell32.dll. </em>When we go back to the symbols tab, our module has finally been loaded, among others. Our list is bigger now :)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MENURLiOSbV3xbACdMqMQ.png" /></figure><ul><li>On the right side of the loaded modules, when you click on Shell32.dll is a list of functions it exports. It’s under these exports that we need to look for APIs that seem like they can be used to run an executable. Alternatively, a simple google search will tell you what API to look for. We’ll do<strong><em> ShellExecute. </em></strong>But first, a little something on Windows shell.</li></ul><h4>WIN32 API call chain(ShellExecute).</h4><p>Windows shell is a collection of objects necessary to run applications and manage the operating system — think of bash in Linux.</p><p>So as you think of ShellExecute in this case, imagine our sample.js script is trying to run some commands on cmd using this API. Which would mean that it’s probably going to use cmd to download the actual initial access executable? (This is just a train of thought, we still haven’t actually confirmed that this is the case)</p><p>Cool, so how then does ShellExecute work?</p><p>Msdn to the rescue :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*72AvmeNGAOtxqKZiZpj-kg.png" /></figure><p>So we can tell that this is an API that accepts six arguments : a handle to something, an operation to be done, a file the operation is done to?, probably the working directory and whether the window should pop up??</p><p>Enough assumptions, let’s just see what msdn says..</p><ol><li><em>hwnd : </em>A handle to the parent window.</li><li><em>lpOperation </em>: A null-terminated string, referred to in this case as a <em>verb</em>, that specifies the action to be performed.</li><li><em>lpFile</em> : A pointer to a null-terminated string that specifies the file or object on which to execute the specified verb.</li><li><em>lpParameters : </em>If lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. If <em>lpFile</em> specifies a document file, <em>lpParameters</em> should be <strong>NULL</strong>.</li><li><em>lpDirectory : </em>A pointer to a null-terminated string that specifies the default (working) directory for the action.</li><li><em>nShowCmd : </em>A flag that specifies how an application is to be displayed when it is opened.</li></ol><p>Okay, so we weren’t so badly off with our initial assumptions. yay!</p><p>When you’re writing code and you make a call to ShellExecute, it’ll be compiled to either ShellExecuteA or ShellExecuteW standing for ASCII or WideString respectively depending on the arguments that you’ve passed to it.</p><p>You can use either, however, internal to the dll Shell32, windows will always convert your parameters from ASCII to wide strings if you use an ASCII call.<br>Ex stands for extended and its basically an API interface that allows more descriptive arguments.</p><p>So when you call ShellExecuteA it is is converted into an extended ASCII call (ShellExecuteExA) which is then converted into an extended wide string (ShellExecuteExW) all of which happens internal to the dll Shell32.dll.</p><p>Remember, Shell32 doesn&#39;t create processes, its just an interface for you to write against. So its gonna have to call into kernel32.dll by calling CreateProcessW (W because your ASCII strings have already been converted to wide strings).<br>Now, inside kernel32.dll, there’s another conversion that happens where CreateProcessW calls CreateProcessInternalW (undocumented API) which in turn calls NtCreateUserProcess within ntdll before crossing over into kernel-mode.</p><ul><li>Remember how we said ShellExecuteA is extended and converted into an extended wide string API? Lets find this extended API (ShellExecuteExW)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2lsyhI1Rkvo49Wt2daaiw.png" /><figcaption>search results for ShellExecute on the exports tab</figcaption></figure><ul><li>Set a breakpoint on it; right click to toggle the breakpoint.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*08wmpeHT1JQHh0vHcSoRpA.png" /></figure><ul><li>Disable breakpoint on the Shell32.dll because its a breakpoint on any part of that dll and we are only interested in the API ShellExecuteExW within it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOVAzFG4qpzvkX-WmH2Dyg.png" /></figure><ul><li>Run</li></ul><blockquote>You might get a break point caused by some sort of exception that’s not our intended ShellExecuteExW. This is defender preventing our script from being executed. Just disable Real time protection and execution should continue. How did I know it was defender? Checked the call stack to see what was called last — a Microsoft security dll .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYtxgd1xgdc_bld4bfc4eA.png" /></figure><p>Looking at the screen above we can already spot quite a number of IOCs and to be honest our work is pretty much done at this point because we can CLEARLY tell whats happening — opens cmd then runs a hidden powershell instance that seems to download and run an executable in the background.</p><p>But let’s be a little bit extra and dig into the IOCs we see and try to analyze them based on what we already know about windows APIs.</p><ul><li>What’s being passed to ShellExecuteExW on CPU view?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dqkb75pAl1n61Gi4wgCQsA.png" /></figure><p>→ eip pointing to ShellExecuteExW</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsjzbO23OMClebv1DpFfQw.png" /><figcaption>Arguments of ShellExecuteExW on the stack</figcaption></figure><p><strong><em>ShellExecuteExW</em></strong></p><p>Remember earlier we said that <em>ShellExecuteExW </em>is the API upon which we provide a platform for our executable to be ran. Looking at the arguments under it on the stack as shown above, you see that it calls cmd (our platform) after which some arguments are passed onto cmd.</p><p>On msdn,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ByM_kpnbJmBcLD_3rqZqQ.png" /></figure><p>From the definition, we can see that the arguments are passed as a struct so lets parse that struct out.</p><ul><li>Only one parameter is being passed here, a pointer to pExecInfo which is of type SHELLEXECUTEINFO.</li><li>What does the struct SHELLEXECUTEINFO contain?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*roatiTSH0ZPzdp-huXvQjw.png" /></figure><ul><li>Two interesting parameters that could contain juicy information: <em>lpVerb</em> &amp; <em>lpFile</em></li></ul><p><strong><em>lpverb</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*tX7fmnb0NmYIiPOeeVZPBg.png" /><figcaption>Definition of lpVerb</figcaption></figure><p>The open verb and the file for the open verb will be the command line parameters to the executable being executed by ShellExecute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUXSIhh10Ckif0ZXamw69Q.png" /></figure><ul><li>Dump the pointer to SHELLEXECUTEINFOA structure so we can parse its members</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*BrmOf2qNCkNFrLFfY7pm6Q.png" /></figure><ul><li>After following pointer to our struct, <em>lpVerb</em> and <em>lpFile</em> will be the 4th and 5th parameters respectively.</li><li><em>lpVerb</em> is the fourth member of this structure so lets dump its content to see what it contains.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*Mg0HGLHNdEujXLflqw_bXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*uUboNdnxdxFNG_1i39nA1Q.png" /><figcaption>lpVerb Open</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*wFMZXm7J8SPs0BcSDbK_dg.png" /><figcaption>lpVerb File</figcaption></figure><p>The ASCII tab shows the command that’s being executed.</p><blockquote>PS: the dots between the letters (represented by the null bytes on the hex view) means that its a wide string.</blockquote><p>To make it more readable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Cq2bdhpwl_qomiY9YB5O-Q.png" /></figure><p>click extended ASCII</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*zkO4MdCOPRYrLpfXmqK9Uw.png" /></figure><p>Now we can actually read the command being passed to Shell execute from the string</p><p>clean it up..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ddnW8-_Eafq3VV0E5N2nMg.png" /></figure><p>And that’s it! We’ve successfully reversed the script.</p><p>Hope you enjoyed this little write up. If you have any questions feels free to hit the comments section or better yet, hit <a href="https://twitter.com/_tweerie_">my twitter</a> DM :)</p><p><strong>Links &amp; Resources:</strong></p><ul><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shellexecuteinfoa">SHELLEXECUTEINFOA (shellapi.h) - Win32 apps</a></li><li><a href="https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexw">ShellExecuteExW function (shellapi.h) - Win32 apps</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuqhBsWXUw7Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuqhBsWXUw7Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuqhBsWXUw7Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/21aa57e97b78a6a374521ba9a090e949/href">https://medium.com/media/21aa57e97b78a6a374521ba9a090e949/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f02a8de923d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup Windows Kernel Debugging between two VMs on a Linux host using VMWare.]]></title>
            <link>https://wambui-ngige.medium.com/how-to-setup-windows-kernel-debugging-between-two-vms-on-a-linux-host-vmware-f1d64f18a281?source=rss-750b60a32819------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1d64f18a281</guid>
            <category><![CDATA[windbg]]></category>
            <category><![CDATA[vmware]]></category>
            <category><![CDATA[windows-debugging]]></category>
            <category><![CDATA[kernel-debugging]]></category>
            <dc:creator><![CDATA[Wambui Ngige ツツ]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 21:18:10 GMT</pubDate>
            <atom:updated>2022-09-27T22:38:52.742Z</atom:updated>
            <content:encoded><![CDATA[<p>If for one reason or another, like me, you prefer to have a Linux host and couldn’t be bothered to dual boot every time you want to debug a Windows VM and, every now and then, you prefer to debug VM to VM using VMware as your hypervisor, then this is just the post for you.</p><p>There are a couple of other <a href="https://hshrzd.wordpress.com/2017/05/28/starting-with-windows-kernel-exploitation-part-1-setting-up-the-lab/">write ups</a> on the same out there, this is just my approach on the same.</p><p>Requirements:</p><ul><li>A Linux host of your choice — I’m using Ubuntu 20.04.3 LTS.</li><li>Hypervisor — I’m using VMware Workstation 16.2.1 build-18811642.</li><li>Two Windows 10 VMs — I’m using Windows 10 Pro 64-bit (10.0, Build 19043) (19041.vb_release.191206–1406).</li><li>WinDbg preview — Yes, you can install this from the Microsoft Store without having signed in just click “No, thanks” when they ask you to sign in.</li></ul><p>Assuming you have the two VMs running already at this point, make sure you take a snapshot of them before we make any changes, in case anything goes wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*yNKeVIeMYYd27CqK8MU4XQ.png" /></figure><h3>Setting up Windbg.</h3><h4><strong><em>On the debugging machine:</em></strong></h4><ul><li>Download WinDbg Preview from the Microsoft Store.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*mdoemvujnlflNuJFBRiEXA.png" /></figure><h4>Add symbols to your Windbg.</h4><p>Go to <em>File -&gt; Settings -&gt; Debugging settings </em>and set it up like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*7ioHa2RR89Fs5XRRvWpS4g.png" /></figure><p>This basically tells WinDbg where to look for symbols.</p><p>Symbols are pdbs (program databases) that resolve function names. We’ve set up a local ‘repository’ of symbols where WinDbg will save downloaded symbols (c:\Symbols) and a remote URL where WinDbg will look for symbols whenever it encounters functions whose symbols are not already stored locally.</p><blockquote><strong><em>A note about symbols</em></strong><em>:</em> Windows does not provide symbols for all its APIs (you might have heard of ‘undocumented APIs’? ) so you’ll have to either Reverse Engineer the functions yourself or look for their documentation in unofficial places such as <a href="http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FTEB.html">ntinternals</a> for NTAPI undocumented functions or the <a href="https://www.vergiliusproject.com/">vergilius project</a> for kernel APIs — but that’s beyond the scope of this post.</blockquote><h3><strong><em>Setting up a Communication Channel between our VMs — KDNET Network Kernel Debugging.</em></strong></h3><p>We need a channel through which our debugging VM can communicate with the debugee VM. In this case, we’re going to use networking as our communication medium because it’s the fastest method.</p><h4><strong><em>On the debugging VM:</em></strong></h4><ul><li>Add a new ‘host-only’ network adapter that we’ll use solely for debugging purposes.</li></ul><p><em>VM -&gt; Settings -&gt; Add -&gt; Network Adapter -&gt; Finish</em></p><ul><li>Then on that new network adapter, change it to Host-only. A new Network adapter should show up under Network adapters on your VM.</li></ul><p><em>Start -&gt; </em>Search<em> Device Manager</em></p><ul><li>Double-click on the Network adapter with a trailing ‘#2’. This is what we’ll use as our channel.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*l1TG0fE3U0-x3qiKzhstFg.png" /></figure><ul><li>We are looking for it’s bus parameters in the location field which we’ll interpret as 27:0:0 with the format &lt;BusNumber&gt;:&lt;DeviceNumber&gt;:&lt;FunctionNumber&gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*A0RzUGC98PLi2-7eyEPzDA.png" /></figure><p>File -&gt; Attach to kernel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WW5ozJrM-9KvsHyi7bShbA.png" /></figure><ul><li>Fill in a port you expect connections from as well as a key you will set for the connection to be established (we’ll set the same key on the debugee shortly) then press <em>OK.</em></li><li>At this point our debugger is waiting for a connection..</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*UQxulMwb7BpBpSt8JVHtcg.png" /></figure><h4>On the Debugee:</h4><p>Create a channel just like you did with the debugger:</p><ul><li>Add a new ‘host-only’ network adapter.</li></ul><p><em>VM -&gt; Settings -&gt; Add -&gt; Network Adapter -&gt; Finish</em></p><ul><li>Change it to Host-only.</li><li>Confirm that it’s on the same location as the debugging machine by checking the network adapters under Device Manager.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*A0RzUGC98PLi2-7eyEPzDA.png" /></figure><p>2. Open cmd as admin. We’ll use bcdedit to edit its boot configuration so that we can be able to boot into debug mode.</p><ul><li>Enabling debug mode:</li></ul><pre>bcdedit /debug on</pre><ul><li>Setting up network properties:</li></ul><pre>bcdedit /dbgsettings net hostip:172.16.22.132 port:50005 key:Back.To.The.Basics</pre><p>where hostip — debugger ip (hostonly interface ip)</p><ul><li>Setting up the bus parameters:</li></ul><p>bcdedit /set {dbgsettings} busparams 27.0.0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*9QXkUu1SmvHkOGlZNBiEIQ.png" /></figure><ul><li>Restart the VM.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*yKyMvZ2qn7RquVfT9bnx_w.png" /></figure><p>That’s it!</p><p>At this point you should see some activity on WinDbg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBB1N-oDx6ACZTnzzQbjdA.png" /></figure><p><strong>Links &amp; Resources:</strong></p><ul><li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-up-a-network-debugging-connection">Setting Up KDNET Network Kernel Debugging Manually - Windows drivers</a></li><li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-up-a-null-modem-cable-connection">Setting Up Kernel-Mode Debugging over a Serial Cable Manually - Windows drivers</a></li><li><a href="https://blahcat.github.io/2017/08/07/setting-up-a-windows-vm-lab-for-kernel-debugging/">Blah Cats</a></li><li><a href="https://dennisbabkin.com/blog/?t=setup-windbg-preview-for-kernel-debugging-via-fast-network-in-vmware-vm#new_tools">Windows Kernel Debugging - WinDbg Preview Setup</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1d64f18a281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provisioning Red Team Infrastructure with Terraform and Ansible on Vultr .]]></title>
            <link>https://wambui-ngige.medium.com/provisioning-red-team-infrastructure-with-terraform-and-ansible-on-vultr-17045b500128?source=rss-750b60a32819------2</link>
            <guid isPermaLink="false">https://medium.com/p/17045b500128</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[iac]]></category>
            <dc:creator><![CDATA[Wambui Ngige ツツ]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 19:06:31 GMT</pubDate>
            <atom:updated>2021-06-28T18:47:28.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>Provisioning Red Team Infrastructure with Terraform and Ansible on Vultr .</h3><h3>Part 1</h3><p>The idea behind this project was to make infrastructure easy to provision, deploy and dispose using Hashicorp’s Terraform as an infrastructure orchestration tool and Ansible to make any modifications to our infrastructure.</p><p>Traditionally, spinning up servers entailed using a provider’s Web UI and or CLI interface after which you would have to manually set up your servers to match your various needs, one at a time. In case of errors it was hard to go back and trace our steps to troubleshoot errors. The cycle would go on and on for each server to be deployed.</p><p><strong>Infrastructure as Code</strong></p><p>It’s important to understand the concept of infrastructure as code. It honestly sounds like such a big word but all it means is using code to define our infrastructure. That’s it. 🙌🏽</p><p>The code entails defining what type of servers you want to deploy, what provider you’re using, what services you want running on these servers, how they communicate with each other, etc.</p><p>If you have played around with serverless infrastructure deployment, implementation, modification or even destruction, you can agree that it’s such a tedious redundant task and to be honest, you don’t always have time for that 🤷🏽‍♀️</p><p>So how about a way to have some sort of ‘template’ such that all you need to deploy, modify or even destroy and re-instate your infrastructure — a common practice in Red team operations, only takes a few commands and you’re good to go? Sounds good right?</p><p>Before we get started, I’d like to give you a rough idea of our end goal. Basically, we want to emulate the key principles in this a <a href="https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki">mazing blog post by bluescreenofjeff</a> with a twist using our own selection of software and tools.</p><p><strong>Pre-Requisites</strong></p><ul><li>A cloud provider of your choice (I’m using Vultr).</li><li>An ssh-key fingerprint.</li><li>An API key.</li></ul><p><strong>TL;DR:</strong></p><p><a href="https://www.terraform.io/downloads.html">https://www.terraform.io/downloads.html</a></p><pre>sudo mv ~/terraform /usr/local/bin/terraform</pre><p>To confirm if this worked, just type on your terminal and you should get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/0*qwmzjleQDJ8GSSM6" /></figure><pre>ssh-keygen -E md5 -lf ~/.ssh/id_rsa.pub | awk &#39;{print $2}&#39;</pre><p>Where: ~/.ssh/id_rsa.pub is the path to your public key.</p><pre>export TF_VAR_my_api_key=your api key <br>export TF_VAR_ssh_fingerprint=yo:ou:r:fi:ng:er:pr:in:t</pre><p>Notice: how we define Terraform variables with the <strong>TF_VAR</strong> prefix.</p><p><strong>Creating your first server.</strong></p><p>At the end of this part, you should be able to create a server on Vultr using Terraform and install Docker on the server.</p><p>Let’s get started shall we?</p><p>We’re going to define a few files that will tell Terraform what our infrastructure should look like.</p><p>This file specifies what provider you are using to create and manage your servers. A provider is a Terraform plugin that Terraform uses to translate the API interactions with the services you’re running on your infrastructure. A few examples of providers include Digital Ocean, Linode, AWS, Chef, etc. See Terraform documentation for the <a href="https://www.terraform.io/docs/providers/">list of providers they support.</a></p><pre>provider &quot;vultr&quot; { <br>     api_key = var.my_api_key <br>}</pre><p>2. <strong><em>variables.tf</em></strong></p><p>We need to declare variables to avoid repetitiveness in our code. These are what we are going to be referring back to as we go along. For now, here’s a few variables we need to get a basic server up and running:</p><pre>variable &quot;my_api_key&quot; {} <br>variable &quot;ssh_fingerprint&quot; {} <br>data &quot;vultr_os&quot; &quot;Ubuntu&quot; { <br>     filter { <br>         name = &quot;name&quot; <br>         values = [&quot;Ubuntu 18.04 x64&quot;] <br>     } <br>} <br>data &quot;vultr_plan&quot; &quot;cnc_plan&quot; { <br>     filter { <br>         name = &quot;name&quot; <br>         values = [&quot;2048 MB RAM,55 GB SSD,2.00 TB BW&quot;]<br>     } <br>} <br>data &quot;vultr_region&quot; &quot;cnc_region&quot; { <br>     filter { <br>         name = &quot;name&quot; <br>         values = [&quot;London&quot;] <br>     } <br>} <br>data &quot;vultr_ssh_key&quot; &quot;Reed&quot; { <br>     filter {<br>         name = &quot;name&quot;<br>         values = [&quot;Reed&quot;]<br>     } <br>} <br>data &quot;vultr_application&quot; &quot;Docker&quot; { <br>     filter { <br>         name = &quot;deploy_name&quot; <br>         values = [&quot;Docker on Ubuntu 18.04 x64&quot;]<br>     } <br>}</pre><p>The code is quite self-explanatory; we basically just defined our server’s ‘characteristics’. Notice how we used both data and variables? Here’s a difference between <a href="https://www.terraform.io/docs/configuration/data-sources.html">data sources</a> and <a href="https://www.terraform.io/docs/configuration/variables.html">input variables</a>.</p><p>3. <strong><em>main.tf</em></strong></p><pre>resource &quot;vultr_server&quot; &quot;cnc&quot; { label = &quot;TF-CNC&quot; plan_id = data.vultr_plan.cnc_plan.id region_id = data.vultr_region.cnc_region.id hostname = &quot;op&quot; app_id = data.vultr_application.Docker.id }</pre><p>Think of this as our ‘main function’ that calls a bunch of other functions (pre-defined variables). It basically describes our entire infrastructure. In this case we only have one server. Later on, we’ll define even more servers (resources) here. We can have multiple resources to spin up multiple servers in our infrastructure.</p><p><strong>label</strong> - what name we want to give our server</p><p><strong>plan_id</strong> - what payment plan we want to use</p><p><strong>region_id</strong> - where we want our sever located</p><p><strong>hostname</strong> - our server&#39;s hostname</p><p><strong>app_id</strong> - the application we want installed in out server upon creation.</p><p>See what <a href="https://www.vultr.com/api/#app">applications can be launched when creating a Vultr VPS</a>.</p><p><strong><em>outputs.tf</em></strong></p><pre>output &quot;ip-address&quot;{ value = vultr_server.cnc.main_ip }</pre><p>This file tells Terraform what information you want relayed back to you once your VPS is created.</p><p><strong>Terraform init</strong></p><p>Once you have all your Terraform files ready, you can run which will initialize our project directory, download our provider information as well as initialize a working directory containing Terraform configuration files.</p><p><strong>NOTE: </strong>Something somewhat annoying you might notice when you do this a couple of times is that every time you create a new project and initialize it, it will download all required providers even if you had downloaded it in another project previously. This uses up a lot of disk space and you end up with multiple provider files like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*3mq4PgMMHHgc28wK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*gMN5R3TwjqZ9zPZq" /></figure><p>To prevent this, you’ll need to cache your Terraform providers.</p><pre>export TF_PLUGIN_CACHE_DIR=&quot;$HOME/opt/.terraform-plugins&quot;</pre><p>After setting this environment variable, just run <strong>terraform init</strong>. You&#39;ll notice now that Terraform downloads your plugins in the cache directory we&#39;ve set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*5_utfTV8F5QCfPMR" /></figure><p><strong>Terraform plan</strong></p><p>In Terraform versions after 0.11, you do not need to run , you can just directly run after initialization. However, if you go through this output you’ll see Terraform’s execution plan describing which actions Terraform will take in order to change real infrastructure to match the configuration.</p><pre>Refreshing Terraform state in-memory prior to plan... The refreshed state will be used to calculate this plan, but will not be persisted to local or remote state storage. <br>data.vultr_os.Ubuntu: Refreshing state... data.vultr_application.Docker: Refreshing state... data.vultr_ssh_key.Reed: Refreshing state... data.vultr_plan.cnc_plan: Refreshing state... data.vultr_region.cnc_region: Refreshing state... vultr_server.cnc: Refreshing state... [id=38139312] -------------------------------------------------------------------- An execution plan has been generated and is shown below. <br>Resource actions are indicated with the following symbols: + create </pre><pre>Terraform will perform the following actions: </pre><pre># vultr_server.cnc will be created <br>+ resource &quot;vultr_server&quot; &quot;cnc&quot; { <br>    + allowed_bandwidth = (known after apply) <br>    + app_id = 37 <br>    + auto_backup = (known after apply) <br>    + cost_per_month = (known after apply) <br>    + current_bandwidth = (known after apply) <br>    + date_created = (known after apply) <br>    + ddos_protection = (known after apply) <br>    + default_password = (sensitive value) <br>    + disk = (known after apply) <br>    + enable_ipv6 = (known after apply)  <br>    + enable_private_network = (known after apply) <br>    + firewall_group_id = (known after apply) <br>    + gateway_v4 = (known after apply) <br>    + hostname = &quot;op&quot; <br>    + id = (known after apply) <br>    + internal_ip = (known after apply) <br>    + iso_id = (known after apply) <br>    + kvm_url = (known after apply) <br>    + label = &quot;TF-CNC&quot; <br>    + location = (known after apply) <br>    + main_ip = (known after apply) <br>    + netmask_v4 = (known after apply) <br>    + network_ids = (known after apply) <br>    + network_ips = (known after apply) <br>    + network_macs = (known after apply) <br>    + notify_activate = (known after apply) <br>    + os = (known after apply) <br>    + os_id = (known after apply) <br>    + pending_charges = (known after apply) <br>    + plan_id = 202 <br>    + power_status = (known after apply) <br>    + ram = (known after apply) <br>    + region_id = 8 <br>    + reserved_ip = (known after apply) <br>    + script_id = (known after apply) <br>    + server_state = (known after apply) <br>    + snapshot_id = (known after apply) <br>    + status = (known after apply) <br>    + tag = (known after apply) <br>    + user_data = (known after apply) <br>    + v6_networks = (known after apply) <br>    + vps_cpu_count = (known after apply) } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ Note: You didn&#39;t specify an &quot;-out&quot; parameter to save this plan, so Terraform can&#39;t guarantee that exactly these actions will be performed if &quot;terraform apply&quot; is subsequently run.</pre><p><strong>Terraform apply</strong></p><p>Run terraform apply to implement your infrastructure.</p><pre>data.vultr_region.cnc_region: Refreshing state... data.vultr_plan.cnc_plan: Refreshing state... data.vultr_application.Docker: Refreshing state... data.vultr_ssh_key.Reed: Refreshing state... data.vultr_os.Ubuntu: Refreshing state... vultr_server.cnc: Refreshing state... [id=38139312] </pre><pre>An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: <br>  + create </pre><pre>Terraform will perform the following actions: <br># vultr_server.cnc will be created <br>+ resource &quot;vultr_server&quot; &quot;cnc&quot; { <br>    + allowed_bandwidth = (known after apply) <br>    + app_id = 37 <br>    + auto_backup = (known after apply) <br>    + cost_per_month = (known after apply)<br>    + current_bandwidth = (known after apply) <br>    + date_created = (known after apply) <br>    + ddos_protection = (known after apply) <br>    + default_password = (sensitive value) <br>    + disk = (known after apply) <br>    + enable_ipv6 = (known after apply) <br>    + enable_private_network = (known after apply) <br>    + firewall_group_id = (known after apply) <br>    + gateway_v4 = (known after apply) <br>    + hostname = &quot;op&quot; <br>    + id = (known after apply) <br>    + internal_ip = (known after apply) <br>    + iso_id = (known after apply) <br>    + kvm_url = (known after apply) <br>    + label = &quot;TF-CNC&quot; <br>    + location = (known after apply) <br>    + main_ip = (known after apply) <br>    + netmask_v4 = (known after apply) <br>    + network_ids = (known after apply) <br>    + network_ips = (known after apply) <br>    + network_macs = (known after apply) <br>    + notify_activate = (known after apply) <br>    + os = (known after apply) <br>    + os_id = (known after apply) <br>    + pending_charges = (known after apply) <br>    + plan_id = 202 <br>    + power_status = (known after apply) <br>    + ram = (known after apply) <br>    + region_id = 8 <br>    + reserved_ip = (known after apply) <br>    + script_id = (known after apply) <br>    + server_state = (known after apply) <br>    + snapshot_id = (known after apply) <br>    + status = (known after apply) <br>    + tag = (known after apply) <br>    + user_data = (known after apply) <br>    + v6_networks = (known after apply) <br>    + vps_cpu_count = (known after apply) } </pre><pre>Plan: 1 to add, 0 to change, 0 to destroy. <br>Do you want to perform these actions? Terraform will perform the actions described above. Only &#39;yes&#39; will be accepted to approve. </pre><pre>Enter a value: yes <br>vultr_server.cnc: Creating... <br>vultr_server.cnc: Still creating... [10s elapsed] <br>vultr_server.cnc: Still creating... [20s elapsed] <br>vultr_server.cnc: Still creating... [30s elapsed] <br>vultr_server.cnc: Still creating... [40s elapsed] <br>vultr_server.cnc: Still creating... [50s elapsed] <br>vultr_server.cnc: Still creating... [1m0s elapsed] <br>vultr_server.cnc: Still creating... [1m10s elapsed] vultr_server.cnc: Still creating... [1m20s elapsed] vultr_server.cnc: Still creating... [1m30s elapsed] vultr_server.cnc: Still creating... [1m40s elapsed] vultr_server.cnc: Creation complete after 1m44s [id=38349585] <br>Apply complete! Resources: 1 added, 0 changed, 0 destroyed. <br>Outputs: ip-address = &lt;ip-address&gt;</pre><p>And there you have it! You just deployed a server using Terraform.</p><p>If you want to destroy this server, simply run</p><p>This whole process seems quite tedious just to create a VPS (it is 😄 ) but in the long-run, you’ll have server provisioning scripts ready to deploy and destroy using just a few commands.</p><p>Our journey has just begun, moving forward in the next parts, we’ll make these servers more practical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*TyVRKkiXqBWruygi" /></figure><p><em>Originally published at </em><a href="https://tweerie.wordpress.com/2020/06/19/provisioning-red-team-infrastructure-with-terraform-and-ansible-on-vultr/"><em>http://tweerie.wordpress.com</em></a><em> on June 19, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17045b500128" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>