<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Posts on Up is Down and Black is White</title><link>https://n4r1b.com/posts/</link><description>Recent content in Posts on Up is Down and Black is White</description><generator>Hugo -- gohugo.io</generator><lastBuildDate>Sat, 04 Mar 2023 00:00:00 +0000</lastBuildDate><atom:link href="https://n4r1b.com/posts/index.xml" rel="self" type="application/rss+xml"/><item><title>The Intersection of Apple&#39;s USB Lower Filter and iPhone-WPD Integration</title><link>https://n4r1b.com/posts/2023/03/the-intersection-of-apples-usb-lower-filter-and-iphone-wpd-integration/</link><pubDate>Sat, 04 Mar 2023 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2023/03/the-intersection-of-apples-usb-lower-filter-and-iphone-wpd-integration/</guid><description>If you&amp;rsquo;ve ever connected an iPhone, iPad, or iPod to a Windows PC, you might have noticed that the device appears as a different type of device depending on what you&amp;rsquo;re doing with it. For example, if you&amp;rsquo;re charging your iPhone, it might show up as a &amp;ldquo;USB Composite Device,&amp;rdquo; but if you&amp;rsquo;re syncing music with iTunes, it might show up as an &amp;ldquo;Apple Mobile Device USB Driver.&amp;rdquo;. Have you ever wondered how this works?</description><content type="html"><![CDATA[

<p>If you&rsquo;ve ever connected an iPhone, iPad, or iPod to a Windows PC, you might have noticed that the device appears as a different type of device depending on what you&rsquo;re doing with it. For example, if you&rsquo;re charging your iPhone, it might show up as a &ldquo;USB Composite Device,&rdquo; but if you&rsquo;re syncing music with iTunes, it might show up as an &ldquo;Apple Mobile Device USB Driver.&rdquo;. Have you ever wondered how this works? It turns out that Apple has a USB lower filter on Windows machines that helps them control which USB configurations is used by the OS.</p>

<p>This blog post will be divide in two parts: first, we&rsquo;ll explore how Apple&rsquo;s USB lower filter works, what it does, and how it can provide a different experience whether Apple software is installed or not, and second, we&rsquo;ll investigate why file operations out-of-the-box with iPhones are so limited when the WPD property <code>WPD_DEVICE_PROTOCOL</code> for the device indicate that device is using the protocol Media Transfer Protocol (MTP). We&rsquo;ll delve into topics such as Windows Portable Device (WPD), USB descriptors, and User-Mode Driver Framework (UMDF), among others.</p>

<blockquote>
<p><strong>Remark:</strong> The research for this post was conducted using Windows 11 22H2, the AppleLowerFilter version 486.0.0.0 and an iPhone SE 2nd generation.</p>
</blockquote>

<h2 id="motivation">Motivation</h2>

<p>The motivation behind this blog post was a curiosity that arose from the limited options presented when connecting an iPhone to a Windows machine. Surprisingly, looking into the WPD properties of the iPhone the WPD device protocol is defined as <code>MTP: 15.20</code>, this is something weird since the class defined by the Interface descriptor is Image. This mismatch and the the limited options to interact with the device without using Apple software was bugging me so I decided to investigate to try an shed some light on these observations.</p>

<h2 id="initializing-apple-s-usb-lower-filter">Initializing Apple&rsquo;s USB Lower Filter</h2>

<p>Apple devices present themselves as composite devices with multiple interfaces to ensure that their devices are properly recognized and that all necessary drivers are loaded. This is because Apple devices typically have multiple interfaces, which provide different functionality, such as audio, video, and control. When we plug an Apple device into a Windows machine, the bus adapter identifies the device and provides its HardwareIDs and CompatibleIDs to the operating system. These IDs are used to search for the best driver in the Driver Store based on the match quality of the IDs. For the bus driver to consider this device a composite device, certain <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/enumeration-of-the-composite-parent-device" target="_blank">requirements</a> must be met. If these requirements cannot be met, the OS will not load the USB Composite Device class driver (usbccgp) automatically. In this case, we need to provide an INF that will load the generic parent driver, which for apple is the file <em>AppleUSB.inf</em></p>

<blockquote>
<p>In the case of the iPhone the requirement not met is that the device has multiple configurations (<code>bNumConfigurations == 4</code>).</p>
</blockquote>

<p>This single INF file contains various setup configurations for different devices (e.g. AppleUSB, AppleUsbHomePod, and AppleUsbWatch). For the case of iOS devices the HardwareId will match exactly so the OS will apply the AppleUSB setup configuration, this will copy the <code>AppleLowerFilter.sys</code> and will add the following values under the device specific registry key:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-inf" data-lang="inf"><span style="color:#ff79c6">[AppleUSB_CCGPDriverInstall_AddReg.HW]</span>
<span style="color:#50fa7b">HKR,,&#34;OriginalConfigurationValue&#34;,0x00010001,2</span>
<span style="color:#50fa7b">HKR,,&#34;UsbccgpCapabilities&#34;,0x00010001,0x10      ; Selective suspend for USB devices attached to the USB Composite Parent Driver</span>
<span style="color:#50fa7b">HKR,,FriendlyName,,%iPhone.AppleUSB.DeviceDesc% ;&#34;Apple Mobile Device USB Composite Device&#34;</span>
<span style="color:#50fa7b">HKR,,LowerFilters,0x00010000,AppleLowerFilter</span></code></pre></div>
<blockquote>
<p>The <code>OriginalConfigurationValue</code> is a value that can be set for the Usbccgp.sys driver in a device&rsquo;s hardware registry key. It determines which configuration of the composite device should be used as the default. When a composite device is first plugged in, the system reads the OriginalConfigurationValue and loads the specified configuration. This can be useful for composite devices with multiple configurations, where one configuration may be preferred as the default. <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/selecting-the-configuration-for-a-multiple-interface--composite--usb-d" target="_blank">More Info</a>.</p>
</blockquote>

<p>The following steps detailed by Microsoft will happen after the driver package is installed &ndash; <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/install/step-3--the-driver-for-the-device-is-installed" target="_blank">How Windows Install Device: Step 3</a>
- The device will be restarted.
- After restarting, the PnP manager identifies the device&rsquo;s function driver and any optional filter drivers, builds the device stack &ndash; In our case the FDO is Usbccgp &amp; the LowerFiDO is AppleLowerFilter &ndash; and starts the device by calling the DriverEntry routine for any required driver that is not yet loaded. The AddDevice routine is then called for each driver, starting with lower-filter drivers, then the function driver. Resources are assigned if required, and the PnP manager sends an IRP_MN_START_DEVICE to the device&rsquo;s drivers</p>

<h2 id="digging-into-apple-s-usb-lower-filter">Digging into Apple&rsquo;s USB Lower Filter</h2>

<p>After covering the theory behind the enumeration and installation of the AppleLowerFilter in the previous section, we will now take a closer look at how the driver works and the role it plays in enabling the functionality of Apple devices on Windows machines.</p>

<p>Being a WDF driver, the first steps when the PnP calls the DriverEntry is to initialize the framework and bind the WDF version (In this case WDF 1.15). Once this is done the framework will call our DriverEntry function, in the case of the AppleLowerFilter they driver entry will simply create a driver object and setting only an AddDevice routine in the <code>WDF_DRIVER_CONFIG</code>. The AddDevice routine for the AppleLowerFilter will do the following:</p>

<ul>
<li>Identify itself as a FiDO by calling <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdffdo/nf-wdffdo-wdffdoinitsetfilter" target="_blank">WdfFdoInitSetFilter</a></li>
<li>Register a <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdfdevice/nf-wdfdevice-wdfdeviceinitsetpnppowereventcallbacks" target="_blank">PnP and power management callback</a> for events:

<ul>
<li>EvtDevicePrepareHardware</li>
<li>EvtDeviceReleaseHardware</li>
<li>EvtDeviceD0Entry</li>
<li>EvtDeviceD0Exit</li>
</ul></li>
<li>Set two <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdfdevice/nf-wdfdevice-wdfdeviceinitassignwdmirppreprocesscallback" target="_blank">IRP pre-process callbacks</a> for IRPs:

<ul>
<li>IRP_MJ_PNP</li>
<li>IRP_MJ_INTERNAL_DEVICE_CONTROL</li>
</ul></li>
<li>Finally, <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdfdevice/nf-wdfdevice-wdfdevicecreate" target="_blank">create a DO</a> with a Context Type Info named <code>FILTER_EXTENSION (sizeof == 0x50)</code></li>
</ul>

<blockquote>
<p><strong>Note:</strong> I won&rsquo;t get into all the details of the WDF framework, but I encourage everyone to delve into the <a href="https://github.com/Microsoft/Windows-driver-frameworks" target="_blank">source code on Github</a>. It&rsquo;s a well-designed piece of software that makes writing drivers much easier and intuitive, so looking into the code is a great exercise 🙂.</p>
</blockquote>

<p>Next step that we are interested in during the <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/wdf/power-up-sequence-for-a-function-or-filter-driver" target="_blank">power-up sequence</a> is to prepare the hardware for power-up, this means calling the EvtDevicePrepareHardware callback registered by the filter. This is probably the most interesting step in the AppleLowerFilter so let&rsquo;s look at it closely.</p>

<p>First step in the Callback is to retrieve the USB descriptor, this is done by means of a function I called <code>GetUsbDeviceDescriptor</code>. This function is used to retrieve the USB device descriptor for the USB device. This is done by allocating memory for a URB (USB Request Block) and using the <code>URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE</code> type, which is a request to retrieve a descriptor from a USB device. The descriptor being requested is <code>USB_DEVICE_DESCRIPTOR_TYPE</code>, which provides information about the USB device such as its vendor and product IDs, device class, and protocol. The function submits the URB synchronously to retrieve the descriptor.</p>

<blockquote>
<p>For most of the USB related operations Apple is using the usbdlib, this is a bit surprising given that this is a WDF driver they could have used the wdfusb header which I personally think it would have simplified things 🙂.</p>
</blockquote>

<p>Then, the driver will store the <code>bNumConfigurations</code> into the <code>FILTER_EXTENSION</code> context and will proceed to call what I consider the main function of this driver: <code>GetPreferredConfig</code>. Let&rsquo;s take a look at a simple pseudocode of this function before describing the internals:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#8be9fd">int</span> PreferredConfig;
<span style="color:#ff79c6">if</span> (FilterCtx<span style="color:#ff79c6">-&gt;</span>bNumConfigurations <span style="color:#ff79c6">==</span> <span style="color:#bd93f9">1</span>) {
    PreferredConfig <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
} <span style="color:#ff79c6">else</span> {
    <span style="color:#ff79c6">if</span>( <span style="color:#ff79c6">!</span>NT_SUCCESS( GetDeviceConfigUrb(WdfDevice, <span style="color:#ff79c6">&amp;</span>PreferredConfig) ) {
        PreferredConfig <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">3</span>;
    }
}

FilterCtx<span style="color:#ff79c6">-&gt;</span>DeviceConfig <span style="color:#ff79c6">=</span> PreferredConfig;
<span style="color:#ff79c6">if</span>( <span style="color:#ff79c6">!</span>QueryAppleSoftwarePresent() ){
    PreferredConfig <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
}

<span style="color:#ff79c6">if</span> ( PreferredConfig <span style="color:#ff79c6">&gt;=</span> FilterCtx<span style="color:#ff79c6">-&gt;</span>bNumConfigurations)  {
    PreferredConfig <span style="color:#ff79c6">=</span> FilterCtx<span style="color:#ff79c6">-&gt;</span>bNumConfigurations;
}

<span style="color:#ff79c6">if</span> ( PreferredConfig <span style="color:#ff79c6">&gt;=</span> <span style="color:#bd93f9">5</span> ) {
    <span style="color:#ff79c6">return</span> <span style="color:#bd93f9">5</span>;
}

<span style="color:#ff79c6">return</span> PreferredConfig;</code></pre></div>
<p>This function will first check if the number of configurations of the device is 1. If it is, the preferred configuration is set to 1. If not, the code sends a URB to retrieve the preferred configuration. If the URB request fails, the preferred configuration is set to 3. The code then sets the <code>DeviceConfig</code> field in the FilterCtx structure. Then, it checks if the <code>QueryAppleSoftwarePresent</code> function returns false (indicating that Apple Software is not installed), and sets the preferred configuration to 1 if so. The code then checks if the preferred configuration is greater than or equal to the number of configurations specified in the device descriptor. If it is, the preferred configuration is set to the maximum number of configurations. Finally, if the preferred configuration is greater than or equal to 5, the code returns 5.</p>

<p>There&rsquo;s a few a key points in this function that we will look into deeper. The first thing that stand-out is the function <code>GetDeviceConfigUrb</code>, this function will allocate memory for a URB, sets the URB to make a vendor-specific control request, and then submits the URB synchronously to the USB driver stack. The specific vendor request being made is a control transfer with a request type of 69 and a transfer buffer containing one byte of data.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c">Urb<span style="color:#ff79c6">-&gt;</span>UrbHeader.Function <span style="color:#ff79c6">=</span> URB_FUNCTION_VENDOR_DEVICE;
Urb<span style="color:#ff79c6">-&gt;</span>UrbHeader.Length <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">sizeof</span>(_URB_CONTROL_VENDOR_OR_CLASS_REQUEST);
Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.TransferBufferLength <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.TransferBuffer <span style="color:#ff79c6">=</span> preferredConfig;
Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.Request <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">69</span>; <span style="color:#6272a4">// Curious number choice by the Apple guys :D
</span><span style="color:#6272a4"></span>Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.Value <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;
Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.Index <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;
Urb<span style="color:#ff79c6">-&gt;</span>UrbControlVendorClassRequest.TransferFlags <span style="color:#ff79c6">=</span> USBD_TRANSFER_DIRECTION_OUT <span style="color:#ff79c6">|</span> USBD_SHORT_TRANSFER_OK;
Status <span style="color:#ff79c6">=</span> SubmitUrbSync(wdfDevice, UsbdHandle, Urb);</code></pre></div>
<p>The next key point into choosing the preferred config is the function <code>QueryAppleSoftwarePresent</code>, this function plays a big role since it&rsquo;s return value will determine if we are always constrained to just one preferred config. This function will do the following:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#6272a4">// Check if we have already found the Apple Mobile Device Service
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">if</span> (gAppleMobileServiceFound) {
    <span style="color:#ff79c6">return</span> <span style="color:#bd93f9">1</span>;
}

<span style="color:#6272a4">// pseudocode just for simplicity 
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">auto</span> EventString{<span style="color:#f1fa8c">&#34;</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">BaseNamedObjects</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">com.apple.MobileDeviceProcess.QueryMuxReady&#34;</span>};
<span style="color:#6272a4">// Try to open the MuxReady event
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">if</span> ( NT_SUCCESS( ZwOpenEvent(<span style="color:#ff79c6">&amp;</span>eventHandle, STANDARD_RIGHTS_REQUIRED, <span style="color:#ff79c6">&amp;</span>EventString) ) ) {
    ZwClose(eventHandle)
    <span style="color:#ff79c6">return</span> <span style="color:#bd93f9">1</span>;
} 

<span style="color:#6272a4">// I believe this is old behavior. At least with the latest version of iTunes from the
</span><span style="color:#6272a4">// Microsoft Store, these keys are not created.
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">auto</span> serviceFound <span style="color:#ff79c6">=</span> QueryRegistry(
    <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Registry</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Machine</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">System</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">CurrentControlSet</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Services</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Apple Mobile Device Service&#34;</span>,
    <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;ImagePath&#34;</span>);
<span style="color:#ff79c6">auto</span> appFound <span style="color:#ff79c6">=</span> QueryRegistry(
    <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Registry</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Machine</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">System</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">CurrentControlSet</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Services</span><span style="color:#f1fa8c">\\</span><span style="color:#f1fa8c">Apple Mobile Device App&#34;</span>,
    <span style="color:#bd93f9">0</span>); 

<span style="color:#ff79c6">if</span> (serviceFound <span style="color:#ff79c6">||</span> appFound) {
    <span style="color:#6272a4">// Apple Mobile Device Service and app were found, so set the global flag    
</span><span style="color:#6272a4"></span>    gAppleMobileServiceFound <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">true</span>;
    <span style="color:#ff79c6">return</span> <span style="color:#bd93f9">1</span>;
}

<span style="color:#6272a4">// Apple NT event, Apple Mobile Device Service and app not found, so return 0
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">return</span>  <span style="color:#bd93f9">0</span>;
</code></pre></div>
<p>Getting back to function <code>GetPreferredConfig</code>, this value plays a big role because the number returned by this function will be used to overwrite the <code>OriginalConfigurationValue</code> in the registry key of the device.</p>

<blockquote>
<p><strong>Note:</strong> The value returned by <code>GetPreferredConfig</code> will be subtracted by one since Registry values described by the <code>OriginalConfigurationValue</code> correspond to the USB-defined configuration index, indicated by the <code>bConfigurationValue</code> member of the configuration descriptor (<code>USB_CONFIGURATION_DESCRIPTOR</code>) and not by the bConfigurationNum values reported in the device&rsquo;s configuration descriptor.</p>
</blockquote>

<p>What we&rsquo;ve just seen is why even thou the INF writes the value <code>2</code> in the <code>OriginalConfigurationValue</code> if you insert an iPhone into a PC without iTunes installed you&rsquo;ll see the following in the registry:</p>

<p><img src="/images/appleLowerFilter/OriginalConfigurationValue.jpg" alt="alt img" title="OriginalConfigurationValue" /></p>

<p>After setting the <code>OriginalConfigurationValue</code> in the registry, the EvtDevicePrepareHardware function will call <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdfusb/nf-wdfusb-wdfusbtargetdevicecreate" target="_blank">WdfUsbTargetDeviceCreate</a> to create the USB target device object. The USB target device object represents the underlying USB device and provides a way for the driver to communicate with the device.</p>

<p>To periodically check the preferred configuration, the function sets up a <code>WDFTIMER</code>. The timer&rsquo;s callback function will be called periodically to check if the preferred configuration has changed. If the preferred configuration has changed, the function will call <a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdfusb/nf-wdfusb-wdfusbtargetdevicecycleportsynchronously" target="_blank">WdfUsbTargetDeviceCyclePortSynchronously</a> for the device to be surprise-removed and re-enumerated, so it loads with the new configuration.</p>

<blockquote>
<p>The timer is set with a period of <code>0</code> so the framework will not call the timer. On the other hand, the filter will call <code>WdfTimerStart</code> with a DueTime of 5s (Relative to the current system time) from within the timer&rsquo;s callback function and also in the D0Entry callback.</p>
</blockquote>

<p>Let&rsquo;s now look into both IRP pre-process callbacks to get the full picture of the driver workflow. The pre-processing of IRPs allows the driver to modify or redirect the IRP before it is sent to the default handler or another driver in the stack. Let&rsquo;s first look at the handler for the Internal Device Control request. This function will check the IRP is an IOCTL_INTERNAL_USB_SUBMIT_URB request to select the USB configuration. If it is, the function obtains a handle to the device, forwards the IRP and then retrieves pipe handles for the USB interface has class Image. The pipe handles for Interrupt, BulkIn and BulkOut will be stored in the device context.</p>

<p>Now lets take a look at the handler for the PnP IRPs pre-processing. In this case the handle will handle two cases:
- <code>IRP_MN_QUERY_DEVICE_RELATIONS</code>
- <code>IRP_MN_QUERY_ID</code></p>

<p>The case of the QueryID IRP is pretty simple, the function will check if <code>FilterCtx-&gt;DeviceConfig</code> &ndash; Remember this value was obtained by means of the vendor-specific URB &ndash; is set to 1,  If it is, the function appends the string <code>&amp;RESTORE_MODE</code> to the information returned for <code>BusQueryHardwareIDs</code> and <code>BusQueryDeviceID</code> requests.</p>

<p>In the other hand, the QueryDeviceRelation is a bit more interesting. First of all, this handler will only execute if certain timer has not run (More on this shortly) and if Apple Software is installed on the machine. It will only handle the BusRelations IRP, it will forward the request synchronously and checks if the status is successful. If there is any information returned, it looks in the returned device object list for a device whose CompatibleId contains <code>USB\Class_06</code>. If found, it dereference this DO, then removes it from the list and updates the device count &ndash; This will make so that even usbccgp created the PDO for the WPD device, the PnP will not see the DO just yet since the returned list won&rsquo;t have it. Shortly we will see how the lower filter handles this.</p>

<p>If the device of class 6 was found then the function will set up another WDF timer, based on the DbgPrints we will call it the PtpTimer, which triggers after 5 seconds.
When triggered the callback will set a flag in the deviceContext so the QueryDeviceRelations handler doesn&rsquo;t process requests anymore, will check if iTunes is present and if it is, it will send the following set of PTP/MTP operation request packets to the USB device.</p>

<ul>
<li>OpenSession - OperationCode: 0x1002</li>
<li>VendorExtension - OperationCode: 0x9008</li>
<li>CloseSession - OperationCode: 0x1003</li>
</ul>

<p>The USB packet capture below illustrates the execution of these operations, notice how they take place approximately 5 seconds into the capture on that port.</p>

<p><img src="/images/appleLowerFilter/CapturePtpTimer.jpg" alt="alt img" title="Capture PTP timer packets" /></p>

<blockquote>
<p>I&rsquo;ve tried by all means to get more information on operation 0x9008 but there seems to not be any information about it for Apple devices. The best I could get was ChatGPT saying that &ldquo;Operation command 0x9008 in a PTP/MTP packet typically corresponds to the &ldquo;Apple Device Info&rdquo; command&rdquo;. Unfortunately, I asked for documents/quotes proving this and every link the chat gave me was either invalid or was unavailable/deprecated Apple documentation. Given the name &ldquo;Apple Device Info&rdquo; I thought it would be similar to the PTP/MTP command &ldquo;GetDeviceInfo&rdquo;, but every test I tried on my machine command 0x9008 doesn&rsquo;t seem to have a Data Phase, so my best guess it&rsquo;s that is either not a &ldquo;Device Info&rdquo; command or Apple devices don&rsquo;t respond to that command anymore. However, if somebody has more info about this command please reach out, I&rsquo;d love to hear more about it 🙂!!</p>
</blockquote>

<p>For reference, the quotes/links from ChatGPT:</p>

<p><img src="/images/appleLowerFilter/ApplePtpChatGpt.jpg" alt="alt img" title="Operation Command 0x9008 ChatGPT info" /></p>

<p>Lastly, after sending the PTP/MTP requests, the PtpTimer will call <code>IoInvalidateDeviceRelations</code> with relation type <code>BusRelation</code> which will trigger a new IRP QueryDeviceRelations, but since this time the timer already executed the handler won&rsquo;t remove the WPD device from the Devices list. So this time the PnP manager we will actually see the PDO for the WPD device and will start building the stack for it. The following image shows this behavior captured by adding our own LowerFilter to the stack and just tracing Pre and Post the IRP is handled by the AppleLowerFilter.</p>

<p><img src="/images/appleLowerFilter/PrePostDeviceRelations.jpg" alt="alt img" title="Pre &amp; Post DeviceRelations" /></p>

<blockquote>
<p>I have no clue why Apple is doing this, my guess is that the PTP packet with operationCode 0x9008 somehow notifies the device that iTunes is present on the host or something around those lines. I didn&rsquo;t notice any different behavior on the WPD device with or without iTunes installed, other than the WPD device taking 5 seconds to actually show up. Removing the AppleLowerFilter from the list of LowerFilters for the device doesn&rsquo;t seems to have any major impact on the behavior of the WPD device. Again, if anybody knows more on why Apple might be doing these I&rsquo;d love to hear it!</p>
</blockquote>

<p>That&rsquo;s pretty much how the AppleLowerFilter behaves, as can be seen it will mainly work during initialization of the device, other than that the timer to check the active config will be running in the background every 5 seconds to see if the port has to be re-enumerated.</p>

<h2 id="ptp-or-mtp-that-is-the-question">PTP or MTP, that is the question</h2>

<p>In this section, we&rsquo;ll focus on why iPhones don&rsquo;t offer a whole set of operations on their storage as the ones we would expect from a device using the MTP protocol. We&rsquo;ll also investigate why the mismatch between the USB Interface Class/Subclass and the <code>WPD_DEVICE_PROTOCOL</code> property. To answer those questions, we&rsquo;ll take a look at how the a WPD device is created, how the storage is &ldquo;mounted&rdquo; and how WPD properties are set.</p>

<p>First let see the differences in the WPD device protocol property between and Android device connected using PTP and an iPhone:</p>

<p><img src="/images/appleLowerFilter/WpdInfo.jpg" alt="alt img" title="WpdInfo Android vs iPhone" /></p>

<p>given the WPD Protocol property in the iPhone we would expect to have a much richer set of options to interact with the device. We can quickly answer why the iPhone behaves as a PTP device just by looking into the Interface descriptor of the device. See the following descriptors for an iPhone and a Xiaomi in both PTP &amp; MTP mode &ndash; The iPhone has multiple configurations, but no matter which one we choose the interface that will create the WPD PDO will always contain the Interface with Class 6 and SubClass 1.</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"> 
        ---------------- iPhone Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x00</span> (Interface <span style="color:#bd93f9">0</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x03</span> (<span style="color:#bd93f9">3</span> Endpoints)
bInterfaceClass          : <span style="color:#bd93f9">0x06</span> (Image)
bInterfaceSubClass       : <span style="color:#bd93f9">0x01</span> (Still Imaging device)
bInterfaceProtocol       : <span style="color:#bd93f9">0x01</span>
iInterface               : 0x0E (String Descriptor <span style="color:#bd93f9">14</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;PTP&#34;</span>

        ---------------- Xiaomi MTP Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x00</span> (Interface <span style="color:#bd93f9">0</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x03</span> (<span style="color:#bd93f9">3</span> Endpoints)
bInterfaceClass          : 0xFF (Vendor Specific)
bInterfaceSubClass       : 0xFF
bInterfaceProtocol       : <span style="color:#bd93f9">0x00</span>
iInterface               : <span style="color:#bd93f9">0x05</span> (String Descriptor <span style="color:#bd93f9">5</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;MTP&#34;</span>

        ---------------- Xiaomi PTP Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x00</span> (Interface <span style="color:#bd93f9">0</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x03</span> (<span style="color:#bd93f9">3</span> Endpoints)
bInterfaceClass          : <span style="color:#bd93f9">0x06</span> (Image)
bInterfaceSubClass       : <span style="color:#bd93f9">0x01</span> (Still Imaging device)
bInterfaceProtocol       : <span style="color:#bd93f9">0x01</span>
iInterface               : <span style="color:#bd93f9">0x00</span> (No String Descriptor)</code></pre></div>
</div>

<p>Even though this answers the big question, there&rsquo;s still details such as why the iPhone won&rsquo;t allow to create nor copy anything into it while on the other hand the Xioami even when using PTP would allow creation of objects so as someone who enjoys getting to the bottom of things, simply glancing at the Interface descriptor wasn&rsquo;t enough to satisfy my curiosity.</p>

<p>Since this descriptor will generate the CompatibleId <code>USB\Class_06&amp;SubClass_01&amp;Prot_01</code>, looking for the INF that matches this ID we find the <code>wpdmtp.inf</code>. Within this INF we can get the following components for the UMDF part of WPD devices:</p>

<ul>
<li><code>WpdMtp.dll</code>: MTP core protocol component</li>
<li><code>WpdMtpUS.dll</code>: Usbscan transport layer for MTP driver</li>
<li><code>WpdMtpDr.dll</code>: Windows Portable Device Media Transfer Protocol Driver</li>
</ul>

<blockquote>
<p>Just for completion, as part of the kernel side of things, the INF will add <code>WinUSB.sys</code> as a LowerFilter and the reflector <code>WUDFRd.sys</code> as function driver.</p>
</blockquote>

<p>From the three binaries mentioned above <code>WpdMtpDr</code> is the main WPD MTP driver that will run in the <code>WUDFHost</code>, so we will start from there. This being a UMDFv1 driver it will be strongly based on COM and written in C++, on the bright side we have the <a href="https://github.com/microsoft/Windows-driver-samples/tree/win11-22h2/wpd/WpdWudfSampleDriver" target="_blank">WpdWudfSampleDriver</a> which will leave us with very little reversing to be done &ndash; It surprises me that the driver has not been updated to use UMDFv2, given that UMDFv1 has pretty much been deprecated and having little to no support for new features, I guess if ain&rsquo;t broken don&rsquo;t fix it 😅.</p>

<p><img src="/images/appleLowerFilter/AddDeviceUMDFv1.jpg" alt="alt img" title="Add Device UMDFv1" /></p>

<p>As can be seen above, our entrypoint will be the <a href="https://github.com/microsoft/Windows-driver-samples/blob/win11-22h2/wpd/WpdWudfSampleDriver/Driver.cpp#L18" target="_blank">OnDeviceAdd</a> routine.  In this function, the <code>CDevice</code> object is created, which takes us to the <a href="https://github.com/microsoft/Windows-driver-samples/blob/win11-22h2/wpd/WpdWudfSampleDriver/Device.cpp#L80" target="_blank">CDevice::OnPrepareHardware</a> routine where the WpdBaseDriver is initialized by calling <a href="https://github.com/microsoft/Windows-driver-samples/blob/win11-22h2/wpd/WpdWudfSampleDriver/WpdBaseDriver.cpp#L152" target="_blank">WpdBaseDriver::Initialize</a>. Unfortunately, this is the part where the Sample code and <code>WpdMtpDr</code> will start to differ. The sample code has no real device to communicate with, but in our case, we do. This is where <code>WpdMtp.dll</code> comes in, to act as the glue between the <code>WpdMtpDr</code> and the real device. The MTP core library contains the <code>CMtpDevice</code> class, which represents the real device. During the WpdBaseDriver initialization, the MTP core library is loaded and a session is opened with the device as can be seen in the following simplified code snippet.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#6272a4">// No error handling
</span><span style="color:#6272a4"></span>HANDLE hEvent{};
CMtpDevice <span style="color:#ff79c6">*</span> MtpCore{};
MTP_RESPONSECODE mtpRes <span style="color:#ff79c6">=</span> OK; <span style="color:#6272a4">// 0x2001
</span><span style="color:#6272a4"></span>
CoCreateInstance(<span style="color:#ff79c6">&amp;</span>CLSID_WindowsMtp, <span style="color:#8be9fd;font-style:italic">NULL</span>, CLSCTX_INPROC_SERVER, <span style="color:#ff79c6">&amp;</span>IID_IMtp2, (LPVOID <span style="color:#ff79c6">*</span>)<span style="color:#ff79c6">&amp;</span>MtpCore);
<span style="color:#6272a4">//
</span><span style="color:#6272a4">// wpdEvent represents a class that implements IMtpEventCallback, to get notifications from MTP events
</span><span style="color:#6272a4">// 
</span><span style="color:#6272a4"></span>MtpCore<span style="color:#ff79c6">-&gt;</span>Open(pszPortName, wpdEvents, <span style="color:#8be9fd;font-style:italic">NULL</span>);  
MtpCore<span style="color:#ff79c6">-&gt;</span>InitAsyncCancelEventHandle(hEvent);

CWpdDriverBase<span style="color:#ff79c6">-&gt;</span>m_mtpCore <span style="color:#ff79c6">=</span> MtpCore <span style="color:#6272a4">// Let&#39;s assume this will be wrapped in a ComPtr
</span><span style="color:#6272a4"></span>
MtpCore<span style="color:#ff79c6">-&gt;</span>OpenSession( <span style="color:#bd93f9">1</span>, <span style="color:#ff79c6">&amp;</span>mtpRes );
<span style="color:#ff79c6">if</span>( mtpRes <span style="color:#ff79c6">==</span> SessionAlreadyOpened <span style="color:#ff79c6">||</span> mtpRes <span style="color:#ff79c6">==</span> InvalidTransactionId ) { <span style="color:#6272a4">// 0x201E &amp; 0x2004 respectively
</span><span style="color:#6272a4"></span>    MtpCore<span style="color:#ff79c6">-&gt;</span>ResetDevice( <span style="color:#ff79c6">&amp;</span>mtpRes );
    MtpCore<span style="color:#ff79c6">-&gt;</span>OpenSession( <span style="color:#bd93f9">1</span>, <span style="color:#ff79c6">&amp;</span>mtpRes );
}

MtpCore<span style="color:#ff79c6">-&gt;</span>Close();
</code></pre></div>
<p>After loading the MTP core module, the initialization routine is triggered to retrieve the MTP DeviceInfo Dataset. This is one of the initial MTP requests sent to the device, and the DeviceInfo structure is populated upon its return. Notably, the structure contains critical information such as the Model, Manufacturer, and various MTP version identifiers, as detailed in section 5.1.1 of the MTPforUSB-IFv1.1 specification. Such information plays a crucial role in setting up the WPD properties later on.</p>

<blockquote>
<p>The MTP core sends the request and parses the response into a <code>CDeviceInfo</code> structure, whereas the <code>WpdMtpDr</code> leverages a caching system that stores COM pointers to the classes returned by <code>WpdMtp</code>. This approach prevents frequent re-issuance of PTP/MTP requests to the device, thereby optimizing I/O operations. Please note that this caching mechanism is beyond the scope of this post.</p>
</blockquote>

<p>The following stack shows the first time this function is called:</p>

<pre><code>0:008&gt; k
 # Child-SP          RetAddr               Call Site
00 000000b5`6027f3d8 00007ffb`db67dc66     wpdmtp!CMtpDevice::GetDeviceInfo
01 000000b5`6027f3e0 00007ffb`db6850fd     wpdmtpdr!CMtpWrapper::GetDeviceInfo+0x10a
02 000000b5`6027f450 00007ffb`db65f058     wpdmtpdr!CMtpWrapper::IsDevicePropertySupported+0xf5
03 000000b5`6027f4f0 00007ffb`db65f3c6     wpdmtpdr!WpdBaseDriver::Initialize+0x58
04 000000b5`6027f570 00007ffb`db6494a9     wpdmtpdr!WpdBaseDriver::Initialize+0xbe
05 000000b5`6027f5a0 00007ffb`db64b9f6     wpdmtpdr!CDevice::InitializeBaseDriver+0x71d
06 000000b5`6027f660 00007ffb`db64acf9     wpdmtpdr!CDevice::_PrepareHardwareThread+0x4e
07 000000b5`6027f7b0 00007ffc`1f3626bd     wpdmtpdr!CDevice::PrepareHardwareThread+0x9
08 000000b5`6027f7e0 00007ffc`2034a9f8     KERNEL32!BaseThreadInitThunk+0x1d
09 000000b5`6027f810 00000000`00000000     ntdll!RtlUserThreadStart+0x28
</code></pre>

<blockquote>
<p><strong>Note:</strong> I won&rsquo;t get into all the details of how the WPD protocol works since that could be a post in itself. But, mainly there&rsquo;s two IOCTLs (For Read-Only and Read-Write commands) which pack the WPD payload inside. In UM a WPD application will build a WPD command usually using the WPD API, which will serialize this WPD command and pack it into an IOCTL request, this will reach the Driver which will deserialize the command and act accordingly. For an example on how a WPD driver handles this, see: <a href="https://github.com/microsoft/Windows-driver-samples/blob/win11-22h2/wpd/WpdWudfSampleDriver/Queue.cpp#L33" target="_blank">CQueue::ProcessWpdMessage</a>.</p>
</blockquote>

<p>Once the device is ready to receive I/O operations, the OS will try to retrieve the WPD DEVICE properties, this information lives within the <code>DEVICE</code> objectID (This ObjectID is pre-defined and always represents the DEVICE object). This request will reach the WPD driver which will fill in the WPD Device properties with the information of the <code>CDeviceInfo</code>. For the case of the <code>WPD_DEVICE_PROTOCOL</code> this is how the value will be set:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#6272a4">// No error handling
</span><span style="color:#6272a4"></span>ULONG extId;
CString protocol;
USHORT extVersion;
IMtpDeviceInfo deviceInfo;
IPortableDeviceValues portableDeviceValues;

<span style="color:#ff79c6">if</span>( property <span style="color:#ff79c6">==</span> WPD_DEVICE_PROTOCOL) {
    deviceInfo<span style="color:#ff79c6">-&gt;</span>GetVendorExtId( <span style="color:#ff79c6">&amp;</span>extId );
    deviceInfo<span style="color:#ff79c6">-&gt;</span>GetVendorExtVersion( <span style="color:#ff79c6">&amp;</span>extVersion );
    
    <span style="color:#ff79c6">if</span>( extId <span style="color:#ff79c6">==</span> MICROSOFT_VENDOR_EXT_ID ) { <span style="color:#6272a4">// MICROSOFT_VENDOR_EXT_ID == 6
</span><span style="color:#6272a4"></span>        protocol.Format(_T(<span style="color:#f1fa8c">&#34;MTP: %.2f&#34;</span>), extVersion <span style="color:#ff79c6">/</span> <span style="color:#bd93f9">100.0</span> );
    } <span style="color:#ff79c6">else</span> {
        protocol.Format(_T(<span style="color:#f1fa8c">&#34;PTP: %.2f&#34;</span>), extVersion <span style="color:#ff79c6">/</span> <span style="color:#bd93f9">100.0</span> );
    }
    portableDeviceValues<span style="color:#ff79c6">-&gt;</span>SetStringValue( <span style="color:#ff79c6">&amp;</span>WPD_DEVICE_PROTOCOL, protocol);
}
</code></pre></div>
<p>So now if we take a look at the DeviceInfo Dataset that is returned by an iPhone, we can look the <code>VendorExtId</code> and <code>VendorExtVersion</code> and finally answer why the <code>WPD_DEVICE_PROTOCOL</code> is set to <code>MTP 15.20</code>. If anyone is curious, the <code>MICROSOFT_VENDOR_EXT_ID</code> is defined by MS as part of their WMDRM protocol. This is one of the values that the MTP responder needs to set in the DeviceInfo Dataset to tell the MTP initiator that it supports AAVT, surprisingly the iPhone only adds this required value but not the others. For more info see: <a href="https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-drmnd/2995527e-53fb-4612-8615-bd1c3c444832" target="_blank">MTP Vendor Extension Identification Message</a> &amp; <a href="https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-drmnd/37ad5858-ae05-45ae-bdfa-97538c190576" target="_blank">Media Transfer Protocol Enhanced specification by MS</a></p>

<p><img src="/images/appleLowerFilter/GetDeviceInfoApple.jpg" alt="alt img" title="Apple Device Info" /></p>

<p>One quick detail from the WPD DEVICE properties, there&rsquo;s a property called <code>WPD_DEVICE_TYPE</code> that is used for representation purposes only. But since we are here I think is interesting to discuss it fast. This property will be retrieved on the function <code>CDevicePropContext::GetDeviceType</code>, the function will get the CompatibleIds using the SetupAPI and will determine the DeviceType using an algorithm roughly like this:</p>

<ol>
<li>If <code>MS_SUBCOMP_XXX</code>, extract the device type from the &ldquo;XXX&rdquo; part of the ID using <code>wcstol</code>.</li>
<li>If <code>MS_COMP_MTP</code>, try to get PTP/MPT property &ldquo;Perceived Device Type (0xD407)&rdquo; if not found set DeviceType to WPD_DEVICE_TYPE_GENERIC.</li>
<li>If neither <code>CLASS_06&amp;SUBCLASS_01&amp;PROT_01</code> nor <code>URN:MICROSOFT-COM:DEVICE:MTP:1</code> set DeviceType to WPD_DEVICE_TYPE_MEDIA_TYPE.</li>
<li>Get the <code>DeviceInfo</code>. If VendorExtId is not 6, set DeviceType to WPD_DEVICE_TYPE_CAMERA. Otherwise try to get &ldquo;Perceived Device Type&rdquo; if not found set DeviceType to WPD_DEVICE_TYPE_GENERIC, if found, set DeviceType to value returned by device.</li>
</ol>

<p>In the case of an iPhone we would reach step 4, and since VendorExtId is equal to 6 and Property &ldquo;Perceived Device Type&rdquo; is not present, the DeviceType will be set to WPD_DEVICE_TYPE_GENERIC.</p>

<p>Now that we understand how the <code>WPD_DEVICE_PROTOCOL</code> property is set, let&rsquo;s explore why the Apple device&rsquo;s file operations are so limited. To anybody familiar with the PTP/MTP protocol they probably already know this, but regardless of the protocol PTP or MTP, each storage object (represented by <code>StorageIDs</code> starting with <code>s</code>) in the device has its own properties. Again, when I/O operations start on the device the OS retrieves information from the storage objects using two key operations: <code>GetStorageIDs (0x1004)</code> (to retrieve the list of <code>StorageIDs</code>) and <code>GetStorageInfo (0x1005)</code> (to define how the storage object behaves). We&rsquo;ll focus on the latter, as it returns a StorageInfo dataset that contains the following three key fields (see section 5.2.2 of the MTPforUSB-IFv1.1 specification for more information).</p>

<ul>
<li>Storage Type</li>
<li>FileSystem Type</li>
<li>Access Capability</li>
</ul>

<p>When the WPD driver first tries to obtain the StorageInfo for the device, the request goes through the MTP core module. This module sends a PTP/MTP operation request to the device and returns the resulting StorageInfo dataset back to the driver.</p>

<pre><code>0:008&gt; k
 # Child-SP          RetAddr               Call Site
00 000000b5`6027de48 00007ffb`db68387f     wpdmtp!CMtpDevice::GetStorageInfo
01 000000b5`6027de50 00007ffb`db695d05     wpdmtpdr!CMtpWrapper::GetStorageInfo+0x117
02 000000b5`6027def0 00007ffb`db6cc52f     wpdmtpdr!CStoragePropContext::CacheStorageUniqueId+0xed
03 000000b5`6027df40 00007ffb`db6cb7e9     wpdmtpdr!CHierarchyHandler::QueryStorages+0x1bb
04 000000b5`6027dfe0 00007ffb`db6c9c7e     wpdmtpdr!CHierarchyHandler::QueryDeviceChildren+0x65
05 000000b5`6027e0c0 00007ffb`db68f589     wpdmtpdr!CHierarchyHandler::GetChildren+0x2ae
06 000000b5`6027e140 00007ffb`db672608     wpdmtpdr!CEnumContext::BeginFunctionalObjectsEnumeration+0xa9
07 000000b5`6027e230 00007ffb`db66f5a7     wpdmtpdr!WpdCapabilities::OnGetFunctionalObjects+0x118
08 000000b5`6027e2f0 00007ffb`db65e497     wpdmtpdr!WpdCapabilities::DispatchWpdMessage+0x18f
09 000000b5`6027e3e0 00007ffb`db65036d     wpdmtpdr!WpdBaseDriver::DispatchWpdMessage+0x5e7
0a 000000b5`6027e6a0 00007ffb`db64f82d     wpdmtpdr!CSessionQueue::ProcessWpdMessage+0x411
0b 000000b5`6027e720 00007ffc`14858eba     wpdmtpdr!CSessionQueue::OnDeviceIoControl+0x22d
</code></pre>

<p>So if we take a look into how the iPhone is answering this request we will be able to determine how the Storage object will behave, based on the three fields we mentioned above</p>

<p><img src="/images/appleLowerFilter/GetStorageInfoApple.jpg" alt="alt img" title="Apple StorageInfo" /></p>

<p>From above image we get the following information:
- <strong>Storage Type == Fixed RAM</strong>, this is pretty standard with mobile devices.
- <strong>FileSystem Type == DCF</strong>, DCF stands for Design Rules for Camera FS, many of you would recognize this from the famous <code>DCIM</code> root directory. The DCF standard defines the option to set the read-only attribute on directories and files.
- <strong>Access Capability == Read-only without object deletion</strong>, this is the nail in the coffin. This will define the access restrictions on the Storage object, and the OS will honour them. For example, this will affect the options displayed in the Context Menu within the iPhone.</p>

<p>So here we have it, this is why the file options on an iPhone are so limited. Just for comparison, the following image shows the StorageInfo Dataset for the Xiaomi device when plugged in using PTP</p>

<p><img src="/images/appleLowerFilter/GetStorageInfoXiaomi.jpg" alt="alt img" title="Xiaomi StorageInfo" /></p>

<p>As it turns out, this is the reason why I was able to create objects on the Xiaomi device even when connected using the PTP protocol. However, it&rsquo;s worth noting that Xiaomi seems to have an issue with their MTP responder. Regardless of whether PTP or MTP is selected on the device, the same Dataset is returned in response to the <code>GetStorageInfo</code> request, at least on the Redmi Note 8 model.</p>

<p>With that, we&rsquo;ve addressed the questions we raised earlier in this section, providing a clearer understanding of why Apple devices behave the way they do, as well as how the WPD properties are configured for the device.</p>

<h2 id="the-impact-of-apple-software-on-the-apple-device-stack">The Impact of Apple Software on the Apple device stack</h2>

<p>Before wrapping up this post, let&rsquo;s briefly discuss what happens when we install iTunes on our host machine and how it enables operations such as copying files to/from the device. As mentioned earlier, the WPD API will only provide a limited subset of operations on the iPhone due to the restrictions in the Storage object. However, when iTunes is installed, it adds a different layer that enables more comprehensive access to the device.</p>

<p>As we saw in the AppleLowerFilter, once iTunes is installed this will allow the device to select a different USB Configuration Descriptor. Without iTunes we are limited to the configuration 1, on the other hand once iTunes is installed by default the chosen configuration will be 3. Let&rsquo;s take a quick look at both configurations and their interfaces:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yaml" data-lang="yaml"> 
    ------------------ Configuration Descriptor -------------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x02</span> (Configuration Descriptor)
wTotalLength             : <span style="color:#bd93f9">0x0027</span> (<span style="color:#bd93f9">39</span> bytes)
bNumInterfaces           : <span style="color:#bd93f9">0x01</span> (<span style="color:#bd93f9">1</span> Interface)
bConfigurationValue      : <span style="color:#bd93f9">0x01</span> (Configuration <span style="color:#bd93f9">1</span>)
iConfiguration           : <span style="color:#bd93f9">0x05</span> (String Descriptor <span style="color:#bd93f9">5</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;PTP&#34;</span>
bmAttributes             : 0xC0
 D7: Reserved, set <span style="color:#bd93f9">1</span>     : <span style="color:#bd93f9">0x01</span>
 D6: Self Powered        : <span style="color:#bd93f9">0x01</span> (yes)
 D5: Remote Wakeup       : <span style="color:#bd93f9">0x00</span> (no)
 D4..<span style="color:#bd93f9">0</span>: Reserved, set <span style="color:#bd93f9">0</span>  : <span style="color:#bd93f9">0x00</span>
MaxPower                 : 0xFA (<span style="color:#bd93f9">500</span> mA)

        ---------------- Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x00</span> (Interface <span style="color:#bd93f9">0</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x03</span> (<span style="color:#bd93f9">3</span> Endpoints)
bInterfaceClass          : <span style="color:#bd93f9">0x06</span> (Image)
bInterfaceSubClass       : <span style="color:#bd93f9">0x01</span> (Still Imaging device)
bInterfaceProtocol       : <span style="color:#bd93f9">0x01</span>
iInterface               : 0x0E (String Descriptor <span style="color:#bd93f9">14</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;PTP&#34;</span>

// Endpoint descriptors -&gt; Bulk IN, Bulk OUT &amp; Interrupt IN

    ------------------ Configuration Descriptor -------------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x02</span> (Configuration Descriptor)
wTotalLength             : 0x003E (<span style="color:#bd93f9">62</span> bytes)
bNumInterfaces           : <span style="color:#bd93f9">0x02</span> (<span style="color:#bd93f9">2</span> Interfaces)
bConfigurationValue      : <span style="color:#bd93f9">0x03</span> (Configuration <span style="color:#bd93f9">3</span>)
iConfiguration           : <span style="color:#bd93f9">0x07</span> (String Descriptor <span style="color:#bd93f9">7</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;PTP + Apple Mobile Device&#34;</span>
bmAttributes             : 0xC0
 D7: Reserved, set <span style="color:#bd93f9">1</span>     : <span style="color:#bd93f9">0x01</span>
 D6: Self Powered        : <span style="color:#bd93f9">0x01</span> (yes)
 D5: Remote Wakeup       : <span style="color:#bd93f9">0x00</span> (no)
 D4..<span style="color:#bd93f9">0</span>: Reserved, set <span style="color:#bd93f9">0</span>  : <span style="color:#bd93f9">0x00</span>
MaxPower                 : 0xFA (<span style="color:#bd93f9">500</span> mA)

        ---------------- Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x00</span> (Interface <span style="color:#bd93f9">0</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x03</span> (<span style="color:#bd93f9">3</span> Endpoints)
bInterfaceClass          : <span style="color:#bd93f9">0x06</span> (Image)
bInterfaceSubClass       : <span style="color:#bd93f9">0x01</span> (Still Imaging device)
bInterfaceProtocol       : <span style="color:#bd93f9">0x01</span>
iInterface               : 0x0E (String Descriptor <span style="color:#bd93f9">14</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;PTP&#34;</span>

// Endpoint descriptors -&gt; Bulk IN, Bulk OUT &amp; Interrupt IN

        ---------------- Interface Descriptor -----------------
bLength                  : <span style="color:#bd93f9">0x09</span> (<span style="color:#bd93f9">9</span> bytes)
bDescriptorType          : <span style="color:#bd93f9">0x04</span> (Interface Descriptor)
bInterfaceNumber         : <span style="color:#bd93f9">0x01</span> (Interface <span style="color:#bd93f9">1</span>)
bAlternateSetting        : <span style="color:#bd93f9">0x00</span>
bNumEndpoints            : <span style="color:#bd93f9">0x02</span> (<span style="color:#bd93f9">2</span> Endpoints)
bInterfaceClass          : 0xFF (Vendor Specific)
bInterfaceSubClass       : 0xFE
bInterfaceProtocol       : <span style="color:#bd93f9">0x02</span>
iInterface               : <span style="color:#bd93f9">0x17</span> (String Descriptor <span style="color:#bd93f9">23</span>)
 Language <span style="color:#bd93f9">0x0409</span>         : <span style="color:#f1fa8c">&#34;Apple USB Multiplexor&#34;</span>

// Endpoint descriptors -&gt; Bulk IN &amp; Bulk OUT</code></pre></div>
</div>

<p>Selecting configuration 3, will make usbccgp generate the deviceID <code>USB\VID_xxxx&amp;PID_yyyy&amp;MI_01</code> (01 extracted from the bInterfaceNumber). And these deviceIDs are actually defined in the <code>appleusb.inf</code>, which define the copy of the following files:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-inf" data-lang="inf"><span style="color:#ff79c6">[AppleUsbMux_Install]</span>
<span style="color:#50fa7b">Include</span><span style="color:#ff79c6">=</span><span style="color:#f1fa8c">winusb.inf</span>
<span style="color:#50fa7b">Needs</span><span style="color:#ff79c6">=</span><span style="color:#f1fa8c">WINUSB.NT</span>
<span style="color:#50fa7b">CopyFiles</span><span style="color:#ff79c6">=</span><span style="color:#f1fa8c">AppleUsbFilter_CopyFiles</span>
<span style="color:#50fa7b">CopyFiles</span><span style="color:#ff79c6">=</span><span style="color:#f1fa8c">AppleKmdfFilter_CopyFiles</span>
<span style="color:#50fa7b">FeatureScore</span><span style="color:#ff79c6">=</span><span style="color:#f1fa8c">0x7F</span>

<span style="color:#ff79c6">[AppleUsbFilter_CopyFiles]</span>
<span style="color:#50fa7b">AppleUsbFilter.dll</span>

<span style="color:#ff79c6">[AppleKmdfFilter_CopyFiles]</span>
<span style="color:#50fa7b">AppleKmdfFilter.sys</span></code></pre></div>
<p>These two drivers will be part of the device Apple calls &ldquo;Apple Mobile Device USB Device&rdquo;, which communicates with the iPhone using a proprietary protocol rather than MTP or PTP. Yoy can learn more about this protocol by looking at the source code of the awesome <a href="https://libimobiledevice.org/" target="_blank">libimobiledevice</a>. Once the drivers are installed and running, iTunes itself communicates with the iPhone using a combination of standard WPD API calls and custom Apple-specific commands. This allows iTunes to offer features like copying files to/from the device, managing apps and backups, and updating the device firmware.</p>

<p>The following diagram provides a simplified overview of the entire device stack for an iPhone, including this scenario in which iTunes is installed and the AppleUsbMux device is created.</p>

<p><img src="/images/appleLowerFilter/AppleDeviceStack.jpg" alt="alt img" title="Apple Device Stack" /></p>

<h2 id="conclusion">Conclusion</h2>

<p>In this post, we explored how Apple&rsquo;s USB lower filter works on Windows machines and it&rsquo;s role in providing a different experience depending on whether Apple software is installed or not. We also delved into topics such as Windows Portable Device (WPD) and User-Mode Driver Framework (UMDF) to better understand the inner workings of the Apple device stack. We touched on how WPD devices are initialized and set up and this helped us learned why there&rsquo;s a mismatch between the WPD device protocol property and the class defined by the interface descriptor in Apple devices. We also looked into how the Storage object for a WPD device is set up and how this plays a role in the limitations that we have to operate with an iPhone without using third party software. Lastly, we briefly discussed how having iTunes installed make a difference in the Apple Mobile Device Stack and how this allows iTunes a way to properly manage the device content.</p>

<p>It&rsquo;s understandable that Apple wants to protect certain information and limit out-of-the-box options for interacting with iPhone storage, but it would have been nice to have a more hybrid solution where users could have more flexibility within certain limits. While iTunes provides a robust solution for managing iPhone content, sometimes installing third-party software may not be an option. However, I recognize that with the recent release of iTunes as a Microsoft Store application, this limitation may be reduced. Overall, while I understand Apple&rsquo;s approach to limiting access to certain information, a bit more flexibility would have been welcome. Maybe a Mac is the solution for a better integration with Apple devices 😄.</p>

<p>Thank you for reading this post and I hope you found it informative! As always, if there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a>.</p>
]]></content></item><item><title>Smart App Control Internals (Part 2)</title><link>https://n4r1b.com/posts/2022/09/smart-app-control-internals-part-2/</link><pubDate>Thu, 08 Sep 2022 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2022/09/smart-app-control-internals-part-2/</guid><description>Welcome back to SAC Internals! In the previous post we saw how SAC gets enabled and initialized. In the current post we will discuss how SAC enforce the actions. This is a good moment to clarify something that might not have been completely clear in the first part. Even thou SAC is a new feature, most of the code used by the feature to work was already in place on the OS.</description><content type="html"><![CDATA[

<p>Welcome back to SAC Internals! In the previous post we saw how SAC gets enabled and initialized. In the current post we will discuss how SAC enforce the actions. This is a good moment to clarify something that might not have been completely clear in the first part. Even thou SAC is a new feature, most of the code used by the feature to work was already in place on the OS. By this I mean, that one can get a similar behavior in versions before 22H2 by using the proper policy rules. So to summarize, the biggest change with regard to SAC is that MS will activate a specific WDAC policy, similar to how the OS enables the <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/microsoft-recommended-driver-block-rules" target="_blank">Driver Block Rules</a> policy when you enable HVCI.</p>

<p>I wanted to clarify that because <strong>a lot</strong> of what we are going to see in this post has been in the OS for a long time. It has been leveraged by features like AppLocker or AppID. Of course, there&rsquo;s a few aspects that will only apply to SAC and I&rsquo;ll make sure to remark those. On the bright side, the vast majority of this post can be extrapolated to how other WDAC policies are evaluated.</p>

<p>Without further ado, let&rsquo;s get into the post. We will start with a very high-level diagram of how an object gets validated by the CI.</p>

<p><img src="/images/smartAppControl/part2/CiValidation.jpg" alt="alt img" title="High-level CI validation" /></p>

<h1 id="sac-in-action">SAC in Action</h1>

<p>In this section we will focus our attention into the steps taken by the CI to handle a validation request coming from the kernel. We will dig deeper into the main routines involved in this process and we will also discuss some of the main structures used by the CI. As I just mentioned, most of this steps are not exclusive of SAC and they will be taken no matter which policies are enabled. Looking at the previous diagram, we see there&rsquo;re three main sources of evaluation. As far as I can tell, these points are related with the following Features/Policy Rules &ndash; The choice of using one or many of the evaluations depends in the Policy Rules.</p>

<ul>
<li><strong>OriginClaim (EAs or Token):</strong> <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/configure-authorized-apps-deployed-with-a-managed-installer" target="_blank">Managed Installer</a>, AppLocker, SmartScreen &amp; SAC</li>
<li><strong>Query Defender:</strong> <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/use-windows-defender-application-control-with-intelligent-security-graph" target="_blank">Intelligent Security Graph (ISG)</a> &amp; SAC</li>
<li><strong>Policy FileRules:</strong> Generic to all Policies with FileRules</li>
</ul>

<p>The following diagram shows in better detail the steps taken by the CI to validate an image:</p>

<p><img src="/images/smartAppControl/part2/InDepthCiValidation.jpg" alt="In-depth CI validation" width="700"/></p>

<p>So to start our journey, we already know from the first post that the global <code>g_CiPolicyState</code> has the bit <code>NW_ENABLED</code> meaning SAC is enabled and the SAC policy (Enforce or Evaluation) is active and stored in the <code>g_SiPolicyCtx</code>. Now let&rsquo;s take a look at the callbacks provided by CI to the kernel to find what ways the kernel has to validate and object. The following functions suggest the option of executing some type of Validation:</p>

<ul>
<li>CiValidateImageHeader</li>
<li>CiValidateImageData</li>
<li>CiValidateFileAsImageType</li>
<li>CiRevalidateImage</li>
</ul>

<p>In this post I&rsquo;m only going to focus on <code>CiValidateImageHeader</code></p>

<h3 id="civalidateimageheader">CiValidateImageHeader</h3>

<p>This function is, arguably, the main entrypoint for most of the CI validations. The Kernel will call this function from <code>SeValidateImageHeader</code> which is referenced within <code>MiValidateSectionCreate</code>. <code>CiValidateImageHeader</code> will handle the Phase 2 of the CI initialization &ndash; Mainly initialize minCrypt, ETW, Lookaside buffers, etc&hellip; &ndash; Once this is done (Only once), the first step is to obtain the Actions for the specified image (<code>CiGetActionsForImage</code>). This function will determine the actions that will take place for the validation based on things like the Requested <a href="http://2012.ruxconbreakpoint.com/assets/Uploads/bpx/alex-breakpoint2012.pdf" target="_blank">SigningLevel</a> or if the object comes from a Protected or System Process &ndash; I have to be honest here, the actions are a bitfield enum but I have no clue what most of the values mean 😄.</p>

<p>Once the actions have been obtained, the function is ready to start validating the image. In case the action variable has bit 0 set (<code>ACTION_FILE_IN_CACHE (0x1)</code>) then the CI will try to obtain any previously validation data already set for this FO, and re-validate it.</p>

<blockquote>
<p>We won&rsquo;t touch on the CI cache and how it&rsquo;s validation works in this post. In essence it will try to obtain the <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ifs/kernel-extended-attributes" target="_blank">Kernel EAs</a>: <code>$Kernel.Purge.CIpCache</code> or <code>$Kernel.Purge.ESBCache</code> (See function <code>CipGetFileCache</code>). Then it will apply the policy to these attributes inside <code>CiApplyPolicyToSyntheticEa</code>. This routine will end up calling <code>CipApplySiPolicyEx</code> which we will discuss in detail later.</p>
</blockquote>

<p>If the &ldquo;file in cache&rdquo; attribute is not set, then the main structure to process validations will be allocated (<code>CipAllocateValidationContext</code>). This structure is used for all types of validation, as an example this same context is also used for HVCI validation (See <code>CiHvciSetValidationContextForHvci</code>). Once this context is allocated, there&rsquo;s two actions I&rsquo;ve seen taking place for UMCI validation.</p>

<ul>
<li>If bit 2 is set (<code>ACTION_PAGE_HASH (0x4)</code>). <em>Validation function</em> -&gt; <code>CipValidatePageHash</code></li>
<li>If bit 8 is set (<code>ACTION_FILE_HASH (0x100)</code>). <em>Validation function</em> -&gt; <code>CipValidateFileHash</code></li>
</ul>

<p><code>CipValidateImageHash</code> will receive as a function pointer the <em>Validation function</em> for the action taking place. No matter what function pointer is passed, PageHash or FileHash, <code>CipValidateImageHash</code> will end up calling it. In both <em>Validation functions</em>, the CI will update the validation context with information from the object being validated. Things like the FileInfo (<code>CipUpdateValidationContextWithFileInfo</code>), the File Version (<code>CiGetFileResourceInformation</code>), the Embedded Signature (<code>CipImageGetCertInfo</code>) or the object hash (Page <code>CipCalculateHeaderHash</code> or File <code>CipCalculateImageHash</code>). With all this information the code will proceed to apply the policy by means of the function <code>CipApplySiPolicyEx</code>.</p>

<blockquote>
<p>For validation of unsigned images the <em>Validation Function</em> will return <code>STATUS_INVALID_IMAGE_HASH</code> and the code will proceed into <code>CipApplySIPolicyUMCI</code> which end up calling the aforementioned <code>CipApplySiPolicyEx</code>. In the contrary for signed files, this function will be reached from <code>CiVerifyPageHashSignedFile</code> or <code>CiVerifyFileHashSignedFile</code> (As a quick note, these two functions have their HVCI counterpart <code>CiHvciXxx</code>).</p>
</blockquote>

<h2 id="cipapplysipolicyex">CipApplySiPolicyEx</h2>

<p>As the name implies, this function will apply the policy to the Object being validated. The function will first set up two structures that will be passed afterwards to the validation engine. One structure will hold the information of the ImageFile being validated while the other one will contain the information needed for the &ldquo;external&rdquo; authorization process &ndash; I say &ldquo;external&rdquo; authorization because MS uses that word in the function name of the callback that will validate the Object.</p>

<p>These two structures will be stored inside the Validation Context and both will actually be filled with data from it. The one that contains the Image data, I named <code>CI_VALIDATE_IMAGE_DATA</code>, and among other things contains the following:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_CERT_CHAIN {
  UINT32 AlgId;
  INT32 Size;
  PVOID Hash;
  UNICODE_STRING IssuedTo;
  UNICODE_STRING IssuedBy;
} SI_CERT_CHAIN, <span style="color:#ff79c6">*</span>PSI_CERT_CHAIN;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_EKU {
  INT32 Type;
  PVOID Oid;
} SI_EKU, PSI_EKU;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_CHAIN_INFO {
  INT32 Size;
  PSI_EKU Ekus[];
  INT32 EkusCount;
  PSI_CERT_CHAIN CertChain[];
  INT32 CertChainCount;
  INT32 Type;
  UNICODE_STRING field_28;
} SI_CHAIN_INFO, <span style="color:#ff79c6">*</span>PSI_CHAIN_INFO;


<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CI_VALIDATE_IMAGE_DATA {
  PSI_CHAIN_INFO ChainInfo; <span style="color:#6272a4">// In case the image is signed, parsed in function SIPolicyConvertChainInfo
</span><span style="color:#6272a4"></span>  PVOID ValidationHash;     <span style="color:#6272a4">// I believe this can take different values depending 
</span><span style="color:#6272a4"></span>                            <span style="color:#6272a4">// what type of validation is being done (PageHash, FileHash, etc..)
</span><span style="color:#6272a4"></span>  INT32 ValidationHashSize;
  PUNICODE_STRING OriginalFileName;
  PUNICODE_STRING InternalName;
  PUNICODE_STRING FileDescription;
  PUNICODE_STRING ProductName;
  UINT64 ProductVersion;
...
} CI_VALIDATE_IMAGE_DATA, <span style="color:#ff79c6">*</span>PCI_VALIDATE_IMAGE_DATA;</code></pre></div>
</div>

<p>On the other hand, the external authorization structure, which I named <code>CI_EXTERNAL_AUTH</code>, has the following interesting values</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CI_EXTERNAL_AUTH {
  INT32 SiSigningScenario; <span style="color:#6272a4">// Refer to &#34;Threat Detection using WDAC (Device Guard)&#34; by Matt Graeber to learn more about this field
</span><span style="color:#6272a4"></span>  ...
  <span style="color:#8be9fd">bool</span> RunFullTrustFlag
  <span style="color:#8be9fd">bool</span> IsSignedScript
  CI_VALIDATION_CTX <span style="color:#ff79c6">**</span>pValidationCtx;
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pCipExternalAuthorizationCallback)(SI_POLICY <span style="color:#ff79c6">*</span>Policy, CI_VALIDATION_CTX <span style="color:#ff79c6">**</span>);
  ...
} CI_EXTERNAL_AUTH, <span style="color:#ff79c6">*</span>PCI_EXTERNAL_AUTH;</code></pre></div>
<p>Before calling the Validation engine routine, <code>CipApplySiPolicyEx</code> will set up an array of structures that contain the validation result per policy, the size of the array will be equal to the number of active policies. I coined this structure as <code>CI_VALIDATION_RESULT</code> and it has the following fields:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CI_VALIDATION_RESULT {
  SI_POLICY_CTX <span style="color:#ff79c6">*</span>PolicyCtx;
  <span style="color:#8be9fd">bool</span> ReprieveResult;
  <span style="color:#8be9fd">bool</span> FileRuleMatchFound;
  INT32 ValidateImageStatus;
  NTSTATUS AuthorizationCbStatus;
  VALIDATE_SCORE ValidateImageScore;
} CI_VALIDATION_RESULT, <span style="color:#ff79c6">*</span>PCI_VALIDATION_RESULT;</code></pre></div>
<p>Finally, we are ready to call <code>SIPolicyObjectValidationEngine</code>, which has the following prototype:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#8be9fd">void</span>
<span style="color:#50fa7b">SIPolicyObjectValidationEngine</span>(
  PCI_EXTERNAL_AUTH ExternalAuthData,
  PCI_VALIDATE_IMAGE_DATA ValidateImageData,
  PSI_POLICY_CTX PolicyCtx,
  PCI_VALIDATION_RESULT ResultPerPolicy
  );</code></pre></div>
<p>This routine will simply iterate through the policies (And supplemental policies), calling the internal routine <code>SIPolicyValidateImageInternal</code> for each.</p>

<p>The internal validation routine has the task of calling into the external authorization callback to obtain the Validation score from the &ldquo;external source&rdquo;. Based on this score it will proceed, or not, to evaluate the image against the Rules within the policy. We will first focus on the external callback &ndash; Set to the function <code>CipExternalAuthorizationCallback</code> &ndash; and later we will discuss how the rules of the policy are evaluated.</p>

<blockquote>
<p>From what I can see in the code this is a bit different to what MS states in section <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/select-types-of-rules-to-create#file-rule-precedence-order" target="_blank">File rule precedence order
</a>. Where they say &ldquo;It will first process all explicit deny rules it finds. Then, it will process all explicit allow rules. If no deny or allow rule exists, WDAC will check for Managed Installer EA. Lastly, if none of these sets exist, WDAC will fall back on ISG&rdquo;. Contrary, in the code it seems Managed Installer and ISG (External Authorization) are checked before processing the FileRules.</p>
</blockquote>

<h3 id="cipexternalauthorizationcallback">CipExternalAuthorizationCallback</h3>

<p>This function contains the core functionality of SAC, and even thou it hasn&rsquo;t changed much from 21H2 to 22H2, there&rsquo;s a few details that make a big difference when SAC is enabled. Nonetheless, most of what we will discuss is meant to be used (And was already being used) by <code>AppLocker</code> and <code>ISG</code>, so on the bright side we will also learn a bit from that 🙂. To get an overview of how we got to this point, here&rsquo;s the stack when we reach the External Authorization callback for the validation of an unsigned image.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-caddyfile" data-lang="caddyfile">0: kd&gt; k
 # Child-SP          RetAddr               Call Site
00 fffffd0d`51916448 fffff803`24119485     CI!CipExternalAuthorizationCallback
01 fffffd0d`51916450 fffff803`2411dec8     CI!SIPolicyValidateImageInternal+0xbd
02 fffffd0d`51916580 fffff803`24104b8a     CI!SIPolicyObjectValidationEngine+0x150
03 fffffd0d`51916680 fffff803`240f8ad4     CI!CipApplySiPolicyEx+0x61e
04 fffffd0d`51916850 fffff803`240f4899     CI!CipApplySIPolicyUMCI+0x198
05 fffffd0d`519168c0 fffff803`240f2734     CI!CipValidateImageHash+0x441
06 fffffd0d`51916a00 fffff803`211a0535     CI!CiValidateImageHeader+0x934
07 fffffd0d`51916ba0 fffff803`2119ffc3     nt!SeValidateImageHeader+0xe9
08 fffffd0d`51916c50 fffff803`210dde43     nt!MiValidateSectionCreate+0x493</code></pre></div>
<p>The function will start by checking the policy options <code>Intelligent Security Graph Authorization</code> or <code>Managed Installer</code>, if none of those options is set in then this function will exit and <code>SIPolicyValidateImageInternal</code> will proceed to process the policy FileRules &ndash; We will see this later in the post.</p>

<p>In case any of the options is set, the next step is to determine if the image is trusted based on the signing level. This is done by using the <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/event-tag-explanations#validatedsigninglevel" target="_blank">ValidatedSigningLevel</a> obtained for the image and comparing this value against the bitmask with index <code>0xC</code> inside the global variable <code>g_CipWhichLevelComparisons</code>.</p>

<blockquote>
<p><strong>Quick Note:</strong> The global variable <code>g_CipWhichLevelComparisons</code> stores a pointer to an array of <code>ULONGs</code>. Each value represents the level of comparisons that apply to this signing level. Is usually used together with the validated signing level to determine different actions/options for the image. For instance, for a validated signing level equal to &ldquo;File Unsigned&rdquo;, which would be index 1 in the array, the bitmask is <code>0xFFFFFFFE</code> so most of the times this bitmask is tested the result will be positive. In other instances, as mentioned above, the index is hardcoded in the code to only act on validated signing levels that match the bitmask for that index. The following table hopefully will help understand the correlation between <code>g_CipWhichLevelComparisons</code> and <code>ValidatedSigningLevel</code></p>
</blockquote>

<table>
<thead>
<tr>
<th>ValidatedSigningLevel Value</th>
<th align="center">ValidatedSigningLevel mask</th>
<th align="center">g_CipWhichLevelComparisons bitmask</th>
</tr>
</thead>

<tbody>
<tr>
<td>Signing level hasn&rsquo;t yet been checked</td>
<td align="center">2^0 = <em>0x1</em></td>
<td align="center"><em>0xFFFFFFFF</em></td>
</tr>

<tr>
<td>File is unsigned</td>
<td align="center">2^1 = <em>0x2</em></td>
<td align="center"><em>0xFFFFFFFE</em></td>
</tr>

<tr>
<td>Trusted by WDAC policy</td>
<td align="center">2^2 = <em>0x4</em></td>
<td align="center"><em>0x5994</em></td>
</tr>

<tr>
<td>Developer signed code</td>
<td align="center">2^3 = <em>0x8</em></td>
<td align="center"><em>0x59FC</em></td>
</tr>

<tr>
<td>Authenticode signed</td>
<td align="center">2^4 = <em>0x10</em></td>
<td align="center"><em>0x5970</em></td>
</tr>

<tr>
<td>Microsoft Store signed app PPL</td>
<td align="center">2^5 = <em>0x20</em></td>
<td align="center"><em>0x5920</em></td>
</tr>

<tr>
<td>Microsoft Store-signed</td>
<td align="center">2^6 = <em>0x40</em></td>
<td align="center"><em>0x5960</em></td>
</tr>

<tr>
<td>Signed by an AV whose product is using AMPPL</td>
<td align="center">2^7 = <em>0x80</em></td>
<td align="center"><em>0x5080</em></td>
</tr>

<tr>
<td>Microsoft signed</td>
<td align="center">2^8 = <em>0x100</em></td>
<td align="center"><em>0x5900</em></td>
</tr>

<tr>
<td>Unknown</td>
<td align="center">2^9 = <em>0x200</em></td>
<td align="center"><em>0x59F4</em></td>
</tr>

<tr>
<td>Unknown</td>
<td align="center">2^10 = <em>0x400</em></td>
<td align="center"><em>0x0</em></td>
</tr>

<tr>
<td>Only used for signing of the .NET NGEN compiler</td>
<td align="center">2^11 = <em>0x800</em></td>
<td align="center"><em>0x800</em></td>
</tr>

<tr>
<td>Windows signed</td>
<td align="center">2^12 = <em>0x1000</em></td>
<td align="center"><em>0x5000</em></td>
</tr>

<tr>
<td>Unknown</td>
<td align="center">2^13 = <em>0x2000</em></td>
<td align="center"><em>0x0</em></td>
</tr>

<tr>
<td>Windows TCB signed</td>
<td align="center">2^14 = <em>0x4000</em></td>
<td align="center"><em>0x4000</em></td>
</tr>
</tbody>
</table>

<p>As can be seen in the table, index <code>0xC</code> represents bitmask <code>0x5000</code> which means for &ldquo;Windows Signed&rdquo; &amp; &ldquo;Windows TCB signed&rdquo;. Also the following two levels &ldquo;Only used for signing of the .NET NGEN compiler&rdquo; and  &ldquo;Signed by an AV whose product is using AMPPL&rdquo; will also be included in the list of trusted images. From here the function will proceed to call <code>CipCheckSmartlockerEAandProcessToken</code> to obtain the first validation score.</p>

<blockquote>
<p>I feel like this is a good moment to discuss namings, and hopefully someone from MS can reach out to me and clarify the namings. On one side we have <code>Smart App Control</code> and <code>Nights Watch</code>, then we have <code>AppLocker</code> where the internal name seems to be <code>SmartLocker</code>. There&rsquo;re 4 different names for things that are the same or very similar. It&rsquo;s definitely a bit confusing, especially when reversing 🤣</p>
</blockquote>

<p>The function has the following prototype:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c">NTSTATUS 
<span style="color:#50fa7b">CipCheckSmartlockerEAandProcessToken</span>(
        PFILE_OBJECT FileObject,
        PTOKEN TokenObject,
        PCI_VALIDATION_CTX ValidationCtx,
        <span style="color:#8be9fd">bool</span> IsTrustedSigning,
        PVALIDATE_SCORE Score
        );</code></pre></div>
<p>This function has two paths, one of them always being executed and the other based on the boolean <code>IsTrustedSigning</code>. If not trusted, then the following EAs will be queried for the FileObject being validated &ndash; It also tries to obtain the same EAs from the current Process FileObject, but other than storing those in the Validation Context I don&rsquo;t see them being used elsewhere.</p>

<ul>
<li><em>$Kernel.Smartlocker.Hash</em>: Contains the Hash of the image</li>
<li><em>$Kernel.Purge.Smartlocker.Valid</em>: Boolean to determine if valid</li>
<li><em>$Kernel.Smartlocker.OriginClaim</em>: Contains the structure I named <code>EA_ORIGIN_CLAIM</code></li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _EA_ORIGIN_CLAIM {
  INT32 DataVersion;
  INT32 Origin;
  INT32 Type;
  INT32 Generation;
  INT64 SessionId;
  INT64 field_18;
  INT64 SubSessionId;
  INT64 field_28;
  INT32 SmartScreenClaim;
  INT32 RevocationId;
  UNICODE_STRING FileName;
} EA_ORIGIN_CLAIM, <span style="color:#ff79c6">*</span>PEA_ORIGIN_CLAIM;</code></pre></div>
<p>If a valid EA is obtained, then the OriginClaim structure will be checked to determine a score for the image. The <em>Origin</em> value will determine the first score, if <em>Origin</em> == 0, then <code>Score |= 1</code>, if <em>Origin</em> == 1, then <code>Score |= 0x1002</code></p>

<blockquote>
<p>I have to apologize here because I don&rsquo;t have much info about this. This is most likely related to the special collection of rules in <code>AppLocker</code> used by WDAC when the <code>Managed Installer</code> option is set in the policy. From what I&rsquo;ve seen, I know <code>appid.sys</code> does set this EAs and another way to set this EAs is through the CI callback <code>CiSetCachedOriginClaim</code>. This function gets called by the kernel when issuing the syscall <code>NtSetCachedSigningLevel</code> with Flag <code>0x2000</code>, of course is not as easy as calling this syscall to set the EA OriginClaim, in case this syscall previous mode is UserMode, then <code>NtSetCachedSigningLevel2</code> will make sure the request is coming from a Protected process.</p>
</blockquote>

<p>The next step, whether we checked the EAs, is to obtain the OriginClaim stored in the Token object. In the case of the Token object, the OriginClaim is stored within the <a href="https://www.vergiliusproject.com/kernels/x64/Windows%2011/21H2%20(RTM)/_AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION" target="_blank">SecurityAttributes</a> list of the token, these attributes are stored as Authz SecurityAttributes and can be queried/retrieved by name using the function <code>SeQuerySecurityAttributesToken</code>. In our case two security attributes will be looked for:</p>

<ul>
<li><em>SMARTLOCKER://ORIGINCLAIM</em></li>
<li><em>SMARTLOCKER://SMARTSCREENORIGINCLAIMNOTINHERITED</em> (New in 22H2, previously &ldquo;SMARTLOCKER://SMARTSCREENORIGINCLAIM&rdquo;)</li>
</ul>

<p>The OriginClaim name will be looked up first. If found the score will be adjusted accordingly. Again, I don&rsquo;t have much info on this nor do I have information on how the structure for this claim looks (<code>appid.sys</code> sets this value token).<br />
Afterwards, the SmartScreen OriginClaim not inherited attribute will be queried, if it&rsquo;s found and flag <code>CLAIM_DANGEROUS_EXT (0x80)</code> (I named this flag based on the check, is not an official name) is set then the function will proceed to check if the ImageFile has what&rsquo;s considered a <em>DangerousExtension</em>. Also in all cases the code will check if the ImageFile has an <em>InstallerExtension</em>. For the Installer extension it will only check against <code>.msi</code>, for the case of Dangerous extension these are all the values:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// DangerousExtensions
</span><span style="color:#6272a4"></span><span style="color:#f1fa8c">&#34;.appref-ms&#34;</span>
<span style="color:#f1fa8c">&#34;.appx&#34;</span>
<span style="color:#f1fa8c">&#34;.appxbundle&#34;</span>
<span style="color:#f1fa8c">&#34;.bat&#34;</span>
<span style="color:#f1fa8c">&#34;.chm&#34;</span>
<span style="color:#f1fa8c">&#34;.cmd&#34;</span>
<span style="color:#f1fa8c">&#34;.com&#34;</span>
<span style="color:#f1fa8c">&#34;.cpl&#34;</span>
<span style="color:#f1fa8c">&#34;.dll&#34;</span>
<span style="color:#f1fa8c">&#34;.drv&#34;</span>
<span style="color:#f1fa8c">&#34;.gadget&#34;</span>
<span style="color:#f1fa8c">&#34;.hta&#34;</span>
<span style="color:#f1fa8c">&#34;.iso&#34;</span>
<span style="color:#f1fa8c">&#34;.js&#34;</span>
<span style="color:#f1fa8c">&#34;.jse&#34;</span>
<span style="color:#f1fa8c">&#34;.lnk&#34;</span>
<span style="color:#f1fa8c">&#34;.msc&#34;</span>
<span style="color:#f1fa8c">&#34;.msp&#34;</span>
<span style="color:#f1fa8c">&#34;.ocx&#34;</span>
<span style="color:#f1fa8c">&#34;.pif&#34;</span>
<span style="color:#f1fa8c">&#34;.ppkg&#34;</span>
<span style="color:#f1fa8c">&#34;.printerexport&#34;</span>
<span style="color:#f1fa8c">&#34;.ps1&#34;</span>
<span style="color:#f1fa8c">&#34;.rdp&#34;</span>
<span style="color:#f1fa8c">&#34;.reg&#34;</span>
<span style="color:#f1fa8c">&#34;.scf&#34;</span>
<span style="color:#f1fa8c">&#34;.scr&#34;</span>
<span style="color:#f1fa8c">&#34;.settingcontent-ms&#34;</span>
<span style="color:#f1fa8c">&#34;.sys&#34;</span>
<span style="color:#f1fa8c">&#34;.url&#34;</span>
<span style="color:#f1fa8c">&#34;.vb&#34;</span>
<span style="color:#f1fa8c">&#34;.vbe&#34;</span>
<span style="color:#f1fa8c">&#34;.vbs&#34;</span>
<span style="color:#f1fa8c">&#34;.vhd&#34;</span>
<span style="color:#f1fa8c">&#34;.vhdx&#34;</span>
<span style="color:#f1fa8c">&#34;.vxd&#34;</span>
<span style="color:#f1fa8c">&#34;.website&#34;</span>
<span style="color:#f1fa8c">&#34;.wsf&#34;</span>
<span style="color:#f1fa8c">&#34;.wsh&#34;</span></code></pre></div>
</div>

<p>If the ImageFile matches any of these values then the score will be set to <code>DangerousExtension (0x800)</code>, and a query to Defender will be issued by calling <code>CiCatDbSmartlockerDefenderCheck</code> (We will discuss more about this function later).<br />
The following pseudocode shows more or less how this last part for the SmartLocker not inherited attribute works</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// sizeof(TOKEN_ORIGIN_CLAIM) == 0x20C
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _TOKEN_ORIGIN_CLAIM { 
  ULONG Flags;
  WCHAR ImageFileName[MAX_PATH];
} TOKEN_ORIGIN_CLAIM;

PCLAIM_SECURITY_ATTRIBUTES_INFORMATION Attr <span style="color:#ff79c6">=</span> <span style="color:#8be9fd;font-style:italic">NULL</span>;
RtlInitUnicodeString(<span style="color:#ff79c6">&amp;</span>AttrName, <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;SMARTLOCKER://SMARTSCREENORIGINCLAIMNOTINHERITED&#34;</span>);

Status <span style="color:#ff79c6">=</span> SeQuerySecurityAttributesToken( Token, <span style="color:#ff79c6">&amp;</span>AttrName, <span style="color:#bd93f9">1</span>, Attr, AttrSize, <span style="color:#ff79c6">&amp;</span>RetLen );
<span style="color:#ff79c6">if</span> ( NT_SUCCESS( Status ) ) { <span style="color:#6272a4">// Let&#39;s imagine it worked, no error check nor STATUS_BUFFER_TOO_SMALL check
</span><span style="color:#6272a4"></span>  <span style="color:#ff79c6">if</span>( Attr<span style="color:#ff79c6">-&gt;</span>AttributeCount ) {
    <span style="color:#6272a4">// Not really this structure, the kernel uses a version of this but a bit modified
</span><span style="color:#6272a4"></span>    PCLAIM_SECURITY_ATTRIBUTE_V1 AttrV1 <span style="color:#ff79c6">=</span> Attr<span style="color:#ff79c6">-&gt;</span>Attribute.pAttributeV1;
    <span style="color:#ff79c6">if</span> ( AttrV1<span style="color:#ff79c6">-&gt;</span>ValueType <span style="color:#ff79c6">==</span> CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING <span style="color:#ff79c6">&amp;&amp;</span> 
        Attr<span style="color:#ff79c6">-&gt;</span>Values.pOctetString<span style="color:#ff79c6">-&gt;</span>ValueLength <span style="color:#ff79c6">==</span> <span style="color:#ff79c6">sizeof</span>(TOKEN_ORIGIN_CLAIM) ) {

      PTOKEN_ORIGIN_CLAIM Claim <span style="color:#ff79c6">=</span> Attr<span style="color:#ff79c6">-&gt;</span>Values.pOctetString<span style="color:#ff79c6">-&gt;</span>Value;
      <span style="color:#6272a4">// Copy Claim to ValidationCtx
</span><span style="color:#6272a4"></span>      <span style="color:#ff79c6">if</span> ( Claim<span style="color:#ff79c6">-&gt;</span>Flags <span style="color:#ff79c6">&amp;</span> CLAIM_DANGEROUS_EXT ) {
        <span style="color:#ff79c6">auto</span> isDangerExt <span style="color:#ff79c6">=</span> CipCheckForExtensionAgainstList( Claim<span style="color:#ff79c6">-&gt;</span>ImageFileName, DangerousExtensions );
        <span style="color:#ff79c6">if</span> ( isDangerExt )
          <span style="color:#ff79c6">*</span>Score <span style="color:#ff79c6">|=</span> DangerousExt;
      }
      <span style="color:#ff79c6">auto</span> isInstaller <span style="color:#ff79c6">=</span> CipCheckForExtensionAgainstList( Claim<span style="color:#ff79c6">-&gt;</span>ImageFileName, InstallerExtensions );

      <span style="color:#ff79c6">if</span> ( isDangerExt <span style="color:#ff79c6">||</span> isInstaller ) {
        RtlInitUnicodeString( <span style="color:#ff79c6">&amp;</span>FileName, Claim<span style="color:#ff79c6">-&gt;</span>ImageFileName );
        CiCatDbSmartlockerDefenderCheck( 
          <span style="color:#ff79c6">&amp;</span>FileName, 
          ValidationCtx<span style="color:#ff79c6">-&gt;</span>CurrentProcess, 
          <span style="color:#bd93f9">0</span>, 
          <span style="color:#8be9fd;font-style:italic">NULL</span>, 
          <span style="color:#ff79c6">&amp;</span>ReplySize, 
          <span style="color:#ff79c6">&amp;</span>ReplyData, ...);
        <span style="color:#6272a4">// Based on the answer might remove the DangerousExt from the score
</span><span style="color:#6272a4"></span>      }
    }
  }
}</code></pre></div>
</div>

<blockquote>
<p><em>Note:</em> Based on how the values from this function are used later to populate the TraceLogging strings, we know that the Defender considers all this part of the evaluation process as: <code>IsDefenderShell</code>.</p>
</blockquote>

<p>This is more or less what we would have for a process being launched from explorer by double-clicking on it, right after the call to obtain the security attribute</p>

<p><img src="/images/smartAppControl/part2/SmartLockerOriginClaim.png" alt="alt img" title="SmartLockerOriginClaim" /></p>

<p><details>
<summary><b>Bonus Section:</b> Where does this OriginClaim Token comes from <i>(Click to Expand)</i></summary></p>

<p>Just as a little bonus before going back into <code>CipExternalAuthorizationCallback</code>, I was quite curious on how or when this OriginClaim was being added into the token. So I dug a bit into it and ended up going into the following rabbit hole. First, we search and found the kernel has a reference to the SmartScreen OriginClaim string and that is being used in function <code>SepAddTokenOriginClaim</code>. In this function we see that the last parameter indicates if the token to add will be either:</p>

<ul>
<li><em>SMARTLOCKER://SMARTSCREENORIGINCLAIM</em> -&gt; Last parameter set to FALSE</li>
<li><em>SMARTLOCKER://SMARTSCREENORIGINCLAIMNOTINHERITED</em> -&gt; Last parameter set to TRUE</li>
</ul>

<p>We are interested in the latter, so we found that this function is being called with the last parameter set to TRUE from <code>SeDuplicateTokenAndAddOriginClaim</code> which comes from <code>NtCreateUserProcess</code>. We can see that the structure <code>TOKEN_ORIGIN_CLAIM</code> stored in the token is already passed to <code>SeDuplicateTokenAndAddOriginClaim</code> by <code>NtCreateUserProcess</code>. Tracing this argument back, we see it is part of the &ldquo;Create Process Context&rdquo; being allocated in <code>PspBuildCreateProcessContext</code> and actually when initializing this context this is taken from the <code>PS_ATTRIBUTES_LIST</code> for the attribute with value <code>PS_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM (0x20017)</code>. To my surprise, this value actually comes from UserMode, so it&rsquo;s not something created by the kernel.</p>

<p>Knowing that &ndash; And even thou I&rsquo;m not a huge fan of reversing UserMode nor C++ &ndash; we had to check where this value was being added to the <code>PS_ATTRIBUTES_LIST</code>. We go straight to <code>KernelBase</code> and check <code>CreateProcessInternalW</code>, here we can find the function <code>BasepConvertWin32AttributeList</code> which seems to convert the Attributes from the UserMode value to KernelMode representation &ndash; See the image, the attribute size matches the size of the OriginClaim structure.</p>

<p><img src="/images/smartAppControl/part2/AttributeConvert.png" alt="alt img" title="BasepConvertWin32AttributeList" /></p>

<p>But we still don&rsquo;t know where the <code>TOKEN_ORIGIN_CLAIM</code> comes from. <code>KernelBase</code> seems to get the AttributesList from the memory right after the StartupInfo &ndash; The size of <code>STARTUPINFOW</code> is actually <code>0x68</code>, but before calling <code>BasepConvertWin32AttributeList</code> the code checks if <code>StartupInfo-&gt;cb</code> is equal to <code>0x70</code>, if equal it means the value right after the size of <code>STARTUPINFOW</code> contains the list of attributes.</p>

<p>So let&rsquo;s find who set up this value, in my case I just set a breakpoint in the point where the OriginClaim value was being converted to the Kernel type and checked the stack. We find that the DLL calling <code>CreateProcessInternalW</code> is <code>windows.storage.dll</code> (Microsoft WinRT Storage DLL). To make this a bit shorter, basically there&rsquo;s two main classes involved in creating the process:
- <code>CInvokeCreateProcessVerb</code>
- <code>CBindAndInvokeStaticVerb</code></p>

<p>The attributes are copied from <code>CBindAndInvokeStaticVerb</code> into <code>CInvokeCreateProcessVerb</code> when instantiating the class and later on, <code>CInvokeCreateProcessVerb</code> will copy them after the <code>STARTUPINFOW</code> and proceed to update the <code>StartupInfo-&gt;cb</code> from <code>0x68</code> to <code>0x70</code> &ndash; Check <code>CInvokeCreateProcessVerb::CallCreateProcess</code>.</p>

<p>So looking to find where <code>CBindAndInvokeStaticVerb</code> gets the attribute for the OriginClaim, we land in the class function <code>CheckSmartScreen</code>. This function calls internally to <code>CheckSmartScreenWithAltFile</code> which will do things like check if it should invoke SmartScreen, if the file is a symlink, get the DisplayName with <code>SIGDN</code> equal to <code>SIGDN_FILESYSPATH</code> or check if &ldquo;IsWindowsLockdownDangerousExtensionEnforcement&rdquo; is on (This last point is done by calling the external DLL <code>Wldp.dll</code>). It will then call into <code>ZoneCheckFile</code> which will do more checks like call <a href="https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-associsdangerous" target="_blank">AssocIsDangerous</a> and check if &ldquo;WindowsLockdownDangerousExtensionValidation&rdquo; is on. Lastly it will call into the method <code>SafeOpenPromptForShellExec</code> from DLL <code>shdocvw.dll</code>, which determines the flags to set in the <code>TOKEN_ORIGIN_CLAIM</code>. Finally, a call into <code>CInvokeCreateProcessVerb</code> class method <code>UpdateProcThreadAttribute</code> will add the OriginClaim attribute into the <code>PS_ATTRIBUTES_LIST</code>.</p>

<p><img src="/images/smartAppControl/part2/UpdateProcAttrStack.png" alt="alt img" title="UpdateProcThreadAttribute" /></p>

<blockquote>
<p>Keep in mind that when SAC is enabled, some of the values from Reputation-Based protection (SmartScreen) are enabled by default and cannot be disabled.
End of the Bonus! Back to <code>CipExternalAuthorizationCallback</code>
</details></p>
</blockquote>

<p>That&rsquo;s all for <code>CipCheckSmartlockerEAandProcessToken</code> and now we are back into <code>CipExternalAuthorizationCallback</code> with a score obtained from either the EAs,  the Token or both.</p>

<p>From here on, we enter into the piece of code that was being used by the <strong>Intelligent Security Graph</strong>, that now has been extended to add some SAC functionality. First of all, the policy option <code>Intelligent Security Graph Authorization</code> will be checked again (If not set the function will exit with the value obtained from <code>CipCheckSmartlockerEAandProcessToken</code>). If the value is active in the policy, which is the case for SAC policies, the function will use the previously discussed <strong>IsTrustedSigning</strong> to determine if it should continue or not. If the image is trusted the following check will be done</p>

<ul>
<li>If the <em>ValidatedSigningLevel</em> is equal to &ldquo;Signed by an AV whose product is using AMPPL (7)&rdquo; and the policy has the value <code>VerifiedAndReputableAllowAntiMalware</code>, then the score will be OR&rsquo;ed with the value <code>AllowAntiMalware (0x100000)</code> and the function will return.</li>
</ul>

<p>If the image is not trusted then the function will proceed to query Defender. As mentioned previously, the function to issue a query to the defender is <code>CiCatDbSmartlockerDefenderCheck</code>. This function will receive two <code>MPFILE_TRUST_EXTRA_INFO</code> structures, one filled with the Request data and one to receive the Reply data. The code will also pass the FileName from the FileObject. The <code>MPFILE_TRUST_EXTRA_INFO</code> structure looks something like this &ndash; Some fields might be a bit off, I didn&rsquo;t want to spend much time reversing the UserMode part of Defender 😄.</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_INFO_RESULT {
  INT32 Unknown;
  ULONG32 ClientStatusCode;
  ULONG32 CloudHTTPCode;
  GUID EngineReportGUID;
} MP_INFO_RESULT, <span style="color:#ff79c6">*</span>PMP_INFO_RESULT;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_INFO_HASH {
  INT32 Reserved; <span style="color:#6272a4">// Must be 1
</span><span style="color:#6272a4"></span>  INT32 Unknown;  <span style="color:#6272a4">// Set to 1 on Request and 0 on Reply
</span><span style="color:#6272a4"></span>  <span style="color:#ff79c6">struct</span> HASH_DATA {
    ALG_ID AlgId;
    INT32 Size;
    BYTE Data[<span style="color:#ff79c6">sizeof</span>(Size)];
  };
} MP_INFO_HASH, <span style="color:#ff79c6">*</span>PMP_INFO_HASH;

<span style="color:#ff79c6">enum</span> MP_NW_CONTROL {
  SwitchNWOff <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2</span>,
  SwitchNWToEnforcementMode <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x4</span>,
  IsUnfriendlyFile <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x8</span> <span style="color:#6272a4">// Not really NW control, but it is here :D
</span><span style="color:#6272a4"></span>}

<span style="color:#ff79c6">union</span> MP_EXTRA_INFO {
  MP_INFO_HASH HashData;
  MP_INFO_RESULT Result;
  MP_NW_CONTROL NightsWatchControl; 
  PWCHAR PrivacyTag;
};

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MPTRUST_INFO {
  INT32 Size;
  INT32 TrustLevel;
  INT64 Trust;
} MPTRUST_INFO, <span style="color:#ff79c6">*</span>PMPTRUST_INFO;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MPFILE_TRUST_EXTRA_INFO {
  INT32 RequestType;
  INT32 ReplyType;
  INT32 Size;
  PMP_EXTRA_INFO Information; 
} MPFILE_TRUST_EXTRA_INFO, <span style="color:#ff79c6">*</span>PMPFILE_TRUST_EXTRA_INFO;</code></pre></div>
</div>

<p>The communication between the parties is achieved using RPC. <code>CI.dll</code> will implement the Client and the Server will be implemented in <code>cryptcatsvc.dll</code> &ndash; For the record, the IID of the RPC stub is <code>f50aac00-c7f3-428e-a022a6b71bfb9d43</code>.</p>

<p><code>cryptcatsvc</code> runs inside the service <code>CryptSvc</code>. Among the dispatch functions for the RPC server the following are interesting for our case:</p>

<ul>
<li><em>s_SSCatDBSmartlockerDefenderCheck</em> (Already present in 22H1)</li>
<li><em>s_SSCatDBSmartlockerDefenderCheck2</em> (New to 22H2)</li>
<li><em>s_SSCatDBSendSmartAppControlBlockToast</em></li>
<li><em>s_SSCatDBSendSmartAppControlSwitchEnforceToast</em></li>
</ul>

<blockquote>
<p>The big difference between the v1 and v2 of the SmartLockerDefenderCheck function, is that in v2 the function accepts a Request and Reply <code>MPFILE_TRUST_EXTRA_INFO</code> as part of its arguments. Both function end up calling the helper function <code>CatDBSmartlockerDefenderCheckHelper</code></p>
</blockquote>

<p>From these functions CI will call into <code>s_SSCatDBSmartlockerDefenderCheck2</code> which will first load <code>MpClient.dll</code></p>

<blockquote>
<p><strong>Note:</strong> On the first execution SmartLocker will be enabled in the Defender Config. The function will call into the <code>MpClient</code> exported function <code>MpSmartLockerEnable</code>. This function will simply register the Defender ELAM cert info (Opening a handle to <code>Wdboot.sys</code> and calling <a href="https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-installelamcertificateinfo" target="_blank">InstallELAMCertificateInfo</a>) and then using RPC it will call the method <code>ServerMpEnableSmartLocker</code> from <code>MpSvc.dll</code>, which will check if <em>SmartLockerMode</em> is set in the Defender config and if not it will write it.</p>
</blockquote>

<p>Once the handle to the library is opened, the function will use the filename provided by <code>CI.dll</code> to open a handle to the file which will be passed to the <code>MpClient</code> exported function <code>MpQueryFileTrustByHandle2</code> &ndash; This function is only called if we come from <strong>DefenderCheck2</strong>, in case of the old version <strong>DefenderCheck</strong>, <code>MpQueryFileTrustByHandle</code> will be called instead.</p>

<p>Inside <code>MpQueryFileTrustByHandle2</code>, the code will use the handle to the file to create a file-mapping which will be used by the defender to do a memory scan on it. The following InSequence functions will be executed by issuing RPC calls from <code>MpClient</code> (Client) to <code>MpSvc</code> (Server) &ndash; Obviously all the function calls we just saw accept both <code>MPFILE_TRUST_EXTRA_INFO</code> set by <code>CI.dll</code> as part of their parameters.</p>

<ul>
<li><em>ServerMpRpcMemoryScanStart:</em> Set up a <code>CMpMemScanContext</code> &amp; <code>CMpMemScanEngineVfz</code> (With GetAttributeTrustCheck as the GetAttributes function), and proceed with the scan asynchronously.</li>
<li><em>ServerMpRpcMemoryScanQueryNotification:</em> Retrieve the Scan information.</li>
<li><em>ServerMpRpcMemoryScanClose:</em> Close and clean <code>CMpMemScanContext</code>.</li>
</ul>

<blockquote>
<p>The internals of these functions are out of the scope of this post, to dig in the MpSvc and it&rsquo;s ScanEngine we would require a few more posts 😄. The point I want to get across by mentioning this is that when SAC is enabled the Defender will be actively scanning files and making cloud queries.</p>
</blockquote>

<p>From the information retrieved from the scan there&rsquo;s three possible signals:
- <code>0x31001</code>: Retrieved MPTRUST_INFO (IGS)
- <code>0x31002</code>: Retrieved MPFILE_TRUST_EXTRA_INFO (SAC)
- <code>0x4005</code>:  Related to <em>RSIG_VIRINFO</em></p>

<p>Lastly to finish with the Defender communication the following image shows both the Client (CI) &amp; Server (cryptcatsvc) stacks when the code reaches the Defender.</p>

<p><img src="/images/smartAppControl/part2/DefenderRpcCall.png" alt="alt img" title="Defender RPC call" /></p>

<blockquote>
<p>One thing to mention here is that if we have SAC in enforce state and we don&rsquo;t have an internet connection in the machine then the default action is to block the process, and a notification saying &ldquo;Smart App Control is unable to verify this app. Please check your internet connection and try again&rdquo; will be displayed.</p>
</blockquote>

<p>Back to the external authorization callback, if the RPC call failed, the policy setting <code>VerifiedAndReputableAllowUnknown</code> is not set and the ValidateSigningLevel is none of the following:</p>

<ul>
<li>Microsoft Store signed app PPL (Protected Process Light)</li>
<li>Microsoft Store-signed</li>
<li>Microsoft signed</li>
<li>Windows signed</li>
<li>Only used for signing of the .NET NGEN compiler</li>
<li>Windows Trusted Computing Base signed</li>
</ul>

<p>then the validation score will be OR&rsquo;ed with the value <code>Unattainable (0x40000)</code> and the function will return. In case the RPC call was successful, then function <code>CiHandleDefenderSignals</code> will be called. As the name implies this function will handle the messages sent back by the Defender. It will iterate the count of elements returned, where each element is of type <code>MPFILE_TRUST_EXTRA_INFO</code>. Based on the <em>ReplyType</em> field it will perform different actions. The two more interesting cases are: First, when a trust result is returned. In this case <em>Information</em> will point to a <code>MP_INFO_RESULT</code>, and the values from it will be copied to the Validation Context:</p>

<p><img src="/images/smartAppControl/part2/CopyResultToValidationCtx.png" alt="alt img" title="Copy Result To ValidationCtx" /></p>

<p>The second interesting case is where <em>Information</em> points to a <code>MP_NW_CONTROL</code> enum. In this case, based on the Control command the feature will be either disabled or switched to enforce mode. This will basically update the <code>VerifiedAndReputablePolicyState</code> RegKey and update the policies in a WorkItem</p>

<p><img src="/images/smartAppControl/part2/HandleNWControl.png" alt="alt img" title="Handle NW Control" /></p>

<blockquote>
<p>In the case we are changing from the learning mode to the enforce mode an RPC call to function <code>s_SSCatDBSendSmartAppControlSwitchEnforceToast</code> will be issued. Within this function, the DLL <code>wldp.dll</code> will be loaded to then call function <code>WldpSendSmartAppControlSwitchEnforceToast</code>.</p>
</blockquote>

<p>After coming back from the signal handling routine, there&rsquo;s a little nuance. If the NW control command had the flag <code>IsUnfriendlyFile</code> set, then the Score will be updated with value <code>UnfriendlyFile (0x80000)</code> and the function will return. If the flag is not set then the TrustInfo along with the FileObject will be passed into function <code>CipSetFileCache</code> with flag <code>0x82</code> which means the EA <code>$Kernel.Purge.CIpCache</code> will be used to store this info.</p>

<p>Lastly, the Score needs to be adjusted based on the trust returned by the Defender. There&rsquo;s 5 options here:</p>

<ul>
<li><em>Trust == 1:</em> The score will be OR&rsquo;ed with the value <code>0x202</code> &ndash; I don&rsquo;t know much about this value 😕</li>
<li><em>Trust == -1 (0xFFFFFFFF):</em> If the policy setting <em>VerifiedAndReputableAllowUnknown</em> is set then score will be OR&rsquo;ed with the value <code>AllowUnknown (0x20000)</code></li>
<li><em>Trust == -2 (0xFFFFFFFE):</em> The score will be OR&rsquo;ed with the value <code>Malicious (0x80)</code></li>
<li><em>Trust == -3 (0xFFFFFFFD):</em> The score will be OR&rsquo;ed with the value <code>PUA (0x100)</code></li>
<li>Any other case, the score will be OR&rsquo;ed with the value <code>0x42</code>.</li>
</ul>

<p>And that&rsquo;s pretty much all for the external authorization callback, now we go back to <code>SIPolicyValidateImageInternal</code> from where the external authorization callback was called!</p>

<h3 id="sipolicyvalidateimageinternal">SIPolicyValidateImageInternal</h3>

<p>Before we jumped into the external authorization callback, we discuss how the <code>SIPolicyObjectValidationEngine</code> function iterates over the policies and calls into the internal <code>SIPolicyValidateImageInternal</code> which will later call the external auth callback. So now, after the callback was called we are back into <code>SIPolicyValidateImageInternal</code> with the validation score returned from it. If SAC is enabled then the function will proceed to evaluate the score, and both propagate this score to the validation engine score and set the <code>NTSTATUS</code> accordingly to the score.</p>

<p><img src="/images/smartAppControl/part2/AuthCbStatus.png" alt="alt img" title="Set NTSTATUS based on score" /></p>

<p>As can be seen in the image, in most of the branches it will set the respective <code>NTSTATUS</code> as the validation status and then it will jump into what I called <code>ProcessDbgAndReprieve</code>. This is no more than a method that will check if the Kernel debugger is attached to log the policy violation in the debugger console. Similar to this output (Just an example, this is coming from another point, that&rsquo;s why the error code doesn&rsquo;t match the ones seen above):</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-caddyfile" data-lang="caddyfile">kd&gt; g
KDTARGET: Refreshing KD connection

************************************************************************************
*  \Device\HarddiskVolume3\Users\n4r1B\Desktop\usbview.exe violated CI base policy {0283ac0f-fff1-49ae-ada1-8a933130cad6}.CIP with error code 0xc0e90002 for scenario 1.
*  It is now allowed to load because debugger is attached.
************************************************************************************</code></pre></div>
<p>In case none of the branches from the previous image is followed &ndash; Or the case where the score is <code>Unattainable</code> but <code>AllowUnknown</code> is set &ndash; the function will proceed to evaluate the object against the Policy Rules. The file rules will be checked first, this will be done inside the function <code>SIPolicyMatchFileRules</code>. This function will receive, among other things, the following parameters:</p>

<ul>
<li>Policy with the file rules to evaluate</li>
<li>The value of the scenario to evaluate</li>
<li>OriginalFileName</li>
<li>InternalName</li>
<li>FileDescription</li>
<li>ProductName</li>
</ul>

<blockquote>
<p>I strongly recommend reading the whole Section <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/select-types-of-rules-to-create#windows-defender-application-control-file-rule-levels" target="_blank">&ldquo;Understand Windows Defender Application Control (WDAC) policy rules and file rules&rdquo;</a> of the MSDN to learn more about Policy Rules and the different options that can be used for them.</p>
</blockquote>

<p>In a similar fashion as we saw in Part 1 with the Policy Secure Settings, the function will set up a structure with the data that will pass as the <code>key</code> to the function <em>bsearch</em>. The key structure has the following prototype</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _POLICY_BINARY_DATA {
  INT32 Size;
  PVOID Data;
} POLICY_BINARY_DATA, PPOLICY_BINARY_DATA;

<span style="color:#6272a4">//
</span><span style="color:#6272a4">// Sorry I don&#39;t have much more info than to what Version of policy each string correlates :(
</span><span style="color:#6272a4">//
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _POLICY_STRING_DATA {
  INT32 StringType;
  UNICODE_STRING String;
  UNICODE_STRING StringPolicyV4;
  UNICODE_STRING String1PolicyV4;
  UNICODE_STRING String2PolicyV4;
  UNICODE_STRING StringPolicyV7;
  UNICODE_STRING StringPolicyV5;
  PVOID DataPolicyV5;
  PVOID V3DataStart;
  PVOID V3DataEnd;
  INT32 StringsCountPolicyV3;
  PUNICODE_STRING StringsPolicyV3;
  POLICY_BINARY_DATA BinaryData;
} POLICY_STRING_DATA, <span style="color:#ff79c6">*</span>PPOLICY_STRING_DATA;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SEARCH_FILE_RULES_KEY {
  INT32 PolicyStringsVersion;
  PUNICODE_STRING OriginalFileName;
  PUNICODE_STRING InternalName;
  PUNICODE_STRING FileDescription;
  PUNICODE_STRING ProductName;
  PUNICODE_STRING AppxPackageString;
  PPOLICY_STRING_DATA PolicyStringsData;
} SEARCH_FILE_RULES_KEY, <span style="color:#ff79c6">*</span>PSEARCH_FILE_RULES_KEY;</code></pre></div>
</div>

<p>The <code>base</code> and the <code>num</code> for the bsearch function will be taken from the <code>SI_POLICY</code> structure. When the policy is parsed into the <code>SI_POLICY</code> structure, an array with two scenarios is set up. Each scenario contains it&rsquo;s specific File Rules, Allowed Signers, Denied Signers and Exception Rules. As I mentioned above, when calling <code>SIPolicyMatchFileRules</code> the specific number of the scenario to evaluate is passed to the function. This number will work as an index for the function to know which element of the Scenarios array to pick. Each scenario is represented by the following structure</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_RULES {
  PUINT32 IndexArray[];
  UITN64 field_8;
  UINT64 field_10;
  INT32 Count;
} SI_RULES, <span style="color:#ff79c6">*</span>PSI_RULES; 

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_POLICY_SIGNERS_RULES {
  SI_RULES Rules;
  UINT64 field_20;
  SI_RULES ExceptionRules;
  PVOID field_48;
  PVOID field_50;
} SI_POLICY_SIGNERS_RULES, <span style="color:#ff79c6">*</span>PSI_POLICY_SIGNERS_RULES;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_FILE_RULES {  
  SI_RULES Rules;
  UINT64 field_20;
} SI_FILE_RULES, <span style="color:#ff79c6">*</span>PSI_FILE_RULES;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_POLICY_SCENARIO {
  UINT32 AlgId;
  SI_POLICY_SIGNERS_RULES AllowedSignersRules;
  SI_POLICY_SIGNERS_RULES DeniedSignersRules;
  SI_FILE_RULES FileRules;
} SI_POLICY_SCENARIO, <span style="color:#ff79c6">*</span>PSI_POLICY_SCENARIO;</code></pre></div>
</div>

<p>If no FileName level file-rule matches, then the function will proceed to evaluate the file-rules that are at Hash level</p>

<p><img src="/images/smartAppControl/part2/HashLevelRules.png" alt="alt img" title="Hash level file-rules" /></p>

<p>If either the FileName or the Hash matches then the <code>SIPolicyMatchFileRules</code> returns <code>TRUE</code>, and the validation status will be set to <code>STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION</code>.</p>

<blockquote>
<p>If curious on what Hashes and FileNames are being used by the SAC policies, you can check the whole list under the <a href="https://gist.github.com/n4r1b/a2c026def8fb77e01ab231c43430bc90#file-sacenforce-xml-L49" target="_blank">FileRules</a> tag of the policy.</p>
</blockquote>

<p>If no file-rule matched, the next step, if the image is signed, is to verify the signature chain info against the Denied and Allowed signers. First, the denied signers will be checked. If a rule matches in this point, same as previously, the function will set the validation status to <code>STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION</code>. If no denied signers rule matches, the code will proceed to check the allowed signer rules. In this case if there&rsquo;s a match any previous status/score will be cleared. The process of verifying the image signature against the policy signatures is mainly done inside the function <code>SIPolicyValidateChainAgainstSigner</code>. This function will receive as it&rsquo;s first parameter the <code>SI_CHAIN_INFO</code> of the image and in <code>@r8</code> it will receive a <code>POLICY_SIGNERS_DATA</code>.</p>

<p>With regard to this <code>POLICY_SIGNERS_DATA</code> structure, basically the <code>SI_POLICY</code> structure keeps an array of <code>POLICY_SIGNERS_DATA</code>. These represent all the Allow and Deny signatures for both scenarios. The way the code knows which rules apply to which scenario, meaning which index of the <code>POLICY_SIGNERS_DATA</code> array to use is quite clever &ndash; And It&rsquo;s something I didn&rsquo;t explain before with the file rules, so now it&rsquo;s a good moment to check it &ndash; If you go back and check the <code>SI_POLICY_SCENARIO</code> structure, you&rsquo;ll see that for each rule type structure (File, Allow, Deny) there&rsquo;s a <code>SI_RULES</code> structure that contains a field I called <code>IndexArray</code>. Basically this is an array of indexes that indicate which index from the arrays with the data has to be used for this specific scenario and rule. Let&rsquo;s see a quick pseudocode snippet to understand this a bit better</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#6272a4">// Imagine we want to check for scenario 1, the Allowed signatures using `SIPolicyValidateChainAgainstSigner`
</span><span style="color:#6272a4"></span>PSI_POLICY Policy; <span style="color:#6272a4">// Let&#39;s assume we have the handle to the policy here
</span><span style="color:#6272a4"></span>PSI_POLICY_SCENARIO Scenario <span style="color:#ff79c6">=</span> Policy<span style="color:#ff79c6">-&gt;</span>ScenariosRules[<span style="color:#bd93f9">1</span>]; <span style="color:#6272a4">// Get the Scenario 1
</span><span style="color:#6272a4"></span>PSI_POLICY_SIGNERS_RULES AllowSigRules <span style="color:#ff79c6">=</span> Scenario<span style="color:#ff79c6">-&gt;</span>AllowedSignersRules; <span style="color:#6272a4">// Get Allowed Signatures for scenario 1
</span><span style="color:#6272a4"></span>
<span style="color:#ff79c6">while</span> ( i <span style="color:#ff79c6">&lt;</span> AllowSigRules<span style="color:#ff79c6">-&gt;</span>Rules.Count ) { <span style="color:#6272a4">// Iterate all the Allowed Signature Rules
</span><span style="color:#6272a4"></span>  INT32 Index <span style="color:#ff79c6">=</span> AllowSigRules<span style="color:#ff79c6">-&gt;</span>Rules.IndexArray[i]; <span style="color:#6272a4">// Get the index that will be used to
</span><span style="color:#6272a4"></span>                                                    <span style="color:#6272a4">// obtain the PolicySignersData from the Policy
</span><span style="color:#6272a4"></span>  PPOLICY_SIGNERS_DATA AllowSigData <span style="color:#ff79c6">=</span> Policy<span style="color:#ff79c6">-&gt;</span>PolicySignersData[Index]; <span style="color:#6272a4">// Get the PolicySignersData
</span><span style="color:#6272a4"></span>
  <span style="color:#6272a4">// AllowSigData has the PolicySignerData for the First Allowed Signature of Scenario 1
</span><span style="color:#6272a4"></span>  <span style="color:#6272a4">// same behavior is used for Denied signatures and File-Rules (Getting a ptr to POLICY_STRING_DATA)
</span><span style="color:#6272a4"></span>  <span style="color:#ff79c6">if</span> ( SIPolicyValidateChainAgainstSigner( ChainInfo, AllowSigData ) ) {
    <span style="color:#6272a4">// A match was found
</span><span style="color:#6272a4"></span>    <span style="color:#ff79c6">break</span>;
  }
  i<span style="color:#ff79c6">++</span>;
}</code></pre></div>
<blockquote>
<p>This might not be 100% accurate and I&rsquo;m omitting quite a few sanity checks that are done in the middle, but I hope the idea gets across.</p>
</blockquote>

<p>To understand a bit better how the signatures are verified, up next you can find the prototype of the <code>POLICY_SIGNERS_DATA</code> &ndash; Remember this will apply both for Allowed and Denied Signers.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> struc _POLICY_SIGNERS_DATA {
  INT32 Type;
  UINT32 AlgId;
  POLICY_BINARY_DATA Value;
  INT32 EkusCount;
  INT32 EkuBufferLen;
  PVOID EkuBuffer;
  UNICODE_STRING IssuedBy;
  UNICODE_STRING IssuedTo;
  UNICODE_STRING field_48;
  PVOID SignersDataV3;
  ULONG FileRuleCount;
  PUINT32 FileRuleIndexArray[]; <span style="color:#6272a4">// Same as the SI_RULES-&gt;IndexArray
</span><span style="color:#6272a4"></span>} POLICY_SIGNERS_DATA, <span style="color:#ff79c6">*</span>PPOLICY_SIGNERS_DATA;</code></pre></div>
<p>Seeing the <code>SI_CHAIN_INFO</code> and the <code>POLICY_SIGNERS_DATA</code> you can more or less get an idea on how the comparison gets done in the function <code>SIPolicyValidateChainAgainstSigner</code>. Finally to sum up the validation of the Signers rules, here&rsquo;s an image taken at the entry of the <code>SIPolicyValidateChainAgainstSigner</code> when validating ProcessHacker with the SAC enforce policy.</p>

<p><img src="/images/smartAppControl/part2/SignerRulesValidation.png" alt="alt img" title="Signer Rules Validation" /></p>

<blockquote>
<p>To be honest, to reach to the point of this image I had to modify the codeflow a bit. Since on the first signature check the <em>Type</em> would match and then it would exit the loop. I wanted to reach this point since there&rsquo;s more info in this <code>POLICY_SIGNERS_DATA</code> than in the first one checked. On the first oned checked, the only filled value is the <em>Type</em> (Set to <code>0x14</code>). I&rsquo;ve tried to find information with regard to this Type value but I can&rsquo;t find anything. If someone knows more about this, please reach out 🙂!!</p>
</blockquote>

<p>So after this whole process is run for every active policy and supplemental policy, we will be back into the function <code>CipApplySiPolicyEx</code> with a <code>CI_VALIDATION_RESULT</code> for each BasePolicy. The results from the supplemental policies are written into the same <code>CI_VALIDATION_RESULT</code> as the BasePolicy. At this point the function won&rsquo;t do much more than iterate the validation results storing those in the Validation Context. Also at this point the SmartLocker event will be logged inside the function <code>CiLogSIPolicySmartlockerEvent</code>. Four type of events can be logged here:</p>

<ul>
<li>SmartlockerOperationalAudit (EventId: 3091)</li>
<li>SmartlockerOperationalFailure (EventId: 3092)</li>
<li>SmartlockerVerbose (EventId: 3088)</li>
<li>SmartlockerOperationalSuccess (EventId: 3090)</li>
</ul>

<p><img src="/images/smartAppControl/part2/SmartlockerOperationalFailure.png" alt="alt img" title="SmartlockerOperationalFailure" /></p>

<p>We are almost done, now we will go up the call stack, propagating the validation status to functions above. Finally, we will get back to the CI entrypoint <code>CiValidateImageHeader</code>, as before there&rsquo;s not much more we are gonna discuss in this function. Only interesting point regarding SAC, is that in case the SigningLevel matches any of the following:</p>

<ul>
<li>Signing level hasn&rsquo;t yet been checked</li>
<li>File is unsigned</li>
<li>Trusted by Windows Defender Application Control policy</li>
<li>Developer signed code</li>
</ul>

<p>and the SAC result is to allow the execution, then the operation will be logged using the function <code>CipInstrumentNightsWatchAllow</code>. This function can write four TraceLogging-based events for providers <em>CodeIntegrity.NWActivityVerbose</em> &amp; <em>CodeIntegrity.NWActivity</em> with the following names.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-caddyfile" data-lang="caddyfile">EventName
---------
QuestionableAllow
OriginClaimData
Allow
QuestionableAllowSignatureInfo</code></pre></div>
<blockquote>
<p>When this function executes either QuestionableAllow or Allow will be logged. If the path to log QuestionableAllow is taken then QuestionableAllowSignatureInfo &amp; OriginClaimData will also be written if the required data is available.</p>
</blockquote>

<p>Since these are Trace-Logging based events we need to do some magic to capture the traces. Thankfully for us mortals Matt has already done all the hard work of researching &amp; documenting the process to get this type of events. Take a look at his post <a href="https://posts.specterops.io/data-source-analysis-and-dynamic-windows-re-using-wpp-and-tracelogging-e465f8b653f7" target="_blank">Windows RE using WPP and TraceLogging</a>. Following the post, we can use the following 4 lines in powershell to start an ETW session that will capture both the <code>NWActivity</code> and the <code>NWActivityVerbose</code> providers.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-powershell" data-lang="powershell"><span style="color:#8be9fd;font-style:italic">New-EtwTraceSession</span> -Name NWTrace -LogFileMode 0x08000100 -FlushTimer 1
<span style="color:#6272a4"># Add Microsoft.Windows.Security.CodeIntegrity.NWActivityVerbose</span>
<span style="color:#8be9fd;font-style:italic">Add-EtwTraceProvider</span> -SessionName NWTrace -Guid ‘{3a82f218-fcc2-4183-afe9-a0febc4416ee}’ -MatchAnyKeyword 0xFFFFFFFFFFFF -Level 0xFF -Property 0x40
<span style="color:#6272a4"># Add Microsoft.Windows.Security.CodeIntegrity.NWActivity</span>
<span style="color:#8be9fd;font-style:italic">Add-EtwTraceProvider</span> -SessionName NWTrace -Guid ‘{28dcc28b-3e31-527b-efd6-b4cc4d73d158}’ -MatchAnyKeyword 0xFFFFFFFFFFFF -Level 0xFF -Property 0x40 
tracerpt -rt NWTrace -o NWTrace.evtx -of EVTX</code></pre></div>
<p>After starting the traces and playing around with some apps/installers you should have an EventLog that can be opened with EventViewer and you can find out things like that the Defender finally trusts ProcessHacker 😝!!</p>

<p><img src="/images/smartAppControl/part2/NWAllow.png" alt="alt img" title="NWAllow event" /></p>

<p>This is going to be all for today, although I&rsquo;ll re-visit the CI for sure to write more about the Cache or HVCI. There&rsquo;s still some things that I didn&rsquo;t discuss but I&rsquo;ll leave that as an exercise for the reader &ndash; If curious check things like <code>CiGetCodeIntegrityOriginClaimForFileObject</code> &amp; <code>CiDeleteCodeIntegrityOriginClaimMembers</code>🙂.</p>

<h1 id="conclusion">Conclusion</h1>

<p>If you made it all the way here, thank you 😅!! Sorry for the <strong>extremely</strong> long post, but I really wanted to dig deep into this feature and try to dissect as much as possible. I&rsquo;m pretty sure I still missed many things, and also I might be wrong in some, but hopefully this series of post will help you get a better understanding of SAC internals (And everything around it like CI, policies, AppLocker, etc&hellip;).</p>

<p>As I mentioned in the beginning, I didn&rsquo;t look into how the system will learn during the evaluation part and this might be a crucial part of the feature. Hopefully somebody (or me) will write about this so we can learn even more about SAC. I&rsquo;m saying that the learning process is critical, because from my experience with the Enforce mode ON the feature is quite restrictive. But again the learning process might modify some parts of how the feature works.</p>

<p>Personally I think the steps MS is taking to improve security in the OS, with the end goal of making users more safe, are great. On the other hand, I do see some resembles between SAC and Windows 10 S, and even thou Windows 10 S had potential, the idea of limiting the users to only use Apps from the Windows Store was very restrictive (Let&rsquo;s not even discuss how much MS has pushed for the Windows Store without a very good reception from Users/Devs which made it even more difficult for this feature). In the case of SAC, when set to enforce, the limits are set by either the app having a digital signature or, if no signature, then to what the Defender cloud considers trusted. The first option, even thou I understand that digital signatures verifies the app pretty well, many open-source projects or freelance developers are not able to afford this and this unfortunately impose some restrictions into devs. That&rsquo;s when we reach the second option, the query to the &ldquo;Intelligent Cloud Security Service&rdquo; and this is where I wish Microsoft was giving more information, since basically the decision of an app being able to run or not will be solemly on hands of MS. To be fair I don&rsquo;t know the internals of the &ldquo;Cloud Security Service&rdquo; nor how is trained or if the data might be coming from multiple external sources. But I feel like many AV vendors will definitely want to be a part of this or at least have a chance to control some decisions, what if an AV different to the Defender is running in the machine and has a list of exclusions that is actually blocked by SAC, this will definitely confuse the customer. Nonetheless, many people might consider this as MS trying to lock-out competing AV vendors by giving more power to the Defender even when another AV is running as the main Antimalware product in the PC (For instance, previously MS was using the naming side-by-side when running Defender and another AV, now the naming seems to be Hybrid-mode). Anyways that&rsquo;s just how I think some AV vendors might take this feature (To some this might resseamble <a href="https://en.wikipedia.org/wiki/Next-Generation_Secure_Computing_Base" target="_blank">NGSCB</a>), personally, as I mentioned before I truly believe the steps MS is making to protect the end user (VBS, FASR, SAC, etc..) are great 🙂.</p>

<p>Unfotunately, I think at first SAC won&rsquo;t be enabled in many machines. This could lead to SAC just being a passive passenger in the OS, and the fact that it can&rsquo;t be re-enabled without resseting the PC will surely help it staying disabled. If Microsoft is really pushing for this feature this might present the dilemma of them thinking to either enforce SAC, or maybe give the option to add exclusions (Which I don&rsquo;t think will happen since it defeats the purpose of the feature). In any case, this is purely speculation, when the feature is actually released we will see the real impact/reception. I do belive that for the Windows average user this might be a killer feature, though I&rsquo;d like to see how many people disable the feature because they want to execute somethig without fully understanding that they cannot re-enable it. There&rsquo;s also the enterprise point of view, where I wonder what type of control will IT admins have over SAC, if it will be possible to apply it for certain Users/Groups but disable it for others. However I&rsquo;m pretty sure Microsoft has already thought about many of this things so I&rsquo;m really looking forward to the future of SAC.</p>

<p>As always, if there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a>. I&rsquo;m back 🥳!!</p>
]]></content></item><item><title>Smart App Control Internals (Part 1)</title><link>https://n4r1b.com/posts/2022/08/smart-app-control-internals-part-1/</link><pubDate>Mon, 29 Aug 2022 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2022/08/smart-app-control-internals-part-1/</guid><description>After more than two years I&amp;rsquo;m back!! Unfortunately, last two years work &amp;amp; life happened and I didn&amp;rsquo;t have the time to continue writing. But things are a bit easier right now, so I&amp;rsquo;m making a comeback 😄. And what a better topic for a comeback than, one of the biggest upcoming security features for Windows: Smart App Control &amp;ndash; From now on I will use Smart App Control and SAC interchangeably.</description><content type="html"><![CDATA[

<p>After more than two years I&rsquo;m back!! Unfortunately, last two years work &amp; life happened and I didn&rsquo;t have the time to continue writing. But things are a bit easier right now, so I&rsquo;m making a comeback 😄. And what a better topic for a comeback than, one of the biggest upcoming security features for Windows: <a href="https://support.microsoft.com/en-us/topic/what-is-smart-app-control-285ea03d-fa88-4d56-882e-6698afdb7003" target="_blank"><strong>Smart App Control</strong></a> &ndash; From now on I will use Smart App Control and SAC interchangeably.</p>

<p>As always in my blog, I will try to go deep into the internals of how this feature works. This time I will summarize everything two or three posts.</p>

<p>With regard to the structure, I&rsquo;ll divide the research in two parts. In the first part we&rsquo;ll see a quick introduction of the feature and the internals of how SAC is initialized. In the second part we&rsquo;ll see how SAC enforce the actions and the conclusions. Also, I&rsquo;ll add an appendix to share gists with main structures I&rsquo;ve used during the research and both SAC policies in XML format.</p>

<blockquote>
<p><strong>Disclaimer:</strong> By any means I&rsquo;m an expert on Windows Policies and CI, so I might mention things that are already well-know for people that play with Policies on a daily basis. For me it was all very new. On the bright side I learnt quite a bit with this research.</p>

<p>Also, before starting, <strong>huge</strong> thanks to <a href="https://twitter.com/mattifestation" target="_blank">Matt Graeber</a> for all the information he has written about CI/Policies. It has been very helpful. And of course, to the people at MS that documented how to work/interact with Policies, there&rsquo;s a vast amount of information!!</p>
</blockquote>

<h1 id="introduction">Introduction</h1>

<p>So what is this &ldquo;Smart App Control&rdquo; feature and why do I consider it as one of the biggest security features coming to Windows. Basically, SAC is a feature inherent to the OS &ndash; Keep this in mind, this is a feature from the OS &ndash; that when enabled will block malicious or untrusted apps. This is very similar, arguably we could say is the same, to <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/applocker/applocker-overview" target="_blank">AppLocker</a>, but imagine MS being the one that wrote the rules/policy.</p>

<blockquote>
<p>Smart App Control is expected to be released with <strong>Windows 22H2</strong>, which should be released in late September this year. This is already available in the Release Preview Channel. For this post I&rsquo;ve done all the research on Build 22621 from the Beta channel.</p>
</blockquote>

<p>SAC has three possible states and only one of them will enforce the actions:</p>

<ul>
<li><strong>Enforce</strong>: Blocking of malicious or untrusted apps will be enforced &ndash; State = 1.</li>
<li><strong>Evaluation</strong>: In this mode the feature will keep evaluating if your system is a good candidate for the feature to be in enforce mode &ndash; State = 2.</li>
<li><strong>Off</strong>: The feature is disabled. Once disabled it can&rsquo;t be activated again unless you do a fresh install of the OS &ndash; State = 0.</li>
</ul>

<blockquote>
<p><strong>Disclaimer:</strong> In this post I won&rsquo;t be discussing how does the feature determine if the endpoint is suitable for the enforce mode. That&rsquo;s something I still need to research and I left it apart for now.</p>
</blockquote>

<p>Microsoft considers a good candidate someone to whom the feature &ldquo;won&rsquo;t get in it&rsquo;s way too often&rdquo;. Unfortunately MS is not giving us any more information with regard to the evaluation mode. The evaluation mode can switch the feature to both Enforce or Off state. But the user can always decide to disable the feature (Opt-In model) &ndash; As mentioned above, this implies not being able to enable it again unless re-installing the OS.</p>

<p>If we refer to the Microsoft documentation on SAC. We can find that at the moment exclusions are not going to be allowed. There&rsquo;s no way to let an application bypass SAC once the feature is in enforce mode. This means untrusted nor malicious apps won&rsquo;t have a way to execute. On the other hand, this might also block certain legitimate apps that are not signed or the MS cloud security doesn&rsquo;t have a reputation for them.</p>

<blockquote>
<p>Please refer to the document <a href="https://support.microsoft.com/en-us/topic/what-is-smart-app-control-285ea03d-fa88-4d56-882e-6698afdb7003" target="_blank">What is Smart App Control?</a> to learn more about the basics of the feature.</p>
</blockquote>

<h2 id="sac-install">SAC Install</h2>

<p>Getting into how this gets installed. This feature requires a fresh install in order to be activated. If we mount the ISO for Build 22621 and navigate through the <code>install.wim</code> to the folder containing the registry hives, then we can load the SYSTEM Hive into the Registry Editor. Within the <code>CI\Policy</code> key we can find the Value <code>VerifiedAndReputablePolicyState</code> set to 2 (Evaluation state).</p>

<p><img src="/images/smartAppControl/part1/InstallWim_VerifiedAndReputablePolicyState.png" alt="alt img" title="VerifiedAndReputablePolicyState" /></p>

<p>Also within the <code>CI</code> key we have the SubKey <code>Protected</code> where we can find the following value <code>VerifiedAndReputablePolicyStateMinValueSeen</code> also set to 2.</p>

<p><img src="/images/smartAppControl/part1/InstallWim_VerifiedAndReputablePolicyStateMinValueSeen.png" alt="alt img" title="VerifiedAndReputablePolicyStateMinValueSeen" /></p>

<blockquote>
<p>Later we will see more on how these keys are used to control the actual state of SAC, and we will also see how the values under the <code>Protected</code> SubKey are guarded to avoid tampering.</p>
</blockquote>

<p>Before ending this section let&rsquo;s see what happens in case of an OS upgrade. In order to enforce this when upgrading, we can see the install ISO has the following code in the replace manifest for the CI &ndash; <code>[ISO]\sources\replacementmanifests\codeintegrity-repl.man</code>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-xml" data-lang="xml"><span style="color:#ff79c6">&lt;addObjects&gt;</span>
  <span style="color:#ff79c6">&lt;conditions&gt;</span>
    <span style="color:#ff79c6">&lt;condition</span> <span style="color:#50fa7b">negation=</span><span style="color:#f1fa8c">&#34;Yes&#34;</span><span style="color:#ff79c6">&gt;</span>MigXmlHelper.DoesObjectExist(&#34;Registry&#34;, &#34;HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy [VerifiedAndReputablePolicyState]&#34;)<span style="color:#ff79c6">&lt;/condition&gt;</span>
  <span style="color:#ff79c6">&lt;/conditions&gt;</span>
  <span style="color:#ff79c6">&lt;object&gt;</span>
    <span style="color:#ff79c6">&lt;location</span> <span style="color:#50fa7b">type=</span><span style="color:#f1fa8c">&#34;Registry&#34;</span><span style="color:#ff79c6">&gt;</span>HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy [VerifiedAndReputablePolicyState]<span style="color:#ff79c6">&lt;/location&gt;</span>
    <span style="color:#ff79c6">&lt;attributes&gt;</span>dword<span style="color:#ff79c6">&lt;/attributes&gt;</span>
    <span style="color:#ff79c6">&lt;bytes&gt;</span>00000000<span style="color:#ff79c6">&lt;/bytes&gt;</span>
  <span style="color:#ff79c6">&lt;/object&gt;</span>
<span style="color:#ff79c6">&lt;/addObjects&gt;</span></code></pre></div>
<p>When upgrading the OS this piece of code will check if the Registry value <code>HKLM\SYSTEM\CurrentControlSet\Control\CI\Policy\VerifiedAndReputablePolicyState</code> exist, if it doesn&rsquo;t it will be created with the SAC state 0 (Off state).</p>

<p>Aside from these two new registry values, the OS will ship with two new System Integrity policy files (<code>.cip</code>) within the <code>System32\CodeIntegrity\CiPolicies</code> folder.</p>

<ul>
<li><strong>PolicyGUID: <code>{0283AC0F-FFF1-49AE-ADA1-8A933130CAD6}</code></strong> Enforce SAC policy, active when SAC state is set to enforce (1)</li>
<li><strong>PolicyGUID: <code>{1283AC0F-FFF1-49AE-ADA1-8A933130CAD6}</code></strong> Eval SAC policy, active when SAC state is set to evaluation (2)</li>
</ul>

<p>Using the <a href="https://github.com/mattifestation/WDACTools/blob/master/CIPolicyParser.psm1" target="_blank">CIPolicyParser</a> script from the WDACTools, we convert both <code>.cip</code> files into their <code>.xml</code> representation. From the XML we can take the <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/select-types-of-rules-to-create#table-1-windows-defender-application-control-policy---policy-rule-options" target="_blank">Policy Rules</a> to get an idea of the options of these Policies. The following Rules are set &ndash; Both XMLs files can be found in the Appendix.</p>

<ul>
<li>Enabled:UMCI</li>
<li>Enabled:Intelligent Security Graph Authorization</li>
<li>Enabled:Developer Mode Dynamic Code Trust</li>
<li>Enabled:Allow Supplemental Policies</li>
<li>Enabled:Revoked Expired As Unsigned</li>
<li>Enabled:Inherit Default Policy</li>
<li>Enabled:Unsigned System Integrity Policy</li>
<li>Enabled:Advanced Boot Options Menu</li>
<li>Disabled:Script Enforcement</li>
<li>Enabled:Update Policy No Reboot</li>
<li>Enabled:Conditional Windows Lockdown Policy</li>
<li>Enabled:Audit Mode (Only in the SAC Evaluation Policy)</li>
</ul>

<p>Lastly, we can search inside the <code>System32</code> folder to find binaries/modules that make use of the previously mentioned registry values.</p>

<p><img src="/images/smartAppControl/part1/RegKeyVerifiedAndReputable.png" alt="alt img" title="Search VerifiedAndReputablePolicyState key" /></p>

<h1 id="sac-initialization">SAC Initialization</h1>

<p>We will split this section into two stages. The first stage we will talk about SAC during the Windows loader. The second stage we will talk about SAC during the OS initialization. It&rsquo;s important to understand that both the loader and the OS play a role in enabling SAC. Finally, I&rsquo;ll add a section to explain how the protection of the values under the SubKey <code>CI\Protected</code> works.<br />
The following simple diagram shows at high level the SAC initialization flow for the aforementioned stages.</p>

<p><img src="/images/smartAppControl/part1/SACGlobalInit.jpg" alt="SAC Global Init Diagram" width="500"/></p>

<h2 id="sac-during-winload">SAC during Winload</h2>

<p>In this section we will discuss how the SAC policy for the active SAC state gets chosen, how the persistence and coherency between RegKeys is enforce by Winload and how the SAC policy is passed to the kernel.<br />
The diagram below presents a high level representation of what we will see during this section.</p>

<p><img src="/images/smartAppControl/part1/SACWinload.jpg" alt="alt img" title="SAC during Winload" /></p>

<p>First step for SAC initialization comes early during the OS loader process. More specifically right after the load of the SystemHive during the preparation of the target (<code>OslPrepareTarget</code>). The function <strong><code>OslpProcessSIPolicy</code></strong> will be called in order to process the System Integrity policies. Within this function the conditional policies &ndash; SKU, EMode, SAC Enforce, SAC Evaluation &ndash; will be evaluated to see if they should be ignored or unlocked. Microsoft considers these four policies conditional because they can be Ignore/Unlocked, unlike other policies like the &ldquo;MS Windows Driver Policy&rdquo; which always apply. The policiesGUIDs for the conditional policies are stored in a global array defined by the symbol <code>g_SiConditionalPolicies</code>.</p>

<blockquote>
<p>The difference between Ignore and Unlock is very subtle. The Unlock flag will be always checked. On the other hand, the Ignore flag will only be checked for Policies where &ldquo;Enabled:Unsigned System Integrity Policy&rdquo; is not set. At the moment Ignore and Unlock match 1 to 1.</p>
</blockquote>

<p>To determine whether SAC should be enabled for either Enforce or Evaluation, the following two functions are used.</p>

<ul>
<li><strong><code>OslpShouldIgnoreUnlockableNightsWatchDesktopEnforcePolicy</code></strong></li>
<li><strong><code>OslpShouldIgnoreUnlockableNightsWatchDesktopEvalPolicy</code></strong></li>
</ul>

<blockquote>
<p>This is the first time that we will see the reference <strong>Nights Watch</strong> to denote SAC, this seem to be the internal microsoft name.</p>
</blockquote>

<p>These two functions behave in the same way, the only difference being that they provide a different PolicyGUID to the internal evaluation function:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#8be9fd">bool</span>  <span style="color:#6272a4">// Return value indicates if unlockable or not
</span><span style="color:#6272a4"></span>OslpShouldIgnoreUnlockableNightsWatchDesktopPolicy(
  PGUID PolicyGUID, <span style="color:#6272a4">// The PolicyGUID matches the name of the `.cip` files we mentioned above
</span><span style="color:#6272a4"></span>  HANDLE SystemHive,
  PBOOL Active, <span style="color:#6272a4">// If true policy is active 
</span><span style="color:#6272a4"></span>  PBOOL Ignore  <span style="color:#6272a4">// If true policy should be ignored
</span><span style="color:#6272a4"></span>  );</code></pre></div>
<p>This function uses the PolicyGUID parameter to determine which SAC state to check. It calls <code>OslpGetNightsWatchDesktopRegKeyState</code>, which returns the actual SAC state in the machine. If the actual SAC state matches the one being evaluated, then this Policy is considered active &ndash; This is an over simplification. There&rsquo;s a few more checks as if the device is WinPE or if a signed policy is required. These checks can make the function return Ignore and Unlockable even if the registry indicates SAC is active.</p>

<p>The behavior of <code>OslpGetNightsWatchDesktopRegKeyState</code> is worth taking a look. This routine is liable of keeping SAC enabled across reboots and keeping the coherency between both registry values. This routine has four possible scenarios:</p>

<ul>
<li><p><em>VerifiedAndReputablePolicyState</em> <strong>==</strong> <em>VerifiedAndReputablePolicyStateMinValueSeen</em>: Values are the same, so return the value directly.</p></li>

<li><p><em>VerifiedAndReputablePolicyState</em> <strong>&lt;</strong> <em>VerifiedAndReputablePolicyStateMinValueSeen</em>: During the previous boot-session the SAC state was modified. We return the value from <code>VerifiedAndReputablePolicyState</code> and update the value under the <code>Protected</code> SubKey.</p></li>

<li><p><em>VerifiedAndReputablePolicyState</em> <strong>&gt;</strong> <em>VerifiedAndReputablePolicyStateMinValueSeen</em>: This is a corner case, since <code>VerifiedAndReputablePolicyState</code> should never be bigger than the value under the <code>Protected</code> key. I believe this is here to keep the coherency between both values if someone manually edits the value <code>VerifiedAndReputablePolicyState</code>.</p></li>

<li><p>Either value is 3 or more: This indicates an Invalid state transition and the function will fail.</p></li>
</ul>

<p>The following pseudo-code summarize it.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">...
Status <span style="color:#ff79c6">=</span> OslGetDWordValue(SystemHive, PolicySubkey, <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;VerifiedAndReputablePolicyState&#34;</span>, <span style="color:#ff79c6">&amp;</span>NWState);
Status <span style="color:#ff79c6">=</span> OslGetDWordValue(SystemHive, ProtectedSubkey, <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;VerifiedAndReputablePolicyStateMinValueSeen&#34;</span>, <span style="color:#ff79c6">&amp;</span>NWMinValSeen);

<span style="color:#ff79c6">if</span> ( NT_SUCCESS( Status ) ) {
  <span style="color:#ff79c6">if</span> ( NWState <span style="color:#ff79c6">&lt;=</span> NWMinValSeen ) {
    <span style="color:#ff79c6">*</span>SACState <span style="color:#ff79c6">=</span> NWState;
    <span style="color:#ff79c6">if</span> ( NWState <span style="color:#ff79c6">&lt;</span> <span style="color:#bd93f9">3</span> ) {

      <span style="color:#ff79c6">if</span> ( NWState <span style="color:#ff79c6">&gt;=</span> NWMinValSeen )
        <span style="color:#ff79c6">return</span> STATUS_SUCCESS;

      <span style="color:#ff79c6">return</span> <span style="color:#50fa7b">OslHiveReadWriteDword</span>( SystemHive, <span style="color:#bd93f9">1</span>, ProtectedSubkey, <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;VerifiedAndReputablePolicyStateMinValueSeen&#34;</span>, SACState );
    }
  } 
  <span style="color:#ff79c6">else</span> {
    <span style="color:#ff79c6">*</span>SACState <span style="color:#ff79c6">=</span> NWMinValSeen;
    <span style="color:#ff79c6">if</span> ( NWMinValSeen <span style="color:#ff79c6">&lt;=</span> <span style="color:#bd93f9">2</span> ) 
      <span style="color:#ff79c6">return</span> OslHiveReadWriteDword( SystemHive, <span style="color:#bd93f9">1</span>, PolicySubkey, <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;VerifiedAndReputablePolicyState&#34;</span>, SACState );
  }
  <span style="color:#ff79c6">return</span> STATUS_INVALID_STATE_TRANSITION;
}</code></pre></div>
<p>When there&rsquo;s a SAC state change by using the Security App. The OS will write to the <code>VerifiedAndReputablePolicyState</code>. After the user reboots this state will be persistent in the machine. This means that after a SAC state transition one can still edit the <code>VerifiedAndReputablePolicyState</code> and the transition won&rsquo;t be persistent across the next reboot. This makes me think MS will trigger transitions from <em>Evaluation</em> mode only when installing updates or they will ask for a reboot. Obviously, during the session when there&rsquo;s a SAC state transition the active policies will be updated.</p>

<p>Once all the conditional policies have been checked to see if they are unlockable or should be ignored. The values obtained from each function will be written into the following two globals:</p>

<ul>
<li>g_SIPolicyConditionalPolicyConditionUnlockHasBeenMet</li>
<li>g_SIPolicyConditionalPolicyConditionIgnoreHasBeenMet</li>
</ul>

<p>The value written into these globals is a four byte array that can be represented with the following struct</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_POLICY_MODES {
  BOOLEAN SkuPolicy;    <span style="color:#6272a4">// Policy used when Windows is running in S mode 
</span><span style="color:#6272a4"></span>  BOOLEAN EModePolicy;  <span style="color:#6272a4">// I can&#39;t find any information about EMode, please reach out if you know more
</span><span style="color:#6272a4"></span>  BOOLEAN NightsWatchDesktopEnforce;
  BOOLEAN NightsWatchDesktopEval;
} SI_POLICY_MODES, <span style="color:#ff79c6">*</span>PSI_POLICY_MODES;</code></pre></div>
<p>After this, the loader will try to parse the policy files. First by loading the serialized data from every <code>.cip</code> file into memory (See <code>BlSIPolicyGetAllPolicyFiles</code>). Then parsing the data from each file inside <code>SIPolicyParsePolicyData</code> &ndash; If anyone is interested in the details check <code>SIPolicyInitialize</code> to see how every section of the Policy is parsed into a structure. In Part 2 we will talk more about this structure and it&rsquo;s data.</p>

<p>Once the policy is parsed both the ignore and Unlock conditions will be checked to see if they are met. In case a condition is met, the policy will be discarded. In case none of the conditions is met, then the policy will be set as active using the function <code>SIPolicySetAndUpdateActivePolicy</code>.</p>

<p>In case the Policy Option &ldquo;Enabled:Unsigned System Integrity Policy&rdquo; is set then the PolicyVersion and the PolicySignersData will be deleted from the EFI SecureBoot private namespace. The deleted variable name will be composed by concatenating the PolicyGUID plus the PolicyVersion/PolicySignersData string &ndash; These EFI variables are created only when the PolicyOptions have &ldquo;Enabled:Unsigned System Integrity Policy&rdquo; disabled.</p>

<p>In the following output we can see how SetVariable is being called with size 0 which would cause the variable to be deleted if found.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-YAML" data-lang="YAML">[SetVariable][VendorGUID: 77FA9ABD-<span style="color:#bd93f9">0359</span>-4D32-BD60-28F4E78F784B] Variable: <span style="color:#f1fa8c">&#34;{0283ac0f-fff1-49ae-ada1-8a933130cad6}PolicyVersion&#34;</span> Size: <span style="color:#f1fa8c">&#34;0x00000000&#34;</span> Attributes: <span style="color:#f1fa8c">&#34;0x00000000&#34;</span>  Status: EFI_NOT_FOUND
[SetVariable][VendorGUID: 77FA9ABD-<span style="color:#bd93f9">0359</span>-4D32-BD60-28F4E78F784B] Variable: <span style="color:#f1fa8c">&#34;{0283ac0f-fff1-49ae-ada1-8a933130cad6}PolicyUpdateSigners&#34;</span> Size: <span style="color:#f1fa8c">&#34;0x00000000&#34;</span> Attributes: <span style="color:#f1fa8c">&#34;0x00000000&#34;</span>  Status: EFI_NOT_FOUND</code></pre></div>
<p>For both SAC policies any EFI variable will be cleared. Afterwards, the policy will be set as active by calling <code>SIPolicySetActivePolicy</code>. This call will add the policy into a Node that will be linked into the global variable <code>g_SiPolicyCtx</code>. The <code>g_NumberOfSiPolicies</code> will be incremented accordingly and a handle to the new policy will be stored in the <code>g_SiPolicyHandles</code> &ndash; This variable is an array of 32 handles, since WDAC supports up to 32 active policies on a device at once.</p>

<p>The prototype for the <code>SI_POLICY_CTX</code> structure which is kept in the <code>g_SiPolicyCtx</code> is the following:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_POLICY_CTX {
  PSI_POLICY Policy;
  PSI_POLICY BasePolicy;
  GUID PolicyGUID;
  GUID BasePolicyGUID;
  <span style="color:#8be9fd">bool</span> IsBasePolicy;
  <span style="color:#8be9fd">bool</span> AuditModeEnabled;
  PSI_POLICY_CTX RootNode;
  PSI_POLICY_CTX NextNode;
  PSI_POLICY_CTX SupplementalPolicy;
} SI_POLICY_CTX, <span style="color:#ff79c6">*</span>PSI_POLICY_CTX;</code></pre></div>
<p>And the following image shows the three global variables. In my case there are three active policies one of them being a <a href="https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/wdac-wizard-create-supplemental-policy" target="_blank">supplemental policy</a> for the SAC enforce policy &ndash; Supplemental policies help expand the Base policy to increase the circle of trust of the policy.</p>

<p><img src="/images/smartAppControl/part1/PolicieHandlesCtx.png" alt="alt img" title="g_SiPolicyCtx &amp; g_SiPolicyHandles" /></p>

<p>With this information, the loader will be able to build the CI structure inside the <a href="https://www.vergiliusproject.com/kernels/x64/Windows%2011/21H2%20(RTM)/_LOADER_PARAMETER_BLOCK" target="_blank">loader parameter block</a>. This is done inside the function <code>OslBuildCodeIntegrityLoaderBlock</code>. This routine, among many other things, will obtain the size of the serialized SI policies with the help of the function <code>SIPolicyGetSerializedPoliciesSize</code>. The code will use the global variables <code>g_NumberOfSiPolicies</code> and the <code>g_SiPolicyHandles</code> and the size will be stored in the field <em>CodeIntegrityPolicySize</em> of the <code>LOADER_PARAMETER_CI_EXTENSION</code>. Afterwards, the serialized data will be copied by means of the function <code>SIPolicyGetSerializedPolicies</code>. The offset to this data will be stored in the field <em>CodeIntegrityPolicyOffset</em>. This information, along other CI info, will be stored in the fields <em>CodeIntegrityDataSize</em> and <em>CodeIntegrityData</em> of the <code>LOADER_PARAMETER_EXTENSION</code> &ndash; The Loader Parameter Block is passed as an argument when the <a href="http://localhost:1313/posts/2019/09/transition-from-an-efi-bootloader-to-the-kernel-in-windows-x64/" target="_blank">loader transitions into the OS</a>.</p>

<blockquote>
<p>Yep, only the serialized payload will be copied. I guess all the parsing of the policy done previously is mainly to check the policy is valid and trigger <code>SYSTEM_INTEGRITY_POLICY</code> error if not valid. Potentially also to use values from the policies for Attestation or EFI variables.</p>
</blockquote>

<p>And that&rsquo;s pretty much all we are gonna see for the SAC initialization during the winload &ndash; In a future post we might re-visit the winload to talk about SiPolicies and MeasuredBoot, PCRs, etc&hellip;<br />
The following capture shows how this data will be set up before the transition to the OS.</p>

<p><img src="/images/smartAppControl/part1/CiExtension.png" alt="alt img" title="LOADER_PARAMETER_CI_EXTENSION" /></p>

<h2 id="sac-during-os-init">SAC during OS Init</h2>

<p>In this section we will take a quick glance on how the kernel initialize the CI. After this, we will get into how the CI initialize the Policies provided by Winload. And lastly, how from these policies it determines if SAC is enabled to act accordingly.</p>

<p><img src="/images/smartAppControl/part1/SACOSInit.jpg" alt="alt img" title="SAC During OS Init" /></p>

<p>During the OS initialization, more specifically during the Phase 1. The kernel will call the method <code>CiInitialize</code> (Exported by the <code>ci.dll</code>). This function will mainly be used by the kernel and CI to exchange APIs. The kernel receives the <code>SeCiCallbacks</code>, which contains the functions pointers the kernel will use to interact with the CI. On the other hand the CI DLL receives the <code>SeCiPrivateApis</code>, which contains, among other kernel functions, the VSL HVCI interface so the CI can trigger Hypercalls by means of the kernel when doing any HVCI validation. The kernel will also pass the the initial CodeIntegrity options. These options were built by the Windows Loader and stored in the <code>LOADER_PARAMETER_CI_EXTENSION</code>. These options initially will contain things like the CodeIntegrity BCD options (DisableIntegrityChecks, AllowPrereleaseSignatures, AllowFlightSignatures) and the WHQL Settings. The CI Options are stored in the global variable <code>g_CiOptions</code>, and CI will also update them based on information retrieved from the OS and the policies.</p>

<blockquote>
<p><strong>Disclaimer:</strong> The CI is a whole beast on it&rsquo;s own and the purpose of this post is to understand how SAC works not how the whole CI works. I&rsquo;ll be focusing mainly on SAC and what is necessary for it to work. We will still learn a lot about the CI but I will leave many things aside. At some point I might do a full post on the CI 😀.</p>
</blockquote>

<p>Still during the Phase 1 of the OS, the kernel will call <code>CiInitializePolicy</code> throughout the CI callbacks. This routine will receive as the first parameter the <code>LOADER_PARAMETER_CI_EXTENSION</code>. The routine will call into it&rsquo;s private counterpart <code>CipInitializeSiPolicy</code>. The function will call <code>SIPolicyInitializeFromSerializedPolicies</code> to validate, parse and load into memory the serialized policy from the loader parameter CI extension. Same as with winload, if the policy parsing works correctly the policy will be added to the <code>g_SiPolicyHandles</code> &amp; <code>g_SiPolicyCtx</code>. More important, if the serialized policies are parsed correctly then function <code>CipUpdateCiSettingsFromPolicies</code> will be called. This method updates the global CI settings based on the PolicyRules from each policy. Within this function the CI will check if SAC is enabled by calling <code>SIPolicyNightsWatchEnabled</code>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-caddyfile" data-lang="caddyfile">1: kd&gt; k
 # Child-SP          RetAddr               Call Site
00 ffff998b`4b406748 fffff800`356858b4     CI!SIPolicyNightsWatchEnabled
01 ffff998b`4b406750 fffff800`35683ba0     CI!CipUpdateCiSettingsFromPolicies+0x224
02 ffff998b`4b406800 fffff800`35622f94     CI!CipInitializeSiPolicy+0x24
03 ffff998b`4b406830 fffff800`356626fc     CI!CiInitializePolicyFromPolicies+0x278
04 ffff998b`4b4068a0 fffff800`32b5766c     CI!CiInitializePolicy+0x28c
05 ffff998b`4b4069d0 fffff800`32b2a59b     nt!SeCodeIntegrityInitializePolicy+0x70
06 ffff998b`4b406a00 fffff800`32825d43     nt!Phase1InitializationDiscard+0xb0f
07 ffff998b`4b406bb0 fffff800`322c3977     nt!Phase1Initialization+0x23
08 ffff998b`4b406bf0 fffff800`32423bb4     nt!PspSystemThreadStartup+0x57
09 ffff998b`4b406c40 00000000`00000000     nt!KiStartSystemThread+0x34</code></pre></div>
<p>This function is interesting and we can finally start to take a look into the SI policy structure. What the function will do is call <code>SIPolicyQueryOneSecurityPolicy</code>. This routine has the following prototype:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS 
<span style="color:#50fa7b">SIPolicyQueryOneSecurityPolicy</span>(
  PSI_POLICY SiPolicy,
  PCUNICODE_STRING Provider,
  PCUNICODE_STRING Key,
  PCUNICODE_STRING ValueName,
  PDWORD Type,
  PVOID Data,
  PULONG RetLen
  );</code></pre></div>
<p>This method will be quite recurrent when dealing with SI policies. Since is used to check/obtain the <em>SecureSettings</em> set in a policy. The policy structure (I personally named this structure <code>SI_POLICY</code>) has the following two members: <em>SecureSettingsCount</em> &amp; <em>SecureSettingsData</em>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SECURE_SETTINGS_DATA {
  INT32 Type;
  UNICODE_STRING Provider;
  UNICODE_STRING Key;
  UNICODE_STRING ValueName;
  <span style="color:#ff79c6">union</span> {
    <span style="color:#8be9fd">bool</span> Boolean;               <span style="color:#6272a4">// Type 0
</span><span style="color:#6272a4"></span>    INT32 Int;                  <span style="color:#6272a4">// Type 1
</span><span style="color:#6272a4"></span>    POLICY_BINARY_DATA Binary;  <span style="color:#6272a4">// Type 2
</span><span style="color:#6272a4"></span>    UNICODE_STRING String;      <span style="color:#6272a4">// Type 3
</span><span style="color:#6272a4"></span>  } Data;
} SECURE_SETTINGS_DATA, <span style="color:#ff79c6">*</span>PSECURE_SETTINGS_DATA;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SI_POLICY {
  ...
  INT32 SecureSettingsCount;                  <span style="color:#6272a4">// offset 0x698
</span><span style="color:#6272a4"></span>
  _Field_size_(SecureSettingsCount <span style="color:#ff79c6">*</span> <span style="color:#ff79c6">sizeof</span>(SECURE_SETTINGS_DATA))
  PSECURE_SETTINGS_DATA SecureSettingsData[];   <span style="color:#6272a4">// offset 0x6A0
</span><span style="color:#6272a4"></span>  ...
} SI_POLICY, <span style="color:#ff79c6">*</span>PSI_POLICY;</code></pre></div>
<p>When the serialized policy is parsed, the necessary memory for all secure settings will be allocated and stored in the <em>SecureSettingsData</em> pointer. Whenever the CI has to query a security setting, it will call <code>SIPolicyQueryOneSecurityPolicy</code> with the Provider, Key &amp; ValueName that it needs to look for. Internally the function will store those three values in a structure that will be used as the Key in the <a href="https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/bsearch?view=msvc-170" target="_blank">bsearch</a> function. The base for the search will be set to the <em>SecureSettingsData</em> of the policy. The CompareFunction is set to <code>SIPolicySecureSettingSearchCompare</code>. The CompareFunction will try to match the Provider, Key and ValueName from the <code>SECURE_SETTINGS_DATA</code> with the ones that are being queried. The comparison for each value is done using <code>RtlCompareUnicodeString</code>.</p>

<p>In our case, when looking to see if SAC is enabled &ndash; Inside <code>SIPolicyNightsWatchEnabled</code> &ndash; the values passed to the query function will be the following:</p>

<ul>
<li>Provider: <em>Microsoft</em></li>
<li>Key: <em>WindowsLockdownPolicySettings</em></li>
<li>ValueName: <em>VerifiedAndReputableTrustMode</em></li>
</ul>

<p>In case the secure setting is found in the policy, then SAC is considered to be enabled and the value <code>NW_ENABLED (0x4000)</code> will be set in the <code>g_CiPolicyState</code>.</p>

<blockquote>
<p>These values are also present in the XML format of the Policy. If you check the Enforce and Evaluation XML from the appendix, you&rsquo;ll see this Secure Setting is set to true in both.</p>
</blockquote>

<p>Just for completion, the PolicyState is a bitfield that can take the following values (Some are missing) &ndash; These are mostly taken from the ETW event metadata from function <code>CiInstrumentSiPolicyInfo</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">enum</span> _CI_POLICY_STATE {
  NEED_TO_APPLY_TO_CI <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x1</span>,
  NEED_TO_APPLY_TO_UMCI <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2</span>,
  AUDIT_MODE_ENABLED <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x4</span>,
  REQUIRES_WHQL <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x8</span>,
  REQUIRES_EV_WHQL <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x10</span>,
  INVALIDATE_EA_ON_REBOOT <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x20</span>,
  PER_PROCESS_VALIDATION <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x40</span>,
  FORCE_IMAGE_REVALIDATION <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x80</span>,
  FULL_IMAGE_PATH_AND_MACROS <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x400</span>,
  UMCI_AUDIT_ONLY <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x800</span>,
  UMCI_OPT_FOR_EXPIRED <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x1000</span>,
  AUTH_ROOT_AUTHORIZED <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2000</span>,
  NIGHTS_WATCH <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x4000</span>,
  SMART_LOCKER <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x8000</span>,
  REQUEST_AUTH_ATTRS <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x10000</span>,
  APPID_TAGGING <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x20000</span>,
} CI_POLICY_STATE, <span style="color:#ff79c6">*</span>PCI_POLICY_STATE;</code></pre></div>
<p>The following shot shows the state right before calling <code>SIPolicyQueryOneSecurityPolicy</code> within <code>SIPolicyNightsWatchEnabled</code> with the SAC enforce policy being used for the query &ndash; Sorry about the light theme, the <code>dx</code> grid doesn&rsquo;t look very well with the dark theme.</p>

<p><img src="/images/smartAppControl/part1/EnforceSecureSettings.png" alt="alt img" title="SAC Enforce Secure Settings" /></p>

<p>Going back into <code>CiInitializePolicy</code>, a global variable to indicate the minimum value seen for SAC in this boot-session will be update in the following fashion:</p>

<p><img src="/images/smartAppControl/part1/NightsWatchMinValSet.png" alt="alt img" title="SAC MinValSet" /></p>

<p>Basically, in case SAC is enabled, then the local variable <code>EnforceNW</code> will be set with the PolicyGUID of the SAC enforce policy. This GUID is then passed into the function <code>SIPolicyIsPolicyActive</code>. If this function returns true (1) then the code will subtract &ldquo;2-1&rdquo; setting the <code>g_NightsWatchDesktopMinValueSeenDuringThisBootSession</code> to <code>Enforce</code> state. In case the SAC Enforce policy is not active but SAC is enabled. The function returns false(0) then the value stored in the global will be &ldquo;2-0&rdquo; setting the <code>Evaluation</code> state. Lastly if SAC is not enabled then the value stored in the global is 0 (Off state).</p>

<p>In Part 2 we will see how CI handles SAC state transitions that are triggered when changing the State in the Windows Security App. Little Spoiler: This involves handling a signal sent by the Defender, and that&rsquo;s something we will discuss in that post 🙂.</p>

<h2 id="ci-protected-subkey">CI Protected SubKey</h2>

<p>In this last section we will see how values under the RegKey <code>CI\Protected</code> are secured by the OS. This is critical for the feature because being able to control <code>VerifiedAndReputablePolicyStateMinValueSeen</code> would allow us to change the SAC state across reboots.</p>

<p>During <code>CiInitializePolicy</code> the first function that will be called is <code>CipCheckLicensing</code>. This routine will be the first to open the SubKey <code>\\CurrentControlSet\\Control\\CI\\Protected</code> &ndash; This time is opened to check the <code>Licensed</code> value but that&rsquo;s not relevant.</p>

<p>Once the CI obtains a handle to the <code>Protected</code> SubKey, it will use one of the methods provided by the kernel during initialization in the <code>SeCiPrivateApis</code> table. Particularly the method <code>SepZwLockRegistryKey</code>. This method will reach <code>NtLockRegistryKey</code> (Throughout the <code>Zw</code> version). <code>NtLockRegistryKey</code> will use the Handle of the key to obtain a reference to the Object, key objects are represented with the <a href="https://www.vergiliusproject.com/kernels/x64/Windows%2011/21H2%20(RTM)/_CM_KEY_BODY" target="_blank"><code>CM_KEY_BODY</code></a> structure. The key object will be passed to <code>CmLockKeyForWrite</code>, which will obtain the <a href="https://www.vergiliusproject.com/kernels/x64/Windows%2011/21H2%20(RTM)/_CM_KEY_CONTROL_BLOCK" target="_blank"><code>CM_KEY_CONTROL_BLOCK</code></a> and call <code>CmpGlobalLockKeyForWrite</code>. See the following stack:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-caddyfile" data-lang="caddyfile">1: kd&gt; k
 # Child-SP          RetAddr               Call Site
00 fffff882`b2a06500 fffff805`3f7a6189     nt!CmpGlobalLockKeyForWrite+0xbe
01 fffff882`b2a06540 fffff805`3f7a6020     nt!CmLockKeyForWrite+0x11d
02 fffff882`b2a06590 fffff805`3f432465     nt!NtLockRegistryKey+0x70
03 fffff882`b2a065e0 fffff805`3f424380     nt!KiSystemServiceCopyEnd+0x25
04 fffff882`b2a06778 fffff805`3f86cab9     nt!KiServiceLinkage
05 fffff882`b2a06780 fffff805`43ff4e87     nt!SepZwLockRegistryKey+0x9
06 fffff882`b2a067b0 fffff805`43ff24bf     CI!CipCheckLicensing+0x1fb
07 fffff882`b2a068a0 fffff805`3fb5766c     CI!CiInitializePolicy+0x4f
08 fffff882`b2a069d0 fffff805`3fb2a59b     nt!SeCodeIntegrityInitializePolicy+0x70
09 fffff882`b2a06a00 fffff805`3f825d43     nt!Phase1InitializationDiscard+0xb0f
0a fffff882`b2a06bb0 fffff805`3f2c3977     nt!Phase1Initialization+0x23
0b fffff882`b2a06bf0 fffff805`3f423bb4     nt!PspSystemThreadStartup+0x57
0c fffff882`b2a06c40 00000000`00000000     nt!KiStartSystemThread+0x34</code></pre></div>
<p>Inside <code>CmpGlobalLockKeyForWrite</code> the ExtFlag <a href="https://github.com/mic101/windows/blob/master/WRK-v1.2/base/ntos/inc/cmdata.h#L663" target="_blank"><code>CM_KCB_READ_ONLY_KEY (0x80)</code></a> will be set in the KCB for this Key object. This is interesting because the protection is at the Object Manager level. Looking at <code>NtSetValueKey</code> we can see how the KCB ExtFlags are checked to see if the object is ReadOnly in order to deny or not the operation. This will apply no mather the user privileges nor the previous mode. See the following image to see this in action when trying to manipulate <code>VerifiedAndReputablePolicyStateMinValueSeen</code> &ndash; <em>Note:</em> The CM callback <code>RegNtSetValueKey</code> will be called, the <code>RegNtPostSetValueKey</code> won&rsquo;t.</p>

<p><img src="/images/smartAppControl/part1/RegKeyCiProtected.png" alt="alt img" title="Protected RegistryKey" /></p>

<p>Of course, <code>winload</code> is able to modify this value since the kernel is not running at this point. If we search within <code>System32</code> for binaries that reference the string <code>VerifiedAndReputablePolicyStateMinValueSeen</code> we will only find:</p>

<ul>
<li><em>winload.exe</em></li>
<li><em>windload.efi</em></li>
<li><em>tcbloader.dll</em></li>
</ul>

<p>Personally I think this is a simple solution to protect the key. This was already in place to protect the <code>Licensed</code> value so probably no code had to be added for it. But I wonder why MS didn&rsquo;t choose to store this value in some space like the TPM NV Storage. Not like this would solve everything. But I feel like the RegKey is easier to manipulate &ndash; For instance, using WinRE to open the registry editor, to then load the OS SYSTEM hive would be a plausible way to modify the value <code>VerifiedAndReputablePolicyStateMinValueSeen</code> . For sure, if someone is able to load WinRE and change this you have bigger problems 🤣.</p>

<blockquote>
<p>I might be missing something and winload might be storing the value somewhere else, but with the steps I just mentioned using WinRE I&rsquo;ve been able to successfully go from SAC disable to SAC enabled on my VM.</p>
</blockquote>

<p>And with this we&rsquo;ve reached the end of this post. This is pretty much everything we need to know on how SAC gets initialized. In the next post we can already start looking into how SAC works. I hope you guys enjoyed it and learned something from the post. As always, if there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a>. See you in the next post!!</p>

<h1 id="appendix">Appendix</h1>

<p>Just sharing this for completion. All credit here goes to Matt Graeber and the amazing <a href="https://github.com/mattifestation/WDACTools" target="_blank">WDACTools</a></p>

<ul>
<li><a href="https://gist.github.com/n4r1b/f1c44d573f055ee2194a16ae10a61611" target="_blank">SAC Evaluation Policy</a></li>
<li><a href="https://gist.github.com/n4r1b/a2c026def8fb77e01ab231c43430bc90" target="_blank">SAC Enforce policy</a></li>
</ul>
]]></content></item><item><title>Dissecting the Windows Defender Driver - WdFilter (Part 4)</title><link>https://n4r1b.com/posts/2020/04/dissecting-the-windows-defender-driver-wdfilter-part-4/</link><pubDate>Sun, 05 Apr 2020 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2020/04/dissecting-the-windows-defender-driver-wdfilter-part-4/</guid><description>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how WdFilter manages the different handle operations for Process and Desktops Objects, also we saw everything regarding the harvest of drivers information and the verification of them. For this post we will just focus on one topic:
Registry operations Let&amp;rsquo;s get into it!
MpRegInitialize This function is the one in charge of initializing the structure that will contain all the fields necessary to keep track of the registry operations.</description><content type="html"><![CDATA[

<p>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how <strong>WdFilter</strong> manages the different handle operations for Process and Desktops Objects, also we saw everything regarding the harvest of drivers information and the verification of them. For this post we will just focus on one topic:</p>

<ul>
<li>Registry operations</li>
</ul>

<p>Let&rsquo;s get into it!</p>

<h2 id="mpreginitialize">MpRegInitialize</h2>

<p>This function is the one in charge of initializing the structure that will contain all the fields necessary to keep track of the registry operations. It&rsquo;s is called from the <code>DriverEntry</code> and first thing it will do is retrieve the following function pointers:</p>

<ul>
<li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-cmcallbackgetkeyobjectidex" target="_blank">CmCallbackGetKeyObjectIDEx</a></li>
<li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-cmcallbackreleasekeyobjectidex" target="_blank">CmCallbackReleaseKeyObjectIDEx</a></li>
</ul>

<p>Once it has those two pointer it will allocate a pool of size <code>0x500</code> with tag <code>MPrD</code> where it will proceed to initialize the structure <code>MP_REG_DATA</code> &ndash; The pointer to the structure is saved in the global variable <strong>MpRegData</strong>.</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_REG_DATA
{
  USHORT Magic;     <span style="color:#6272a4">// Set to 0xDA09
</span><span style="color:#6272a4"></span>  USHORT Size;      <span style="color:#6272a4">// Sizeof 0x500
</span><span style="color:#6272a4"></span>  ULONG_PTR RegDataPushLock;
  PMP_REG_USER_DATA MonitoredKeys;
  ULONG MonitoredRegKeyRules;
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pCmCallbackGetKeyObjectIDEx)(PLARGE_INTEGER Cookie, PVOID Object, PULONG_PTR ObjectID, PCUNICODE_STRING <span style="color:#ff79c6">*</span>ObjectName, ULONG Flags);
  <span style="color:#8be9fd">void</span> (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pCmCallbackReleaseKeyObjectIDEx)(PCUNICODE_STRING ObjectName);
  LARGE_INTEGER CmCallbackGetKeyCookie;
  INT64 field_38;
  PAGED_LOOKASIDE_LIST NotificationsLookaside;
  FAST_MUTEX CmUnregisterFastMutex;
  LARGE_INTEGER CmRegisterCallbackCookie;
  INT OpenConnectionPortsCount;
  UNICODE_STRING LoadAppInitString;
  LIST_ENTRY ServiceKeyHardeningList;
  FAST_MUTEX CallCtxFastMutex;
  LIST_ENTRY CallCtxList;
  INT64 Unk;
  INT64 Unk1;
  PAGED_LOOKASIDE_LIST CreateKeyCtxLookaside;
  PAGED_LOOKASIDE_LIST SetValueKeyCtxLookaside;
  PAGED_LOOKASIDE_LIST DeleteValueKeyCtxLookaside;
  PAGED_LOOKASIDE_LIST DeleteKeyCtxLookaside;
  PAGED_LOOKASIDE_LIST RegDataEntry;
  PAGED_LOOKASIDE_LIST KeyNamesLookaside;
  PAGED_LOOKASIDE_LIST RenameKeyCtxLookaside;
} MP_REG_DATA, <span style="color:#ff79c6">*</span>PMP_REG_DATA;</code></pre></div>
</div>

<p>After initializing the events and the lookaside lists, in case we are running either <strong>MpFilter</strong> or a Windows version older than Win8.1 the function will proceed to register a registry callback that&rsquo;s meant for hardening keys, shortly we will see the behavior of this callback (<code>MpRegHardeningCallback</code>).</p>

<p>Finally, the list of hardened keys will be created inside <code>MpRegCreateHardeningList</code>, this function will obtain a handle to the <strong>CurrentControlSet</strong> key, then it will iterate an array of hard-coded services keys &ndash; Actually is an struct with the key name and a flag that determines if it&rsquo;s related to <strong>MpFilter</strong> or <strong>WdFilter</strong> &ndash; and for those that match the criteria their full key name will be chained into <code>MpRegData-&gt;ServiceKeyHardeningList</code>. On a machine with <strong>WdFilter</strong> the following keys would match:</p>

<p><img src="/images/wdFilter/part4/HardenedKeys.png" alt="alt image" title="Hardened Keys under WdFilter" /></p>

<h2 id="mpreghardeningcallback">MpRegHardeningCallback</h2>

<p>As seen in the previous section, the initialization routine register a registry callback meant for hardening keys. As every registry callback routine the prototype of this function is <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nc-wdm-ex_callback_function" target="_blank">EX_CALLBACK_FUNCTION</a>, and in this case no context is going to be passed into this routine.</p>

<p>This function will only focus on the case where <em>Argument1</em> is <strong>RegNtQueryValueKey</strong>, which implies that <em>Argument2</em> contains the structure <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_reg_query_value_key_information" target="_blank">REG_QUERY_VALUE_KEY_INFORMATION</a>. If <em>Argument1</em> is the expected then <code>MpRegPreQueryValueKey</code> will be called, this function is quite simple and it&rsquo;s pseudocode looks something like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">valueName <span style="color:#ff79c6">=</span> QueryValueKeyInfo<span style="color:#ff79c6">-&gt;</span>ValueName

<span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>valueName <span style="color:#ff79c6">||</span> <span style="color:#ff79c6">!</span>RtlEqualUnicodeString(valueName, <span style="color:#ff79c6">&amp;</span>MpRegData<span style="color:#ff79c6">-&gt;</span>LoadAppInitString, <span style="color:#bd93f9">1</span>))
  <span style="color:#ff79c6">return</span> STATUS_NO_MATCH;

<span style="color:#ff79c6">if</span> (MpGetProcessContextByObject(IoGetCurrentProcess(), <span style="color:#ff79c6">&amp;</span>processCtx)) {
  <span style="color:#ff79c6">if</span> (processCtx<span style="color:#ff79c6">-&gt;</span>processFlags <span style="color:#ff79c6">&amp;</span> (MsSecesProcess<span style="color:#ff79c6">|</span>MpServiceSidProcess)) {
    <span style="color:#ff79c6">return</span> STATUS_ACCESS_DENIED;
   } <span style="color:#ff79c6">else</span> {
    MpReleaseProcessContext(processCtx);
    <span style="color:#ff79c6">return</span> STATUS_SUCCESS;
  }
}</code></pre></div>
<p>I still don&rsquo;t have a clue why is the access being denied to process with the <strong>MpServiceSid</strong>. Even thou, being a callback that&rsquo;s only registered if running a version of Windows under NT 6.3 it may have to do something with that. In case someone can shed some light on this topic I would kindly appreciate it! :D</p>

<h2 id="mpregcallback">MpRegCallback</h2>

<p>Finally we get into the main routine for handling registry operations, this routine is registered inside <code>MpRegisterRegCallback</code>, which is the last function called in the <code>DriverEntry</code>. As with the previous registry routine, <code>MpRegCallback</code> function prototype is also <code>EX_CALLBACK_FUNCTION</code>. And again, no context will be registered for this function.</p>

<blockquote>
<p>This routine is registered using <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-cmregistercallback" target="_blank">CmRegisterCallback</a> instead of <code>CmRegisterCallbackEx</code>, may be legacy code not modified since this function is obsolete since Windows Vista.</p>
</blockquote>

<p>Getting into the actual registry callback routine, the function will begin by checking if the <em>Argument1</em> &ndash; which keeps a value from within the enum <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_reg_notify_class" target="_blank">REG_NOTIFY_CLASS</a> and identifies the type of registry operation &ndash; contains one of the monitored <em>Pre</em> operations values from which it will retrieve some data from the structure contained in <em>Argument2</em> &ndash; As stated on the msdn, <em>Argument2</em> has a pointer to a structure that contains information that is specific to the type of registry operation &ndash; to determine this, the following bitmask is used <code>0x220000000017</code>. I will save you the time of determining which <code>REG_NOTIFY_CLASS</code> values match the bitmask:</p>

<ul>
<li>RegNtDeleteKey        = 0</li>
<li>RegNtSetValueKey      = 1</li>
<li>RegNtDeleteValueKey   = 2</li>
<li>RegNtRenameKey        = 4</li>
<li>RegNtPostRestoreKey   = 2Ah</li>
<li>RegNtPreReplaceKey    = 2Dh</li>
</ul>

<p>For pretty much all of these values, the function will retrieve the registry key <em>Object</em> that&rsquo;s inside the structure. The only one that differs is the case of <code>RegNtRenameKey</code> where the <em>NewName</em> will also be saved into a local.</p>

<blockquote>
<p>Even thou <strong>RegNtPreCreateKeyEx</strong> is not checked with the bitmask, actually the first check done in the function is to see if <em>Argument1</em> contains the value RegNtPreCreateKeyEx (0x1A), and in this case the pointer to the structure <code>REG_CREATE_KEY_INFORMATION_V1</code> is copied to a local.</p>
</blockquote>

<p>Once the function has the necessary values, it will proceed to check if the process that trigger the callback is one of the following:</p>

<ul>
<li>System</li>
<li>MsMpEng</li>
<li>FriendlyProcess (<code>ProcessCtx-&gt;ProcessFlags &amp; 0x20</code>)</li>
<li>MpServicesSidProcess (<code>ProcessCtx-&gt;ProcessFlags &amp; 0x10</code>)</li>
</ul>

<p>If the process meets any of the previous checks then <code>MpRegHardeningIsMatch</code> won&rsquo;t be called for this operation, shortly we will visit that function but first we need to check some pre-processing that&rsquo;s done in case the previous check is not met. This pre-processing can take three paths:</p>

<ul>
<li><p>First path is regarding the case of key creation, this path will mainly check if the key to be created already exists, in order to do this it calls <code>MpRegpCheckExistingKey</code> &ndash; This function will basically try to get a handle to the object using the <em>RootObject</em> and then try to open this key, also the function will return a copy of the <em>CompleteName</em>.</p></li>

<li><p>Second case applies to <strong>RegKeyNewName</strong>, for this path the function will first obtain the <em>ObjectName</em> using function <code>MpRegpGetKeyName</code> &ndash; This function will call <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-cmcallbackgetkeyobjectidex" target="_blank">CmCallbackGetKeyObjectIDEx</a> if running Windows 8 or above, in any other case it will pop an entry from <code>MpRegData-&gt;KeyNamesLookaside</code> and use <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-obquerynamestring" target="_blank">ObQueryNameString</a> to obtain the object name &ndash; using the function name and the <em>NewName</em> it will create a new unicode string which will be used afterwards to call <code>MpRegHardeningIsMatch</code></p></li>

<li><p>Last path applies to all the other registry operations we saw before, and is quite simple. It will call <code>MpRegpGetKeyName</code> to get the object name to then call <code>MpRegHardeningIsMatch</code></p></li>
</ul>

<blockquote>
<p>It&rsquo;s curious to see they use <code>ObQueryNameString</code> instead of <code>CmCallbackGetKeyObjectID</code>, the latter is available since Windows Vista. Which makes me wonder if this piece of code comes from the Windows XP era and maybe they updated it on Windows 8 to use <code>CmCallbackGetKeyObjectIDEx</code> which became available. Just a random thought 😁</p>
</blockquote>

<p>Last step before starting with the actual processing of the operations is to check if the key involved matches one of the hardened keys. As already said this is done inside <code>MpRegHardeningIsMatch</code>, this function receives a unicode string as only parameter and it will iterate the list <code>MpRegData-&gt;ServiceKeyHardeningList</code> checking if the regkey passed as parameter match any of the list &ndash; <code>RtlPrefixUnicodeString</code> &ndash; if it does then it will return <code>TRUE</code>. If this function returns true, then no matter what type operation is being done the registry callback will return <code>STATUS_ACCESS_DENIED</code></p>

<p>Finally we get into the actual processing of the different registry operations, first step in this process is to check two bitmasks. First one (<code>0x66000C0B8017</code>) contains all the registry operations that the callback will check, second one (<code>0x4400080B8000</code>) contains all the Post operations checked, and will be used in order to know if a <strong>CallCtx</strong> can be fetched &ndash; Later we will see more about this <strong>CallCtx</strong> stuff.</p>

<p>As before I&rsquo;ll save you the time of checking these bitmasks (I&rsquo;ll omit the values checked before, but those are included in the bitmask that contains all operations):</p>

<ul>
<li>RegNtPostDeleteKey  = 0Fh<br /></li>
<li>RegNtPostSetValueKey  = 10h<br /></li>
<li>RegNtPostDeleteValueKey  = 11h<br /></li>
<li>RegNtPostRenameKey  = 13h<br /></li>
<li>RegNtPostCreateKeyEx  = 1Bh<br /></li>
<li>RegNtPostRestoreKey  = 2Ah<br /></li>
<li>RegNtPostReplaceKey  = 2Eh</li>
</ul>

<p>After those two checks the code will go into a switch statement that will end up calling the specific subfunction that will handle the registry operation. I will divide these subfunctions in different sections that will contain the different pre-operations for each type of operation, then we will discuss all the post-operations in one section since they are pretty much the same.</p>

<blockquote>
<p><strong>Disclaimer:</strong> These subfunctions don&rsquo;t differ much but we will at least see the function prototype and structures/enums involved in each one. Also, by the name of the function it can be implied to which type of operation they correspond.</p>
</blockquote>

<h3 id="mpregprecreatekeyex">MpRegPreCreateKeyEx</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreCreateKeyEx</span>(
  PREG_CREATE_KEY_INFORMATION_V1 CreateKeyInfo, 
  ULONG MonitoredKeysRules, 
  PKeyCtx <span style="color:#ff79c6">*</span>CreateKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName, 
  BOOLEAN KeyExist
);</code></pre></div>
<p>The function will start by doing a sanity check on <em>CreateKeyInfo</em> and <em>CreateKeyCtx</em>, if everything is fine it will check that <strong>CreateKeyOperation</strong> (<code>0x1</code>) is active in <em>MonitoredKeysRules</em>, after that if no <em>KeyName</em> is provided then function <code>MpRegpCheckExistingKey</code> will be called in order to obtain the <em>KeyName</em> and to check if the <em>KeyExisy</em>. In case the key is found the function will return, in case it doesn&rsquo;t <code>MpRegMatchData</code> will be called</p>

<blockquote>
<p><code>MpRegMatchData</code> is probably the most important function regarding registry operations and we will discuss it in detail later in the post, for now let&rsquo;s imagine that this function will check the <em>KeyName</em> against a list of keys and if found it will return the rules that apply to it</p>
</blockquote>

<p>if <code>MpRegMatchData</code> doesn&rsquo;t find a matching key then the function will return, on the other hand if a matching key is found then the code will check if <strong>CreateDenied</strong> (<code>0x10000</code>) is active for that key, if the value is active then it will proceed to check if the process trying to create the key match any of the following requirements:</p>

<ul>
<li><code>ProcessCtx-&gt;ProcessRules</code> has <strong>AllowAllRegistryOperations</strong> (<code>0x400</code>) set.</li>
<li>The process is a ExcludedProcess (<code>ProcessCtx-&gt;ProcessFlags &amp; 0x1</code>)</li>
<li>The process is a FriendlyProcess (<code>ProcessCtx-&gt;ProcessFlags &amp; 0x20</code>)</li>
<li>The process is a MpServiceSidProcess (<code>ProcessCtx-&gt;ProcessFlags &amp; 0x10</code>)</li>
</ul>

<p>if any of these requirements is met, then the access won&rsquo;t be denied, but if the process doesn&rsquo;t match the requirements then parameter <em>AccessDenied</em> will be set to <code>TRUE</code> and a notification throughout <code>MpRegpSendNotification</code> will be sent.</p>

<p>There&rsquo;s another case where they key rules don&rsquo;t have the <strong>CreateDenied</strong> bit set, but it has the <strong>CreateKeyOperation</strong> bit set. In this case, a <strong>CallCtx</strong> will be created. This <strong>CallCtx</strong> has a union which differs depending which type of operation is representing, for the key creation the <strong>CallCtx</strong> will be the following</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CallCtx
{
  USHORT Magic;     <span style="color:#6272a4">// Set to 0xDA0B
</span><span style="color:#6272a4"></span>  USHORT Size;      <span style="color:#6272a4">// Sizeof 0x38
</span><span style="color:#6272a4"></span>  PVOID FreeKeyCtx; <span style="color:#6272a4">// Points to MpRegpFreeCreateKeyContext 
</span><span style="color:#6272a4"></span>  LIST_ENTRY CallCtxList;
  PKTHREAD CurrentThread;
  PUNICODE_STRING KeyName;
  <span style="color:#ff79c6">union</span> TypeOfOperation {
      PMP_REG_MATCH_INFO MatchInfo;
  } CreateAndDeleteKey;
} CallCtx, <span style="color:#ff79c6">*</span>PCallCtx;</code></pre></div>
<p>Finally this created <strong>CallCtx</strong> will be copied into the out-param <em>CreateKeyCtx</em>, so then it can be inserted into the <code>MpRegData-&gt;CallCtxList</code> by calling <code>MpRegpInsertCallContext</code>.</p>

<p><img src="/images/wdFilter/part4/PreCreateKey.png" alt="alt image" title="Pre-operation CreateKey CallCtx" /></p>

<p>Since this was the first one I got into a bit more of detail, next ones are pretty similar so the explanation will be a bit more shallow.</p>

<h3 id="mpregprerestorekey">MpRegPreRestoreKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreRestoreKey</span>(
  PREG_RESTORE_KEY_INFORMATION PreRestoreKeyInfo, 
  ULONG MonitoredKeysRules, 
  PKeyCtx <span style="color:#ff79c6">*</span>RestoreKeyCtx,
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>Also we start with the sanity checks and checking if <strong>RestoreKeyOperation</strong> (<code>0x4000</code>) is active in the <em>MonitoredKeysRules</em>. If we don&rsquo;t have the <em>KeyName</em> then it will be obtained by calling <code>MpRegpGetKeyName</code>. Wit the <em>KeyName</em> <code>MpRegMatchData</code> will be called and as we saw previously there&rsquo;s three options. First no matching data is found so the function will return. Second matching data is found and bit <strong>RestoreDenied</strong> (<code>0x200000</code>) is set, in this case it will again check the process requirements and if they are not met it will set <em>AccessDenied</em> to <code>TRUE</code> and send a notification. Last option is that matching data is found but it only has the <strong>RestoreKeyOperation</strong> bit set in which case the following <strong>CallCtx</strong> will be created &ndash; The <strong>CallCtx</strong> used by this operation is the one meant for the renaming of keys operation, is even allocated with function <code>MpRegpAllocRenameKeyContext</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CallCtx
{
  USHORT Magic;     <span style="color:#6272a4">// Set to 0xDA19
</span><span style="color:#6272a4"></span>  USHORT Size;      <span style="color:#6272a4">// Sizeof 0x40
</span><span style="color:#6272a4"></span>  PVOID FreeKeyCtx; <span style="color:#6272a4">// Points to MpRegpFreeRenameKeyContext 
</span><span style="color:#6272a4"></span>  LIST_ENTRY CallCtxList;
  PKTHREAD CurrentThread;
  PUNICODE_STRING KeyName;
  <span style="color:#ff79c6">union</span> TypeOfOperation {
      PUNICODE_STRING KeyNewName;
      PMP_REG_MATCH_INFO MatchInfo;
  } RenameKey;
} CallCtx, <span style="color:#ff79c6">*</span>PCallCtx;</code></pre></div>
<p>And again this context is saved in the parameter <em>RestoreKeyCtx</em> to then be added to the <strong>CallCtx</strong> list.</p>

<h3 id="mpregprereplacekey">MpRegPreReplaceKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreReplaceKey</span>(
  PREG_REPLACE_KEY_INFORMATION ReplaceKeyInfo, 
  ULONG MonitoredKeysSig, 
  PCallCtx <span style="color:#ff79c6">*</span>RenameKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>Same behavior as before but, of course, the bits checked differ. Bits checked in this function are the following:</p>

<ul>
<li>ReplaceKeyOperation (<code>0x8000</code>)</li>
<li>ReplaceDenied (<code>0x100000</code>)</li>
</ul>

<p>This operation will also use the RenameKey <strong>CallCtx</strong>, so is the same one we just saw in the previous section.</p>

<h3 id="mpregpresetvaluekey">MpRegPreSetValueKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreSetValueKey</span>(
  PREG_SET_VALUE_KEY_INFORMATION SetValueKey, 
  ULONG MonitoredKeysRules, 
  PCallCtx <span style="color:#ff79c6">*</span>SetValueKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>This function also has the same behavior but when it calls <code>MpRegMatchData</code> it will also provide the <em>ValueName</em> that is going to be added, so the <em>KeyName</em> and the <em>ValueName</em> must match. Again if a match is found the function will check for the following two values:</p>

<ul>
<li>SetValueKeyOperation (<code>0x100</code>)</li>
<li>SetValueDenied (<code>0x80000</code>)</li>
</ul>

<p>There&rsquo;s one little detail in this operation, the rule that match may have the value <strong>SetValueRetrieveKeyValueInfo</strong> (<code>0x400</code>) set. If this is the case then <code>MpRegpQueryValueKeyByPointer</code> will be called in order to obtain the <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_value_partial_information" target="_blank">key partial information</a> of the value.</p>

<p>Finally, if the access was not denied but the bit <strong>SetValueKeyOperation</strong> is set then the following <strong>CallCtx</strong> will be created:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CallCtx
{
  USHORT Magic;     <span style="color:#6272a4">// Set to 0xDA0C
</span><span style="color:#6272a4"></span>  USHORT Size;      <span style="color:#6272a4">// Sizeof 0x48
</span><span style="color:#6272a4"></span>  PVOID FreeKeyCtx; <span style="color:#6272a4">// Points to MpRegpFreeSetValueContext 
</span><span style="color:#6272a4"></span>  LIST_ENTRY CallCtxList;
  PKTHREAD CurrentThread;
  PUNICODE_STRING KeyName;
  <span style="color:#ff79c6">union</span> TypeOfOperation {
      PKEY_VALUE_PARTIAL_INFORMATION KeyValueInfo;
      ULONG KeyType;
      PMP_REG_MATCH_INFO MatchInfo;
  } SetValueKeyCtx;
} CallCtx, <span style="color:#ff79c6">*</span>PCallCtx;</code></pre></div>
<p>In the following image we can see an example of this <strong>CallCtx</strong>:</p>

<p><img src="/images/wdFilter/part4/PreSetValueKey.png" alt="alt image" title="Pre-operation SetValueKey CallCtx" /></p>

<h3 id="mpregpredeletevaluekey">MpRegPreDeleteValueKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreDeleteValueKey</span>(
  PREG_DELETE_VALUE_KEY_INFORMATION DeleteValueKeyInfo, 
  ULONG MonitoredKeysRules, 
  PCallCtx <span style="color:#ff79c6">*</span>DeleteValueKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>This function has the same behavior as <code>MpRegPreSetValueKey</code>. It also passes the <em>ValueName</em> to <code>MpRegMatchData</code> and the checks done in case there&rsquo;s a match are the following:</p>

<ul>
<li>DeleteValueKeyOperation (<code>0x800</code>)</li>
<li>DeleteDenied (<code>0x40000</code>)</li>
</ul>

<p>And again we have a value in case the key partial information must be retrieved, <strong>DeleteValueRetrieveKeyValueInfo</strong> (<code>0x2000</code>). Finally, in case a <strong>CallCtx</strong> is created it will look something like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _CallCtx
{
  USHORT Magic;     <span style="color:#6272a4">// Set to 0xDA0D
</span><span style="color:#6272a4"></span>  USHORT Size;      <span style="color:#6272a4">// Sizeof 0x48
</span><span style="color:#6272a4"></span>  PVOID FreeKeyCtx; <span style="color:#6272a4">// Points to MpRegpFreeDeleteValueContext 
</span><span style="color:#6272a4"></span>  LIST_ENTRY CallCtxList;
  PKTHREAD CurrentThread;
  PUNICODE_STRING KeyName;
  <span style="color:#ff79c6">union</span> TypeOfOperation {
      PUNICODE_STRING ValueName;
      PKEY_VALUE_PARTIAL_INFORMATION KeyValueInfo;
      PMP_REG_MATCH_INFO MatchInfo;
  } SetValueKeyCtx;
} CallCtx, <span style="color:#ff79c6">*</span>PCallCtx;</code></pre></div>
<h3 id="mpregprerenamekey">MpRegPreRenameKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreRenameKey</span>(
  PREG_RENAME_KEY_INFORMATION RenameKeyInfo, 
  ULONG MonitoredKeysRules, 
  PCallCtx <span style="color:#ff79c6">*</span>RenameKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>In this function behavior differs a bit from the other cases since there&rsquo;s two <em>KeyName&rsquo;s</em> to match, one for the key before it&rsquo;s renamed and a second one for the renamed key. So <code>MpRegMatchData</code> is called two times with both <em>KeyNames</em> and if both match then the rules are OR&rsquo;ed. Everything else works in the same fashion as previously explained. The checked values are the following:</p>

<ul>
<li>RenameKeyOperation (<code>0x4</code>)</li>
<li>RenameDenied (<code>0x20000</code>)</li>
</ul>

<p>In case a <strong>CallCtx</strong> is created, the type of the context is the one we saw previously in <code>MpRegPreRestoreKey</code></p>

<p><img src="/images/wdFilter/part4/PreRenameKey.png" alt="alt image" title="Pre-operation rename key" /></p>

<h3 id="mpregpredeletekey">MpRegPreDeleteKey</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegPreDeleteKey</span>(
  PREG_DELETE_KEY_INFORMATION DeleteKeyInfo,
  ULONG MonitoredKeysRules, 
  PCallCtx <span style="color:#ff79c6">*</span>DeleteKeyCtx, 
  PBOOLEAN AccessDenied, 
  PUNICODE_STRING KeyName
);</code></pre></div>
<p>Behavior for this pre-operation is exactly the same as the one we saw for the Create key pre-operation, the values checked are the following:</p>

<ul>
<li>DeleteKeyOperation (<code>0x10</code>)</li>
<li>DeleteDenied (<code>0x40000</code>)</li>
</ul>

<p>and in case a <strong>CallCtx</strong> is created, the type of the context is the same as for the create key operation, it only differs in the <code>CallCtx-&gt;Magic</code> which in this case is set to <code>0xDA11</code></p>

<blockquote>
<p>One detail I forgot to mention is that there is a special value that can be set in the rules of the RegKey which I called <strong>TamperProtectionActive</strong> (<code>0x400000</code>), if this value is set the access will be denied no matter which process is trying to perform the operation on that key.</p>
</blockquote>

<h3 id="post-operations">Post-operations</h3>

<p>First things first, as we saw before in the post there is a bitmask for the post-operations and when the <em>RegNotifyClass</em> matches any of these values then function <code>MpRegpFetchCallContext</code> will be called. This function, as the name says, fetches a <strong>CallCtx</strong>. A pseudocode of this function would be something like this:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">PCallCtx <span style="color:#50fa7b">MpRegpFetchCallContext</span>() 
{
  CurrentThread <span style="color:#ff79c6">=</span> KeGetCurrentThread();
  CallCtx <span style="color:#ff79c6">=</span> (PCallCtx) CONTAINING_RECORD(MpRegData<span style="color:#ff79c6">-&gt;</span>CallCtxList.Flink, CallCtx, <span style="color:#f1fa8c">&#34;CallCtxList&#34;</span>);
  <span style="color:#ff79c6">if</span> (CallCtx <span style="color:#ff79c6">!=</span> <span style="color:#ff79c6">&amp;</span>MpRegData<span style="color:#ff79c6">-&gt;</span>CallCtxList) {
    <span style="color:#ff79c6">while</span> (<span style="color:#bd93f9">1</span>) {
      nextCallCtx <span style="color:#ff79c6">=</span> CallCtx<span style="color:#ff79c6">-&gt;</span>CallCtxList.Flink;
      <span style="color:#ff79c6">if</span> (CallCtx<span style="color:#ff79c6">-&gt;</span>CurrentThread <span style="color:#ff79c6">==</span> CurrentThread)
        <span style="color:#ff79c6">break</span>;
      CallCtx <span style="color:#ff79c6">=</span> nextCallCtx;
      <span style="color:#ff79c6">if</span> (nextCallCtx <span style="color:#ff79c6">==</span> <span style="color:#ff79c6">&amp;</span>MpRegData<span style="color:#ff79c6">-&gt;</span>CallCtxList) 
        <span style="color:#ff79c6">goto</span> End;
    }
    <span style="color:#6272a4">// Sanity checks and unchaining
</span><span style="color:#6272a4"></span>  }
<span style="color:#8be9fd;font-style:italic">End</span>:
  <span style="color:#ff79c6">return</span> CallCtx;
}</code></pre></div>
</div>

<p>As you can see basically it will walk the <strong>CallCtx</strong> list entry and try to find one context that matches the same <em>CurrentThread</em> that was set when the context was created in the pre-operation.</p>

<blockquote>
<p>This is safe since, as stated in the MSDN: &ldquo;A RegistryCallback executes at IRQL = PASSIVE_LEVEL and in the context of the thread that is performing the registry operation.&rdquo; Basically we can assume pre and post will execute in the same thread. The following image shows the post-operation from the Create pre-operation shown in the section &ldquo;MpRegPreCreateKeyEx&rdquo;, thread object is the same for both operations.</p>

<p><img src="/images/wdFilter/part4/PostOperation.png" alt="alt image" title="Post-operation thread safe" /></p>
</blockquote>

<p>So after we have the expected <strong>CallCtx</strong> the code will go again into the switch statement to enter into the corresponding post-operation function. All of this post-operation functions will do the same, first do a sanity check checking if a <strong>CallCtx</strong> is passed as an argument and then checking if the <code>CallCtx-&gt;Magic</code> matches the one expected from that type of operation. If sanity checks are correct, then the function will proceed to create a <code>RegNotification</code> and send it throughout <code>MpRegpSendNotification</code> &ndash; We&rsquo;ll see both the notification structure and the function later in the post.</p>

<h2 id="mpregmatchdata">MpRegMatchData</h2>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpRegMatchData</span>(
  PUNICODE_STRING KeyName, 
  PUNICODE_STRING ValueName, 
  ULONG Flags, 
  PMP_REG_MATCH_INFO <span style="color:#ff79c6">*</span>MatchingInfo
);</code></pre></div>
<p>Finally we get into the function that actually checks if certain type of operation on a Key is allowed. First thing this function will do is obtain a pointer to the data that keeps the keys that will be monitored, this pointer can be obtained from <code>MpRegData-&gt;MonitoredKeys</code>.</p>

<blockquote>
<p>In case you are curios this data comes from user space &ndash; Parsed in the function MpRegUpdateData &ndash; more specifically it comes from <strong>MpRtp.dll</strong>, which is the Real-time protection module of the Windows Defender. Since I&rsquo;m just focusing on the kernel I didn&rsquo;t check how this data is obtained. But is a nice project to look into it (Even thou is C++&hellip; maybe in the future 🤔)</p>
</blockquote>

<p>Going back to <code>MpRegData-&gt;MonitoredKeys</code>, this member contains a pointer to a <code>MP_REG_USER_DATA</code> structure, which looks like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_REG_USER_DATA
{
  <span style="color:#8be9fd">int</span> DataSize;
  <span style="color:#8be9fd">int</span> NumberOfEntries;
  PMP_KEY_ENTRY MonitoredKeysTree;
  ULONG MonitoredKeysRules;
} MP_REG_USER_DATA, <span style="color:#ff79c6">*</span>PMP_REG_USER_DATA;</code></pre></div>
<p>With this data the function can start to search if the <em>KeyName</em> is included in the monitored keys, in order to understand how this is done we first need to understand how the data is laid out. First we need to know the definition of the structure I coined <code>MP_KEY_ENTRY</code>:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_KEY_ENTRY
{
  PMP_KEY_ENTRY SubKey;
  PMP_KEY_ENTRY NextKey;
  PWSTR KeyName;
  USHORT KeysToSkip;
  PMP_CLIENT_VALUE ClientList;
  PMP_KEY_VALUE ValuesList;
} MP_KEY_ENTRY, <span style="color:#ff79c6">*</span>PMP_KEY_ENTRY;</code></pre></div>
<p>as you can see the structure keeps a pointer to a <em>SubKey</em>, a <em>NextKey</em> (Both of type <code>MP_KEY_ENTRY</code>) and a <em>KeyName</em>. So as you may have already guess the data is laid out in a kind of binary tree. So the pseudocode of how this data will be walked looks something like this (It&rsquo;s super simplified):</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">keyEntry <span style="color:#ff79c6">=</span> MpRegData<span style="color:#ff79c6">-&gt;</span>MonitoredKeys<span style="color:#ff79c6">-&gt;</span>MonitoredKeysTree; <span style="color:#6272a4">// Root KeyName =&gt; Registry
</span><span style="color:#6272a4"></span>
<span style="color:#ff79c6">while</span> (<span style="color:#bd93f9">1</span>) {
  FsRtlDissectName(<span style="color:#ff79c6">&amp;</span>keyNameToMatch, <span style="color:#ff79c6">&amp;</span>firstName, <span style="color:#ff79c6">&amp;</span>remainingName);

  <span style="color:#ff79c6">if</span> (keyEntry<span style="color:#ff79c6">-&gt;</span>KeyName) {
    partialMatch <span style="color:#ff79c6">=</span> MpRegpMatchName(keyEntry<span style="color:#ff79c6">-&gt;</span>KeyName, <span style="color:#ff79c6">&amp;</span>FirstName);
  } <span style="color:#ff79c6">else</span> {
    <span style="color:#ff79c6">if</span> (keyEntry<span style="color:#ff79c6">-&gt;</span>KeysToSkip <span style="color:#ff79c6">==</span> <span style="color:#bd93f9">0xFFFF</span>) {
      partialMatch <span style="color:#ff79c6">=</span> TRUE;
    } <span style="color:#ff79c6">else</span> {
      <span style="color:#6272a4">// Used to skip key paths that have KeyNames that differ on each PC (Like User&#39;s SID)    
</span><span style="color:#6272a4"></span>      <span style="color:#ff79c6">do</span> {
        FsRtlDissectName(<span style="color:#ff79c6">&amp;</span>keyNameToMatch, <span style="color:#ff79c6">&amp;</span>tmp, <span style="color:#ff79c6">&amp;</span>remainingName)
      }
      <span style="color:#ff79c6">while</span>(keyEntry<span style="color:#ff79c6">-&gt;</span>KeysToSkip)
      partialMatch <span style="color:#ff79c6">=</span> tmp.Length <span style="color:#ff79c6">!=</span> <span style="color:#bd93f9">0</span>;
    }
  }

  <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>partialMatch) {
    keyEntry <span style="color:#ff79c6">=</span> keyEntry<span style="color:#ff79c6">-&gt;</span>NextKey;
    <span style="color:#ff79c6">continue</span>; 
  } 

  MpRegpMatchEntry(....);
  <span style="color:#ff79c6">if</span> (keyEntry<span style="color:#ff79c6">-&gt;</span>NextKey) {
    <span style="color:#6272a4">// The function keeps a stack of non-visited nextKeys, in order to come back later
</span><span style="color:#6272a4"></span>    MpRegpPushEntryToStack(....);
  }
  keyEntry <span style="color:#ff79c6">=</span> keyEntry<span style="color:#ff79c6">-&gt;</span>SubKey;

  <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>keyEntry) {
    <span style="color:#6272a4">// I&#39;m leaving out some checks here that would check if there&#39;s 
</span><span style="color:#6272a4"></span>    <span style="color:#6272a4">// entries in the stack, if there are no entries it means we reached
</span><span style="color:#6272a4"></span>    <span style="color:#6272a4">// the end so we would break 
</span><span style="color:#6272a4"></span>    MpRegpPopEntryFromStack(....);
  }

  keyNameToMatch <span style="color:#ff79c6">=</span> remainingName;
}</code></pre></div>
</div>

<p>So as you can see, the algorithm is not that hard. The whole KeyName will be dissect and the first name will be compared against the actual entry, if it matches then we go to the <em>SubKey</em> and we save the <em>NextKey</em> in the non-visited stack. In case the entry <em>KeyName</em> didn&rsquo;t match then the algorithm will go to the <em>NextKey</em> if there is, if there is no <em>NextKey</em> then an entry will be poped from the stack and the same will be repeated &ndash; I hope this is more or less clear :).</p>

<p>So now the last step, you may have noticed an strange function in the middle of the algorithm, <code>MpRegpMatchEntry</code>. This function is the one that fills the structure <code>MP_REG_MATCH_INFO</code> which is then returned to the pre-operation functions and contains the rules that apply to the Key being manipulated.</p>

<p>This function will only execute if the key path to check has matched fully. If this is the case then there&rsquo;s two possible paths. First path is for every operation other than <strong>SetValueKeyOperation</strong> and <strong>DeleteValueKeyOperation</strong>, in this case the <code>MP_KEY_ENTRY-&gt;ClientList</code> will be obtained, this member contains the following structure:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_CLIENT_VALUE
{
  PMP_CLIENT_VALUE NextClientValue;
  BYTE ValueHash[<span style="color:#bd93f9">16</span>];
  ULONG KeyRules;
} MP_CLIENT_VALUE, <span style="color:#ff79c6">*</span>PMP_CLIENT_VALUE;</code></pre></div>
<p>second path is for the case of <em>SetValueKey</em> and <em>DeleteValueKey</em>, in this case <code>MP_KEY_ENTRY-&gt;ValuesList</code> will be obtained, and this member contains the following structure:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_KEY_VALUE
{
  PMP_KEY_VALUE NextKeyValue;
  PWSTR KeyValueName;
  PMP_CLIENT_VALUE ClientValue;
} MP_KEY_VALUE, <span style="color:#ff79c6">*</span>PMP_KEY_VALUE;</code></pre></div>
<p>in order for the function to obtain the <code>MP_KEY_VALUE-&gt;ClientValue</code>, the <em>ValueName</em> that the operation wants to set or delete must match the one from the structure.</p>

<p>An mainly how the function will work is by comparing the <code>MP_CLIENT_VALUE-&gt;KeyRules</code> with the <em>Flag</em> passed as an argument when calling <code>MpRegMatchData</code></p>

<blockquote>
<p>This flag is build in every pre-operation function, and keeps both values we saw in each pre-operation. For instance for a key creation this flag would be: <code>CreateDenied | CreateKeyOperation (0x100001)</code></p>
</blockquote>

<p>if the comparison of the flag with the <em>KeyRules</em> returns true then a <code>MP_REG_MATCH_INFO</code> structure will be allocated and the <em>KeyRules</em> and <em>ValueHash</em> will be copied</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_REG_MATCH_INFO
{
  INT HashesCount;
  ULONG HashesArrayLen;
  _OWORD (<span style="color:#ff79c6">*</span>HashesArray)[];
  BYTE KeyValueInfoFlag;
  ULONG KeyRules;
} MP_REG_MATCH_INFO, <span style="color:#ff79c6">*</span>PMP_REG_MATCH_INFO;</code></pre></div>
<blockquote>
<p>The <em>ValueHash</em> is not used in the WdFilter, but since this is sent to the <strong>MsMpEng</strong> I guess it&rsquo;s probably used there. Also, I&rsquo;m not sure what the hash represents, since this hash comes from <strong>MpRtp</strong> I don&rsquo;t know which data is being hashed.</p>
</blockquote>

<p>Lastly, since this is super painful to debug I decided to practice my JavaScript debugger scripting and wrote the following <a href="https://gist.github.com/n4r1b/2d913f50e9de4767df96bf0fc01b757b" target="_blank"><strong>script</strong></a> that has two options:</p>

<ul>
<li>Create an instance of an MP_KEY_ENTRY, MP_KEY_VALUE or MP_CLIENT_VALUE</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">&gt;</span> dx Debugger.Utility.Analysis.WdFilterExtension.CreateInstance(typeName, addrObj)</code></pre></div>
<ul>
<li>List all the monitored keys</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">&gt;</span> <span style="color:#ff79c6">!</span>mpRegData
<span style="color:#ff79c6">&gt;</span> dx Debugger.Utility.Analysis.WdFilterExtension.RegUserData()</code></pre></div>
<p>The script is not bulletproof, I just wrote it to make the debugging easier for me, but it has many flaws (For example, not showing the whole key path to get to a specific <code>MP_KEY_ENTRY</code>) thou it comes in handy if we use it with <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/using-linq-with-the-debugger-objects" target="_blank">LINQ</a> syntax to search for a specific <em>KeyName</em> or <em>ValueName</em>. For example we could run the following query to search for an entry that has the <em>KeyName</em> <strong>MsMpEng.exe</strong>, and then check which rules apply to this key.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#ff79c6">&gt;</span> dx <span style="color:#ff79c6">-</span>r1 @$mpRegUserData().MpRegUserData.MonitoredKeysTree.Select(p =&gt; <span style="color:#ff79c6">new</span> { 
    Name <span style="color:#ff79c6">=</span> p.KeyName, 
    Client <span style="color:#ff79c6">=</span> p.ClientList.Select(n =&gt; <span style="color:#ff79c6">new</span> { Hash <span style="color:#ff79c6">=</span> n.ValueHash, KeyRules <span style="color:#ff79c6">=</span> n.KeyRules })
  }).Where(p =&gt; p.Name <span style="color:#ff79c6">!=</span> <span style="color:#bd93f9">0x0</span> <span style="color:#ff79c6">&amp;&amp;</span> p.Name.ToDisplayString(<span style="color:#f1fa8c">&#34;su&#34;</span>).ToLower().Contains(<span style="color:#f1fa8c">&#34;msmpeng.exe&#34;</span>))
</code></pre></div>
<p>The following picture shows this query and one looking for the monitored values inside the <em>Windows Defender</em> key.</p>

<p><img src="/images/wdFilter/part4/WindbgScript.png" alt="alt image" title="Example WinDbg script" /></p>

<h2 id="mpregpsendnotification">MpRegpSendNotification</h2>

<p>As seen during the post there&rsquo;s two possible ways for the Registry Callback to send a notification. First, one in case the operation is denied. And Second, in case a pre-operation creates a <strong>CallCtx</strong> so the post-operation will retrieve this context and send a notification. The function in charge of preparing the notification is <code>MpRegpSendNotification</code>. This function is quite simple, and since the post is already super long I won&rsquo;t get into all the little details. Mainly this function will receive a pointer to a structure I named <code>RegNotification</code> which looks like this:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _RegNotification
{
  PVOID KeyObject;
  PUNICODE_STRING KeyName;
  PUNICODE_STRING ValueName;
  PUNICODE_STRING NewKeyName;
  PUNICODE_STRING OldFileName;
  PUNICODE_STRING NewFileName;
  ULONG ValueType;
  ULONG ValueDataSize;
  PVOID ValueData;
  ULONG NewValueType;
  ULONG NewValueDataSize;
  ULONG RegRestoreFlags;
  PVOID NewValueData;
  ULONG FinalKeyRules;
  PMP_REG_MATCH_INFO MatchInfo;
} RegNotification, <span style="color:#ff79c6">*</span>PRegNotification;</code></pre></div>
</div>

<p>As you may notice, this structure contains fields for every possible operation this means they use the same structure for every registry operation, and just populate the fields that apply in each operation.</p>

<p>With this information <code>MpRegpSendNotification</code> will calculate the necessary size of the buffer to allocate for the notification, and then proceed to allocate it by calling <code>MpAsyncCreateNotification</code>. This <code>AsyncMessageData</code> buffer will contain the following data type in the union <em>TypeOfMessage</em>:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _RegOperationMessage
{
  INT64 OffsetKeyName;
  INT64 OffsetValueName;
  INT64 OffsetNewKeyName;
  INT64 OffsetOldFileName;
  INT64 OffsetNewFileName;
  AuxPidCreationTime Process;
  HANDLE ThreadId;
  DWORD SessionId;
  ULONG FinalKeyRules;
  ULONG NewValueType;
  ULONG BufferNewValueDataLen;
  INT64 OffsetNewValueData;
  ULONG ValueType;
  ULONG BufferValueDataLen;
  INT64 OffsetValueData;
  ULONG RegRestoreFlags;
  GUID TransactionId;
  INT HashesCount;
  INT64 OffsetHashesArray;
} RegOperationMessage, <span style="color:#ff79c6">*</span>PRegOperationMessage;</code></pre></div>
</div>

<blockquote>
<p>There&rsquo;s a helper function that is the one in charge of copying the data from the <code>RegNotification</code> to the <code>RegOperationMessage</code>. In case you&rsquo;d like to look at it, this function is <code>MpRegpCopyVariableNotificationData</code></p>
</blockquote>

<p>Finally, the message will be sent either synchronously in case the <code>ProcessCtx-&gt;ProcessRules</code> have the bit <strong>NotifyRegistryOperationSync</strong> (<code>0x200000</code>) active or asynchronously in any other case &ndash; For the sync message the type of operation will be set to <strong>RegistryEventSync</strong> (<code>0x2</code>).</p>

<p><img src="/images/wdFilter/part4/SendNotification.png" alt="alt image" title="Send notification" /></p>

<h2 id="conclusion">Conclusion</h2>

<p>And that&rsquo;s all for this part folks! Again sorry for the long post but I believe this is one of the coolest parts of the driver so I wanted to get a bit in depth with some things. In the next post we will end up code non-related to the minifilter capabilities of the driver!! We will see the different messages <strong>MsMpEng</strong> can send to <strong>WdFilter</strong> in order to trigger different operations like adding a process to the excluded list or creating a section for a data scan! If this sounds cool, see ya in the next post! :)</p>

<p>As always if there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a></p>
]]></content></item><item><title>Dissecting the Windows Defender Driver - WdFilter (Part 3)</title><link>https://n4r1b.com/posts/2020/03/dissecting-the-windows-defender-driver-wdfilter-part-3/</link><pubDate>Mon, 23 Mar 2020 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2020/03/dissecting-the-windows-defender-driver-wdfilter-part-3/</guid><description>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how WdFilter handles the loading of images in memory through an ImageLoad callback routine, we also saw how new threads are checked in two different Thread-creation callback routines and lastly we saw how messages are sent to MsMpEng both synchronously and asynchronously. And now for this part, we will focus on the following things:
Process and Desktop handle operations callback Drivers information and verification So without further ado let&amp;rsquo;s get into it.</description><content type="html"><![CDATA[

<p>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how <strong>WdFilter</strong> handles the loading of images in memory through an ImageLoad callback routine, we also saw how new threads are checked in two different Thread-creation callback routines and lastly we saw how messages are sent to <strong>MsMpEng</strong> both synchronously and asynchronously. And now for this part, we will focus on the following things:</p>

<ul>
<li>Process and Desktop handle operations callback</li>
<li>Drivers information and verification</li>
</ul>

<p>So without further ado let&rsquo;s get into it.</p>

<h3 id="process-desktop-handle-callbacks">Process &amp; Desktop handle callbacks</h3>

<p>First things first, how the initialization of the Object callbacks is done. This process starts inside <code>MpObInitialize</code>, this function will obtain dynamically the address of two functions:</p>

<ul>
<li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-obregistercallbacks" target="_blank">ObRegisterCallbacks</a> (Pointer saved in <code>MpData-&gt;pObRegisterCallbacks</code>)</li>
<li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-obunregistercallbacks" target="_blank">ObUnRegisterCallbacks</a> (Pointer saved in <code>MpData-&gt;pObUnRegisterCallbacks</code>)</li>
</ul>

<p>If both function pointers were retrieved then it will proceed to call <code>MpObAddCallback</code>. The main job of  <code>MpObAddCallback</code> is to actually register the callback and return, in an out parameter, the registration handle which is then saved in <code>MpData-&gt;ObRegistrationHandle</code>.</p>

<p>In order to register an Object callback a <code>OB_CALLBACK_REGISTRATION</code> structure must be provided to <code>ObRegisterCallbacks</code>. Among other things this structure contains an array of <code>OB_OPERATION_REGISTRATION</code> which will be initialized in this way:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">OB_CALLBACK_REGISTRATION    ObCbRegistration <span style="color:#ff79c6">=</span> {}     
OB_OPERATION_REGISTRATION   OperationRegistration[<span style="color:#bd93f9">2</span>] <span style="color:#ff79c6">=</span> {}

OperationRegistration[<span style="color:#bd93f9">0</span>].Operations <span style="color:#ff79c6">=</span> OB_OPERATION_HANDLE_CREATE <span style="color:#ff79c6">|</span> OB_OPERATION_HANDLE_DUPLICATE;
OperationRegistration[<span style="color:#bd93f9">0</span>].ObjectType <span style="color:#ff79c6">=</span> PsProcessType;
OperationRegistration[<span style="color:#bd93f9">0</span>].PreOperation <span style="color:#ff79c6">=</span> MpObPreOperationCallback;

<span style="color:#ff79c6">if</span> (MpData<span style="color:#ff79c6">-&gt;</span>OsVersionMask <span style="color:#ff79c6">&amp;</span> OsVersionWin10) {
    OperationRegistration[<span style="color:#bd93f9">0</span>].Operations <span style="color:#ff79c6">=</span> OB_OPERATION_HANDLE_CREATE <span style="color:#ff79c6">|</span> OB_OPERATION_HANDLE_DUPLICATE;
    OperationRegistration[<span style="color:#bd93f9">0</span>].ObjectType <span style="color:#ff79c6">=</span> ExDesktopObjectType;
    OperationRegistration[<span style="color:#bd93f9">0</span>].PreOperation <span style="color:#ff79c6">=</span> MpObPreOperationCallback;
    ObCbRegistration.OperationRegistrationCount <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">2</span>;
} <span style="color:#ff79c6">else</span> {
    ObCbRegistration.OperationRegistrationCount <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
}

ObCbRegistration.OperationRegistration <span style="color:#ff79c6">=</span> OperationRegistration;</code></pre></div>
</div>

<p>In the previous pseudocode we can see how two entries (In case of Windows 10) are being added into the array, both of the operations register the same <em>PreOperation</em> and no <em>PostOperation</em>, also both register to handle creation and duplication. Now we are going to focus on the <em>PreOperation</em> function <code>MpObPreOperationCallback</code></p>

<blockquote>
<p>To learn much more than what I explained about all this structure and other cool stuff I strongly recommend this post <a href="https://rayanfam.com/topics/reversing-windows-internals-part1/" target="_blank">https://rayanfam.com/topics/reversing-windows-internals-part1/</a> from <a href="https://twitter.com/Intel80x86" target="_blank">Sinaei</a>.</p>
</blockquote>

<h4 id="mpobpreoperationcallback">MpObPreOperationCallback</h4>

<p>As we saw before this callback is registered for both <strong>PsProcessType</strong> and <strong>ExDesktopObjectType</strong>, so obviously the routine needs a way to distinguish which object is the one triggering the callback. Since this is a <em>PreOperation</em> routine it&rsquo;s prototype must be defined as a <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nc-wdm-pob_pre_operation_callback" target="_blank">POB_PRE_OPERATION_CALLBACK</a> which means the second parameter of it will be an <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_ob_pre_operation_information" target="_blank">OB_PRE_OPERATION_INFORMATION</a> structure that contains a field with the <em>ObjectType</em>, this value can be used to know what type of object triggered the callback. So this function&rsquo;s only job will be to redirect the <em>OperationInformation</em> into the correct function for each object type.</p>

<h4 id="mpobhandleopendesktopcallback">MpObHandleOpenDesktopCallback</h4>

<p>This is the function that handles operation regarding the Desktop Object, it&rsquo;s function will mainly be to act as a notifier. It will receive the <code>OB_PRE_OPERATION_INFORMATION</code> as a parameter and first thing it will do is to obtain the <strong>ProcessCtx</strong> from the current process. The <code>ProcessCtx-&gt;ProcessRules</code> will be checked to see if the value, I coined, <strong>DoNotNotifyDesktopHandlesOp</strong> (<code>0x8</code>) is not set. If the value is not set then the target <em>Object</em> will be retrieved from <code>OB_PRE_OPERATION_INFORMATION</code>. With this <em>Object</em> the code will proceed to obtain it&rsquo;s name throughout the function <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-obquerynamestring" target="_blank">ObQueryNameString</a>. Then a <code>AsyncMessageData</code> structure will be allocated &ndash; Taking into account the length of the object name &ndash; and populated accordingly. The union <em>TypeOfMessage</em> will contain the following structure:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ObDesktopHandleMessage
{
  AuxPidCreationTime Process;
  INT ThreadId;
  INT SessionId;
  BYTE Operation;
  BYTE KernelHandleFlag;
  INT DesiredAccess; <span style="color:#6272a4">// https://docs.microsoft.com/en-us/windows/win32/winstation/desktop-security-and-access-rights
</span><span style="color:#6272a4"></span>  WCHAR <span style="color:#ff79c6">*</span>ObjectName;
} ObDesktopHandleMessage, <span style="color:#ff79c6">*</span>PObDesktopHandleMessage;</code></pre></div>
<p>Once the whole <code>AsyncMessageData</code> is filled, the notification is sent using <code>MpAsyncSendNotification</code>. And that&rsquo;s pretty much all for this callback, as I said in the beginning of the section it mainly works as a notifier.</p>

<p><img src="/images/wdFilter/part3/ObDesktopHandle.png" alt="alt image" title="Async Message Desktop Handle" /></p>

<h4 id="mpobhandleopenprocesscallback">MpObHandleOpenProcessCallback</h4>

<p>This function will handle operations regarding Process handles. In order for this callback to start it&rsquo;s operation the flag <code>MpData-&gt;UnsetObAndRegCallback</code> must not be set, the current process must be other than <strong>MsMpEng</strong> and the handle must not be a <strong>KernelHandle</strong>. If these conditions are met, then the code will proceed to obtain the <strong>ProcessCtx</strong> for both, the current process and the target process &ndash; The current process is the one trying to obtain a handle to the target process &ndash; From now on different rules will be applied depending on which type of access the process is requesting. If the process is requesting any of the following accesses:</p>

<ul>
<li>PROCESS_VM_WRITE - Write to the address space of the target process</li>
<li>PROCESS_VM_OPERATION - Modify the address space of the target process</li>
<li>PROCESS_CREATE_THREAD - Create a new thread in the context of the target process</li>
</ul>

<p>Then the callback will proceed to check if code injection from the current process to the target process is allowed, in order to do this it uses two functions. <code>BOOLEAN MpAllowCodeInjection(PProcessCtx CurrentProcess, PProcessCtx TargetProcess)</code> this function will check if the <em>ProcessFlags</em> of the <em>CurrentProcess</em> match any of the following values:</p>

<ul>
<li>ExcludedProcess - 0x1</li>
<li>MpServiceSidProcess - 0x10</li>
<li>FriendlyProcess  - 0x20</li>
<li>SvchostProcess - 0x100</li>
</ul>

<p>if none flag is matched then it will obtain the value <code>ProcessCtx-&gt;CodeInjectionTargetMask</code> from the <em>TargetProcess</em> and the value <code>ProcessCtx-&gt;CodeInjectionRequestMask</code> from the <em>CurrentProcess</em> and it will proceed to AND the two values to determine if the injection is allowed. The following pseudo-code shows the behavior of this function</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">processFlags <span style="color:#ff79c6">=</span> CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessFlags;
 
<span style="color:#ff79c6">if</span> (processFlags <span style="color:#ff79c6">&amp;</span> ExcludedProcess <span style="color:#ff79c6">||</span> processFlags <span style="color:#ff79c6">&amp;</span> MpServiceSidProcess <span style="color:#ff79c6">||</span>
    processFlags <span style="color:#ff79c6">&amp;</span> FriendlyProcess <span style="color:#ff79c6">||</span> processFlags <span style="color:#ff79c6">&amp;</span> SvchostProcess) {
      <span style="color:#ff79c6">return</span> TRUE;
}
targetMask <span style="color:#ff79c6">=</span> TargetProcess<span style="color:#ff79c6">-&gt;</span>CodeInjectionTargetMask;
requestMask <span style="color:#ff79c6">=</span> CurrentProcess<span style="color:#ff79c6">-&gt;</span>CodeInjectionRequestMask;

<span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>targetMask <span style="color:#ff79c6">||</span> requestMask <span style="color:#ff79c6">==</span> <span style="color:#ff79c6">-</span><span style="color:#bd93f9">1</span> <span style="color:#ff79c6">||</span> targetMask <span style="color:#ff79c6">&amp;</span> requestMask) {
  <span style="color:#ff79c6">return</span> TRUE
} 
MpLogPrintfW(<span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;[Mini-filter] Injection into process %u from process %u is BLOCKED.&#34;</span>,
    TargetProcess<span style="color:#ff79c6">-&gt;</span>ProcessId,
    CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessId);
<span style="color:#ff79c6">return</span> FALSE;</code></pre></div>
<p>in case this function returns <code>FALSE</code> the <em>DesiredAccess</em> will be modified in order to remove the permission that trigger this check.</p>

<p>In case we are running <code>Windows 10 build 16000</code> or higher another check will be done, based on Windows Defender host intrusion and prevention system (HIPS) rules</p>

<blockquote>
<p>To be honest, I don&rsquo;t know much about Windows Defender HIPS, and I couldn&rsquo;t find much information about it on the internet. So I don&rsquo;t know if there&rsquo;s a way to add or check which HIPS rules are running on the system. If someone has more insight about it, please reach out to me as I would love to learn more about this.</p>
</blockquote>

<p>The HIPS rules for handles creation are checked inside <code>MpAllowAccessBasedOnHipsRule</code>. Among other things this function accept the following parameters:</p>

<ul>
<li>HipsRule - <code>@r8</code></li>
<li>ProcessRule - <code>@r9</code></li>
<li>TargetRule - <code>@rsp+20</code></li>
</ul>

<p>and the function will basically check the rules provided as arguments against the corresponding <strong>ProcessRules</strong> &ndash; The HipsRule is checked against the current process rules &ndash; the actual behavior can be seen in the following pseudo-code:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">allowedFlag <span style="color:#ff79c6">=</span> FALSE;
allowedOrBlocked <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;BLOCKED&#34;</span>;
targetRules <span style="color:#ff79c6">=</span> TargetProcess<span style="color:#ff79c6">-&gt;</span>ProcessRules; 
processRules <span style="color:#ff79c6">=</span> CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessRules;

<span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>(processRules <span style="color:#ff79c6">&amp;</span> HipsRule) <span style="color:#ff79c6">||</span> targetRules <span style="color:#ff79c6">&amp;</span> TargetHipsRule <span style="color:#ff79c6">||</span> processRules <span style="color:#ff79c6">&amp;</span> ProcessRule) {
      allowedOrBlocked <span style="color:#ff79c6">=</span> <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;ALLOWED&#34;</span>;
      status <span style="color:#ff79c6">=</span> TRUE;
}

MpLogPrintfW(
    <span style="color:#f1fa8c">L</span><span style="color:#f1fa8c">&#34;[Mini-filter] Applying HipsRule 0x%x: Access from process %u to target %u is &#39;%ls&#39;&#34;</span>,
    HipsRule,
    CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessId,
    TargetProcess<span style="color:#ff79c6">-&gt;</span>ProcessId,
    allowedOrBlocked);

<span style="color:#ff79c6">return</span> allowedFlag;</code></pre></div>
<p>for <em>PROCESS_VM_WRITE</em>, <em>PROCESS_VM_OPERATION</em> and <em>PROCESS_CREATE_THREAD</em> the following values are passed as arguments to this function:</p>

<ul>
<li>HipsRule =&gt; AllowCodeInjectionHIPSRule - 0x8000</li>
<li>ProcessRule =&gt; AllowedToInjectCode - 0x10000</li>
<li>TargetRule =&gt; AllowIncomingCodeInjection - 0x80000</li>
</ul>

<p>Getting into the callback again, there&rsquo;s another set of access rights that will trigger checks, they can be seen in the following list:</p>

<ul>
<li>SYNCHRONIZE - Required to wait for the process to terminate using the wait functions</li>
<li>PROCESS_TERMINATE - Required to terminate a process using TerminateProcess</li>
<li>PROCESS_SUSPEND_RESUME - Required to suspend or resume a process</li>
<li>PROCESS_QUERY_LIMITED_INFORMATION - Required to retrieve certain information about a process</li>
</ul>

<p>in this case the callback will check the value <code>ProcessCtx-&gt;ProcessProtection</code> from the current process in order to check if the <em>Type</em> is <strong>PsProtectedTypeNone</strong> and the <em>Signer</em> less than <strong>PsProtectedSignerAntimalware</strong>. Also as in the previous case, there&rsquo;s a HIPS rule for this case too, in this case the parameters passed to function <code>MpAllowAccessBasedOnHipsRule</code> are the following:</p>

<ul>
<li>HipsRule =&gt; QuerySuspendResumeHIPSRule - 0x800000</li>
<li>ProcessRule =&gt; AllowedToQuerySuspendResume - 0x1000000</li>
<li>TargetRule =&gt; AllowQuerySuspendResume - 0x2000000</li>
</ul>

<p>if any of these checks fail then the <em>DesiredAccess</em> will be adjusted accordingly.</p>

<p>Lastly, this callback will proceed to send an async notification. This notification will be created and send inside <code>MpObSendOpenProcessBMNotification</code>, we&rsquo;ve already seen a couple of functions similar to this one in behavior, it will basically create a <code>AsyncMessageData</code> where the <em>TypeOfMessage</em> will be <code>ObProcessHandleMessage</code>, which is a structure that has the following definition:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ObProcessHandleMessage
{
  AuxPidCreationTime Process;
  AuxPidCreationTime TargetProcess;
  INT SessionId;
  INT FinalDesiredAccess;
  INT FileNameLen;
  INT FileNameOffset;
  INT TargeFileNameLen;
  INT TargeFileNameOffset;
  BYTE CodeInjectionHIPS[<span style="color:#bd93f9">16</span>];           <span style="color:#6272a4">// Needs investigation
</span><span style="color:#6272a4"></span>  BYTE QuerySuspendResumeHIPSRule[<span style="color:#bd93f9">16</span>];  <span style="color:#6272a4">// Needs investigation
</span><span style="color:#6272a4"></span>  INT Unk;
  MP_OB_NOTIFICATION_REASON NotificationReason;
} ObProcessHandleMessage, <span style="color:#ff79c6">*</span> PObProcessHandleMessage;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">enum</span> MP_OB_NOTIFICATION_REASON
{
  <span style="color:#6272a4">// Default notification set to 0x0
</span><span style="color:#6272a4"></span>  DesiredAccessModified <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x1</span>,
  AllowCodeInjectionHIPSTrigger <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2</span>,
  QuerySuspendResumeHIPSTrigger <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x4</span>,
  SameDesiredAccesAndAllowCodeInjectionHIPSTrigger <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x8</span>,
  SameDesiredAccessAndQuerySuspendResumeHIPSTrigger <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x10</span>,
}</code></pre></div>
</div>

<p>Once this structure is allocated and populated the notification will be added to the <code>AsyncNotificationsList</code> for it to be processed by the worker thread.</p>

<p><img src="/images/wdFilter/part3/ObProcessHandle.png" alt="alt image" title="Async Message Process Handle" /></p>

<p>Getting back into the main function, after sending the notification there is one last check before finishing the function, in case the target process is a <strong>MpServiceSidProcess</strong> and the current process is neither a <strong>MpServiceSidProcess</strong> nor a <strong>FriendlyProcess</strong>, then the following access rights will be removed</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>(TargetProcess<span style="color:#ff79c6">-&gt;</span>ProcessFlags <span style="color:#ff79c6">&amp;</span> MpServiceSidProcess)) {

  <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>(CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessFlags <span style="color:#ff79c6">&amp;</span> MpServiceSidProcess) <span style="color:#ff79c6">&amp;&amp;</span> 
      <span style="color:#ff79c6">!</span>(CurrentProcess<span style="color:#ff79c6">-&gt;</span>ProcessFlags <span style="color:#ff79c6">&amp;</span> FriendlyProcess)) {

    ObOpParameters<span style="color:#ff79c6">-&gt;</span>CreateHandleInformation.DesiredAccess <span style="color:#ff79c6">&amp;=</span> 
        <span style="color:#ff79c6">~</span>(PROCESS_VM_WRITE<span style="color:#ff79c6">|</span>PROCESS_VM_OPERATION<span style="color:#ff79c6">|</span>PROCESS_CREATE_THREAD<span style="color:#ff79c6">|</span>PROCESS_TERMINATE);
  }

  <span style="color:#ff79c6">goto</span> ReleaseProcessCtx;
}</code></pre></div>
<blockquote>
<p>More info about <a href="https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights" target="_blank">Process security and Access Rights</a></p>
</blockquote>

<h3 id="drivers-information-and-verification">Drivers information and verification</h3>

<p>First function involved in this process is <code>MpInitializeDriverInfo</code> which is being called from within the <code>DriverEntry</code>. We already mentioned this function in the first post, now we will see more details about it and about other functions related to Drivers info and verification. Getting into the actual function, mainly it will allocate the following structure:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DRIVERS_INFO
{
  INT Status;
  BYTE Reserved[<span style="color:#bd93f9">8</span>];
  INT ElamSignaturesMajorVer;
  INT ElamSignatureMinorVer;
  LIST_ENTRY LoadedDriversList;
  PSLIST_ENTRY ElamRegistryEntries;
  LIST_ENTRY BootProcessList;
  PCALLBACK_OBJECT CallbackObject;
  PVOID BootDriverCallbackRegistration;
  FAST_MUTEX DriversInfoFastMutex;
  INT TotalDriverEntriesLenght;
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pSeRegisterImageVerificationCallback)(SE_IMAGE_TYPE, SE_IMAGE_VERIFICATION_CALLBACK_TYPE, PSE_IMAGE_VERIFICATION_CALLBACK_FUNCTION, PVOID, SE_IMAGE_VERIFICATION_CALLBACK_TOKEN, PVOID <span style="color:#ff79c6">*</span>);
  VOID (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pSeUnregisterImageVerificationCallback)(PVOID);
  PVOID ImageVerificationCbHandle;
  INT RuntimeDriversCount;
  INT RuntimeDriversArrayLenght;
  PVOID RuntimeDriversArray;
  LIST_ENTRY RuntimeDriversList;
  INT64 field_C8;
} MP_DRIVERS_INFO, <span style="color:#ff79c6">*</span>PMP_DRIVERS_INFO</code></pre></div>
</div>

<p>after initializing some fields of the structure the function will obtain a handle to the callback object <code>\Callback\WdEbNotificationCallback</code> and then it will proceed to register <code>MpBootDriverCallback</code> as the callback function, saving the registration handle in the structure member <em>BootDriverCallbackRegistration</em>.</p>

<h4 id="mpadddriverinfo-mpaddbootprocessentry">MpAddDriverInfo &amp; MpAddBootProcessEntry</h4>

<p>Before getting into the boot driver callback I want to explain how list entries <code>LoadedDriversList</code> and <code>BootProcessList</code> are filled. In the former data is going to be chained in <code>MpAddDriverInfo</code> which is executed in the Image-Load callback, while the latter is filled inside <code>MpAddBootProcessEntry</code> which is called from within the Process-Creation callback.</p>

<p>Digging into <code>MpAddDriverInfo</code>, as I just said, is going to be called from within the Image-Load callback whenever the loaded image is a <strong>SystemModeImage</strong>. This function will receive the <code>IMAGE_INFO</code> and the full image name as parameters, and mainly it will allocate memory for the structure <code>MP_DRIVER_INFO</code></p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DRIVER_INFO
{
  LIST_ENTRY DriverInfoList;
  UNICODE_STRING ImageName;
  UNICODE_STRING DriverRegistryPath;
  UNICODE_STRING CertPublisher;
  UNICODE_STRING CertIssuer;
  PVOID ImageHash;
  INT ImageHashAlgorithm;
  INT ImageHashLength;
  PVOID CertThumbprint;
  INT ThumbprintHashAlgorithm;
  INT CertificateThumbprintLength;
  PVOID ImageBase;
  INT64 ImageSize;
  INT ImageFlags;
  INT DriverClassification;
  INT ModuleEntryEnd;
} MP_DRIVER_INFO, <span style="color:#ff79c6">*</span>PMP_DRIVER_INFO;</code></pre></div>
</div>

<p>where it will just fill the <em>ImageSize</em>, <em>ImageBase</em> and the <em>ImageName</em> to then chain this new entry into <code>MP_DRIVERS_INFO-&gt;LoadedDriversList</code>.</p>

<p><img src="/images/wdFilter/part3/AddDriverInfo.png" alt="alt image" title="Add Driver Info" /></p>

<p>For the case of <code>MpAddBootProcessEntry</code> this function is called from within the process creation, and it executes for the first 50 loaded processes (Counter kept in global variable <strong>BootProcessCounter</strong>). The function prototype looks like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">VOID
MpAddBootProcessEntry(
  HANDLE  ProcessId,
  HANDLE  ParentProcessId,
  PCUNICODE_STRING  ImageFileName,
  PCUNICODE_STRING  CmdLine
)</code></pre></div>
<p>and again as the previous case, this function main goal is to allocate and initialize an structure, in this case the structure is <code>MP_BOOT_PROCESS</code> and it&rsquo;s definition is as it follows:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_BOOT_PROCESS
{
  LIST_ENTRY BootProcessList;
  HANDLE ProcessId;
  HANDLE ParentProcessId;
  UNICODE_STRING ImageFileName;
  UNICODE_STRING CommandLine;
  INT SomeFlag;   <span style="color:#6272a4">// Set to 3
</span><span style="color:#6272a4"></span>} MP_BOOT_PROCESS, <span style="color:#ff79c6">*</span>PMP_BOOT_PROCESS;</code></pre></div>
<p>once the entry is initialized is then chained into the list <code>MP_DRIVERS_INFO-&gt;BootProcessList</code>.</p>

<p><img src="/images/wdFilter/part3/AddBootProcess.png" alt="alt image" title="Add Boot Process" /></p>

<h4 id="mpbootdrivercallback">MpBootDriverCallback</h4>

<p>Now that we know how those two list entries are filled we will start looking into the callback function registered during the initialization. As I already explained on my post about the <a href="https://n4r1b.com/posts/2019/11/understanding-wdboot-windows-defender-elam/" target="_blank">Windows Defender ELAM</a> this callback is notified when in the boot driver callback function of the ELAM driver the <code>BDCB_CALLBACK_TYPE</code> is set to <strong>BdCbStatusUpdate</strong> and the image information has the <code>BDCB_CLASSIFICATION</code> set to <strong>BdCbClassificationKnownBadImage</strong>. If this conditions are met then the callback will be notified with <em>Argument1</em> being a pointer to the main <strong>WdBoot</strong> structure, <code>MP_EB_GLOBALS</code>, and <em>Argument2</em> set to the constant <code>0x28</code>.</p>

<p>So getting into <code>MpBootDriverCallback</code>, first thing it will do is a sanity check on <em>Argument1</em> and <em>Argument2</em>, for the latter it will check if is equal to <code>0x28</code> while for the former it will check that the <em>Magic</em> of the structure is <code>0xEB01</code>. If both checks are fine, then it will proceed to iterate the over the list of drivers that was created by <strong>WdBoot</strong> and for every driver it will call <code>MpCopyDriverEntry</code>, which will mainly copy the driver entry data into a <code>MP_DRIVER_INFO</code> structure that will be then chained to <code>MP_DRIVERS_INFO-&gt;LoadedDriversList</code>.</p>

<blockquote>
<p>Disclaimer! The following paragraph describes a path/use-case I haven&rsquo;t been able to trigger so there&rsquo;s gonna be some guessing, I apologize for this. I think this has to do with the fact that ELAM Drivers can use Registry Callbacks or Boot-Driver Callbacks to monitor and validate the configuration data, and at least on my research I&rsquo;ve only seen the second case. <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/install/elam-driver-requirements#am-driver-callback-interface" target="_blank">More info</a></p>
</blockquote>

<p>Once every entry has been copied, then the <code>SLIST_ENTRY</code> <em>ElamRegistryEntries</em> will be walked and for each entry it will call <code>MpCopyElamRegistryEntry</code>. This function will basically copy the entry to a structure I named <code>MP_ELAM_REGISTRY_ENTRY</code> and this structure will be inserted in the singly linked list <code>MP_DRIVERS_INFO-&gt;ElamRegistryEntries</code> &ndash; Probably this has something to do with the ELAM registry hive entries, <code>MP_ELAM_REGISTRY_ENTRY</code> sizeof is <code>0x40</code> and it contains two <code>UNICODE_STRINGS</code> but I can&rsquo;t provide much more info about this, if anyone knows more please reach out to me so I can update this whole paragraph (I&rsquo;ll try to research more thou).</p>

<p>Lastly, two more values are copied from <code>MP_EB_GLOBALS</code> to <code>MP_DRIVERS_INFO</code>. These values are the <em>ElamSignaturesMajorVer</em> and the <em>ElamSignatureMinorVer</em>. And that&rsquo;s all this function will do, so to summarize, it mainly copy the information from <code>MP_EB_GLOBALS</code> &ndash; Which is the information obtained by the ELAM driver &ndash; to the structure <code>MP_DRIVERS_INFO</code>.</p>

<h4 id="mpsetimageverificationcallback">MpSetImageVerificationCallback</h4>

<p>This is one of the last functions executed during the initialization, the goal from this function is mainly to register an Image Verification callback, for this purpose it will retrieve dynamically two function pointers</p>

<ul>
<li>SeRegisterImageVerificationCallback</li>
<li>SeUnregisterImageVerificationCallback</li>
</ul>

<p>Both functions reside in the kernel and they basically do what their name says. <code>SeRegisterImageVerificationCallback</code> has a couple of checks that can be seen on the following pseudo-code:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS 
<span style="color:#50fa7b">SeRegisterImageVerificationCallback</span>(
  SE_IMAGE_TYPE ImageType, 
  SE_IMAGE_VERIFICATION_CALLBACK_TYPE CallbackType, 
  PSE_IMAGE_VERIFICATION_CALLBACK_FUNCTION CallbackFunction, 
  PVOID CallbackContext, 
  SE_IMAGE_VERIFICATION_CALLBACK_TOKEN CallbackToken, 
  PVOID <span style="color:#ff79c6">*</span> RegistrationHandle
)
{
  <span style="color:#ff79c6">if</span> (ImageType <span style="color:#ff79c6">!=</span> SeImageTypeDriver <span style="color:#ff79c6">||</span> CallbackType <span style="color:#ff79c6">||</span> CallbackToken) {
    <span style="color:#6272a4">// CallbackType should be SeImageVerificationCallbackInformational which is 0
</span><span style="color:#6272a4"></span>    <span style="color:#ff79c6">return</span> STATUS_INVALID_PARAMETER;
  }
  
  PVOID registrationHandle <span style="color:#ff79c6">=</span> 
        ExRegisterCallback(ExCbSeImageVerificationDriverInfo, 
                          CallbackFunction, 
                          CallbackContext);

  <span style="color:#ff79c6">if</span> (registrationHandle) {
    <span style="color:#ff79c6">*</span>RegistrationHandle <span style="color:#ff79c6">=</span> registrationHandle;
  }
}</code></pre></div>
</div>

<p>Returning to <code>MpSetImageVerificationCallback</code>, besides registering function <code>MpImageVerificationCallback</code> as the image verification callback routine it will also allocate a pool of size <code>0x800</code> where the <strong>RuntimeDriversArray</strong> will reside.</p>

<h4 id="mpimageverificationcallback">MpImageVerificationCallback</h4>

<p>This callback will be notified from within <code>SepImageVerificationCallbackWorker</code> inside the kernel, the call stack when this callback executes looks something like the following:</p>

<p><img src="/images/wdFilter/part3/CallStackImageVerification.png" alt="alt image" title="Call stack MpImageVerificationCallback" /></p>

<blockquote>
<p>How and when the callback is notified, for now, I will leave it as an exercise for the reader</p>
</blockquote>

<p>Once the callback is notified first thing will do is call <code>MpAllocateDriverInfoEx</code> that will allocate and initialize a <code>MP_DRIVER_INFO_EX</code></p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DRIVER_INFO_EX
{
  USHORT Magic;   <span style="color:#6272a4">// Set to 0xDA18
</span><span style="color:#6272a4"></span>  USHORT Size;    <span style="color:#6272a4">// Sizeof 0xB0
</span><span style="color:#6272a4"></span>  _QWORD WdFilterFlag;
  PVOID SameIndexList;
  _QWORD IndexHash;
  MP_DRIVER_INFO DriverInfo;
} MP_DRIVER_INFO_EX, <span style="color:#ff79c6">*</span>PMP_DRIVER_INFO_EX;</code></pre></div>
</div>

<blockquote>
<p>If you remember the post I wrote about WdBoot, this is the same structure I named <code>MODULE_ENTRY</code> in that post. Also this structure seems to be the extended version of <code>MP_DRIVER_INFO</code>, this recalls <code>IMAGE_INFO_EX</code> and <code>IMAGE_INFO</code> &ndash; In this case is not a pointer is the whole structure contained.</p>
</blockquote>

<p>From here on, the code will do pretty much the same as what I explained on the post about <strong>WdBoot</strong>. An <em>IndexHash</em> will be calculated using the same algorithm</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"> WCHAR  upper;
 _QWORD IndexHash <span style="color:#ff79c6">=</span>  <span style="color:#bd93f9">0x4CB2F</span>;
 <span style="color:#ff79c6">while</span>(<span style="color:#ff79c6">*</span>DriverInfo.ImageName.Buffer) {
     upper <span style="color:#ff79c6">=</span> RtlUpcaseUnicodeChar(<span style="color:#ff79c6">*</span>DriverInfo.ImageName.Buffer);
     IndexHash <span style="color:#ff79c6">=</span> HIBYTE(upper) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (upper <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> IndexHash);
     DriverInfo.ImageName.Buffer<span style="color:#ff79c6">++</span>;
 }</code></pre></div>
<p>to then using this <em>IndexHash</em> to obtain an index in the <strong>RuntimeDriversArray</strong> using the following algorithm:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">DWROD size <span style="color:#ff79c6">=</span> (MpDriversInfo.RuntimeDriversArray <span style="color:#ff79c6">&gt;&gt;</span> <span style="color:#bd93f9">5</span>) <span style="color:#ff79c6">-</span> <span style="color:#bd93f9">1</span>;
_QWORD tmp <span style="color:#ff79c6">=</span> IndexHash <span style="color:#ff79c6">&amp;</span> (<span style="color:#ff79c6">-</span><span style="color:#bd93f9">1</span> <span style="color:#ff79c6">&lt;&lt;</span> (MpDriversInfo.RuntimeDriversArray <span style="color:#ff79c6">&amp;</span> <span style="color:#bd93f9">0x1F</span>))
_QWORD idx <span style="color:#ff79c6">=</span> (<span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE6(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE5(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE4(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE3(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE2(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE1(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0xB15DCB</span>))))))) <span style="color:#ff79c6">+</span> HIBYTE(tmp)) <span style="color:#ff79c6">&amp;</span> size;</code></pre></div>
<blockquote>
<p>Please refer to the WdBoot post in order to get a better understanding on how all this madness actually works.</p>
</blockquote>

<p>Lastly, the driver will be chained into <code>MpDriversInfo.RuntimeDriversList</code>.</p>

<p><img src="/images/wdFilter/part3/ImageVerification.png" alt="alt image" title="Image Verification callback" /></p>

<p>Everything we&rsquo;ve seen regarding the Drivers information comes into play in one function we will see in another post called <code>MpQueryLoadedDrivers</code>. This function can be triggered by <strong>MsMpEng</strong> in order to obtain a copy of <code>MP_DRIVERS_INFO</code> data.</p>

<h3 id="conclusion">Conclusion</h3>

<p>And that&rsquo;s all for this post! I&rsquo;m sorry if the driver information part is a bit messy, couldn&rsquo;t find a better way to explain it, I hope at least the big picture is clear. We are not far away from starting to see the filtering part of the driver &ndash; Which as a spoiler, is quite nice &ndash; but we still have to see some cool things along the way, for example next post I will dedicate the whole post to how <strong>WdFilter</strong> handles registry operations and there&rsquo;s some neat stuff going on there 😄.</p>

<p>If there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a></p>
]]></content></item><item><title>Dissecting the Windows Defender Driver - WdFilter (Part 2)</title><link>https://n4r1b.com/posts/2020/02/dissecting-the-windows-defender-driver-wdfilter-part-2/</link><pubDate>Thu, 06 Feb 2020 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2020/02/dissecting-the-windows-defender-driver-wdfilter-part-2/</guid><description>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how WdFilter gets initialized and how it handles the process creation throughout a process-creation callback. We also saw the ProcessCtx structure which will be used all over the driver to keep track of the different process running on the system. And now for this part, we will focus on the following things:
Image loading callback Thread creation callback Sending Sync/Async notifications Disclaimer: The callbacks I&amp;rsquo;ll explain in this post rely mainly on ProcessCtx.</description><content type="html"><![CDATA[

<p>Welcome back to Dissecting the Windows Defender Driver, in the previous part we saw how <strong>WdFilter</strong> gets initialized and how it handles the process creation throughout a process-creation callback. We also saw the <strong>ProcessCtx</strong> structure which will be used all over the driver to keep track of the different process running on the system. And now for this part, we will focus on the following things:</p>

<ul>
<li>Image loading callback</li>
<li>Thread creation callback</li>
<li>Sending Sync/Async notifications</li>
</ul>

<blockquote>
<p><strong>Disclaimer:</strong> The callbacks I&rsquo;ll explain in this post rely mainly on <code>ProcessCtx.ProcessRules</code> and as much as I&rsquo;ve tried with different type of process (Even malware) I haven&rsquo;t been able to determine to what type of process corresponds each rule (Maybe it has to do with the Windows Defender configuration)</p>

<p>I deeply apologize for not having this info, hopefully once I get further into the driver I will discover more about the different rules. Just for demonstration purpose, I&rsquo;ve forced the code to follow different paths.</p>
</blockquote>

<p>And after that disclaimer, let&rsquo;s get into it!</p>

<h3 id="mpcreatethreadnotifyroutineex-mpcreatethreadnotifyroutine">MpCreateThreadNotifyRoutineEx - MpCreateThreadNotifyRoutine</h3>

<p>The first two callbacks we will look are <code>MpCreateThreadNotifyRoutine</code> and <code>MpCreateThreadNotifyRoutineEx</code>, both of them are notified whenever a new thread is created or a thread is deleted. There&rsquo;s two different callbacks because the first one is registered using <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreatethreadnotifyroutine" target="_blank">PsSetCreateThreadNotifyRoutine</a> while the second one is registered using <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreatethreadnotifyroutineex" target="_blank">PsSetCreateThreadNotifyRoutineEx</a>, this function is available starting from Windows 10, and a pointer to it is saved in <strong>MpData</strong>, of course if the pointer is <code>NULL</code> this second callback won&rsquo;t be registered.</p>

<blockquote>
<p>As explained on the remark section from <code>PsSetCreateThreadNotifyRoutineEx</code> documentation this two functions differ in the context in which the callback is executed quoting MS documentation: <em>&ldquo;With PsSetCreateThreadNotifyRoutine, the callback is executed on the creator thread. With PsSetCreateThreadNotifyRoutineEx, the callback is executed on the newly created thread.&rdquo;</em></p>
</blockquote>

<h4 id="mpcreatethreadnotifyroutine">MpCreateThreadNotifyRoutine</h4>

<p>The code of the callbacks differ more than what you may expect, so we will study both. Starting with <code>MpCreateThreadNotifyRoutine</code> &ndash; Keep in mind this callback is executed in the context of the creator thread &ndash; this callback will check the following three things in order to execute:</p>

<ul>
<li>Create parameter is set to <code>TRUE</code></li>
<li>ProcessId is different than <code>0x4</code> (System)</li>
<li>Curren thread is not a system thread &ndash; <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-psissystemthread" target="_blank">!PsIsSystemThread</a></li>
</ul>

<p>In case this three conditions are met, the code will proceed to set a flag that indicates if the current process is the same as the one from the parameter ProcessId.</p>

<blockquote>
<p>A process could be creating a thread in another process, and since this callback executes in the context of the creator thread the current process would be the creator while the parameter ProcessId would be the one where the thread is going to execute.</p>
</blockquote>

<p>If they are the same then the current process <code>ProcessCtx.ProcessRules</code> will be tested against rule <strong>NotifyNewThreadSameProcess</strong> (<code>0x10000000</code>) and a flag will be set accordingly. In case the current process is not the same then the <code>ProcessRules</code> will be tested against rule <strong>NotifyNewThreadDifferentProcess</strong> (<code>0x400000</code>) and other flag will be set accordingly. If none of these flags is set then the callback will return &ndash; The following pseudocode shows this behavior in case my explanation is not clear enough</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">BOOLEAN SameProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
BOOLEAN NotifyNewThreadSameProcFlag <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;
BOOLEAN NotifyNewThreadDiffProcFlag <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;

<span style="color:#ff79c6">if</span> ( Create <span style="color:#ff79c6">&amp;&amp;</span> ProcessId <span style="color:#ff79c6">!=</span> <span style="color:#bd93f9">4</span> <span style="color:#ff79c6">&amp;&amp;</span> <span style="color:#ff79c6">!</span>PsIsSystemThread(KeGetCurrentThread()) ) {

    SameProcess <span style="color:#ff79c6">=</span> ProcessId <span style="color:#ff79c6">==</span> PsGetCurrentProcessId();
    <span style="color:#6272a4">// Retrieve the ProcessCtx by the ProcessId
</span><span style="color:#6272a4"></span>    MpGetProcessContextById(PsGetCurrentProcessId(), <span style="color:#ff79c6">&amp;</span>CurrentProcessCtx);

    <span style="color:#ff79c6">if</span> ( SameProcess <span style="color:#ff79c6">&amp;&amp;</span> CurrentProcessCtx<span style="color:#ff79c6">-&gt;</span>ProcessRules <span style="color:#ff79c6">&amp;</span> NotifyNewThreadSameProcess ) 
        NotifyNewThreadSameProcFlag <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
    <span style="color:#ff79c6">if</span> ( <span style="color:#ff79c6">!</span>SameProcess <span style="color:#ff79c6">&amp;&amp;</span> CurrentProcessCtx<span style="color:#ff79c6">-&gt;</span>ProcessRules <span style="color:#ff79c6">&amp;</span> NotifyNewThreadDifferentProcess )
        NotifyNewThreadDiffProcFlag <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;

    <span style="color:#ff79c6">if</span> ( <span style="color:#ff79c6">!</span>NotifyNewThreadSameProcFlag <span style="color:#ff79c6">&amp;&amp;</span> <span style="color:#ff79c6">!</span>NotifyNewThreadDiffProcFlag )
        <span style="color:#ff79c6">goto</span> Cleanup;
}</code></pre></div>
<p>In case one of the flags is set the code will proceed to obtain the structure I called <code>AuxPidCreationTime</code> &ndash; We saw in part 1, but as a remainder it contains de PID and the CreationTime of the process &ndash; after it has this structure for both process (Is obtained two times even if is the same process) the code will proceed to call <code>MpGetPriorityInfo</code>, this function will mainly call <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/fltkernel/nf-fltkernel-fltretrieveiopriorityinfo" target="_blank">FltRetrieveIoPriorityInfo</a> to get the <code>IO_PRIORITY_INFO</code> of the current thread and use this data to fill a structure I coined <code>MP_IO_PRIORITY</code>:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_IO_PRIORITY
{
    IO_PRIORITY_HINT IoPriority
    ULONG ThreadPriority  
    ULONG PagePriority    
} MP_IO_PRIORITY, <span style="color:#ff79c6">*</span>PMP_IO_PRIORITY;</code></pre></div>
<p>Different messages will be send to <strong>MsMpEng</strong> depending on the flag that was set. In the case of <strong>NotifyNewThreadDifferentProcess</strong>, <code>MpSendSyncMonitorNotification</code> will be called with <em>OperationType</em> equal to <strong>NewThreadDifferentProcess</strong> (<code>0x3</code>) and the <em>Data</em> will be the <code>AuxPidCreationTime</code> from the process that will execute the thread.</p>

<p><img src="/images/wdFilter/part2/NewThreadDifferentProcess.png" alt="alt image" title="Notify new thread different process" /></p>

<p>In the case the thread is being created in the same process, before calling <code>MpSendSyncMonitorNotification</code> the data that to send will be initialized, function <code>MpCreatePsThreadSyncMonitorData</code> is in charge of doing this. This function will basically fill the following structure:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ThreadNotifySyncMessage
{
  AuxTidCreationTime CreatedThread;
  AuxTidCreationTime CurrentThread;
  AuxPidCreationTime Process;
  INT64 Unk;
  PVOID ThreadStartAddress;
} ThreadNotifySyncMessage, <span style="color:#ff79c6">*</span>PThreadNotifySyncMessage;</code></pre></div>
<p>to get the value of the <strong>ThreadStartAddress</strong> it will open obtain a handle to the thread (<a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-pslookupthreadbythreadid" target="_blank">PsLookupThreadByThreadId</a>) and then using this handle it will call <a href="https://docs.microsoft.com/en-us/previous-versions/windows/hardware/drivers/mt629133(v%3Dvs.85)" target="_blank">ZwQueryInformationThread</a> with class <strong>ThreadQuerySetWin32StartAddress</strong>. Once <code>ThreadNotifySyncMessage</code> is filled, function <code>MpSendSyncMonitorNotification</code> will be called with this structure as the <em>Data</em> and <em>OperationType</em> equal to <strong>NewThreadSameProcess</strong> (<code>0x6</code>)</p>

<p><img src="/images/wdFilter/part2/NewThreadSameProcess.png" alt="alt image" title="Notify new thread same process" /></p>

<p>Lastly if <strong>NotifyNewThreadDifferentProcess</strong> is set the callback will execute one last step. This step will consist on sending an async notification with the following data</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ThreadNotifyMessage
{
  AuxPidCreationTime CurrentProcess;
  INT CurrentThreadId;
  AuxPidCreationTime CreatedThreadProcess;
  AuxTidCreationTime CreatedThread;
  WCHAR <span style="color:#ff79c6">*</span>ImageFileName;
} ThreadNotifyMessage, <span style="color:#ff79c6">*</span>PThreadNotifyMessage;</code></pre></div>
<p>Fields are pretty self-explanatory, in the case of the ImageFileName it will be retrieved from the <strong>ProcessCtx</strong> &ndash; In this case the <strong>ProcessCtx</strong> corresponds to the one from the thread creator process, which may not be the same as the one where the thread is going to run</p>

<p><img src="/images/wdFilter/part2/NewThreadAsyncMessage.png" alt="alt image" title="Async notification new thread" /></p>

<h4 id="mpcreatethreadnotifyroutineex">MpCreateThreadNotifyRoutineEx</h4>

<p>This routine is much simple than the previous one, in this case the function executes on the new thread, this basically means that the current process will always match the one indicated by the parameter ProcessId. First, in order to actually send the notification a lot of conditions must be met:</p>

<ul>
<li><code>MpProcessTable-&gt;CreateThreadNotifyLock</code> set to a value different than 0 (I know, lock is not the best name for this field, is locked when is zero 😆)</li>
<li>Create param set to <code>TRUE</code></li>
<li>Current process other than <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/mm64bitphysicaladdress" target="_blank">PsInitialSystemProcess</a></li>
<li>Flag <strong>ThreadNotifyRoutineExSet</strong> (<code>0x400</code>) set in <code>ProcessCtx.ProcessFlags</code></li>
<li>Rule <strong>NotifyProcessCmdLine</strong> (<code>0x20000000</code>) set in <code>ProcessCtx.ProcessRules</code></li>
</ul>

<p>As before, the following pseudocode explains this a bit better:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">if</span> ( _InterlockedCompareExchange(<span style="color:#ff79c6">&amp;</span>MpProcessTable<span style="color:#ff79c6">-&gt;</span>CreateThreadNotifyLock, <span style="color:#bd93f9">0</span>, <span style="color:#bd93f9">0</span>) 
    <span style="color:#ff79c6">&amp;&amp;</span> IoGetCurrentProcess() <span style="color:#ff79c6">!=</span> PsInitialSystemProcess <span style="color:#ff79c6">&amp;&amp;</span> Create ) {

    <span style="color:#6272a4">// Retrieve the ProcessCtx using the Process Object, in the end it will use
</span><span style="color:#6272a4"></span>    <span style="color:#6272a4">// the CreationTime (PsGetProcessCreateTimeQuadPart) and the ProcessId (PsGetProcessId)   
</span><span style="color:#6272a4"></span>    MpGetProcessContextByObject(IoGetCurrentProcess(), <span style="color:#ff79c6">&amp;</span>ProcessCtx)

    <span style="color:#6272a4">// Same as ((ProcessCtx-&gt;ProcessFlags &gt;&gt; 10) &amp; 1  &amp;&amp; (ProcessCtx-&gt;ProcessRules &gt;&gt; 0x1D) &amp; 1)
</span><span style="color:#6272a4"></span>    <span style="color:#ff79c6">if</span> ((ProcessCtx<span style="color:#ff79c6">-&gt;</span>ProcessFlags <span style="color:#ff79c6">&amp;</span> ThreadNotifyRoutineExSet) 
        <span style="color:#ff79c6">&amp;&amp;</span> (ProcessCtx<span style="color:#ff79c6">-&gt;</span>ProcessRules <span style="color:#ff79c6">&amp;</span> NotifyProcessCmdLine)) {
      .....
    }
}</code></pre></div>
<p>A couple of clarifications here, the flag <strong>ThreadNotifyRoutineExSet</strong> is set in every ProcessCtx if the pointer to <code>PsSetCreateThreadNotifyRoutineEx</code> is not NULL in the <code>MP_DATA</code>:</p>

<p><img src="/images/wdFilter/part2/ThreadNotifyExFlag.png" alt="alt image" title="Set ThreadNotifyRoutineFlag" /></p>

<p>in the case of the rule <strong>NotifyProcessCmdLine</strong>, comes from <strong>MsMpEng</strong> when setting the process info &ndash; Again, I haven&rsquo;t managed to trigger this rule with any process, so I don&rsquo;t really know to what kind of process does this rule apply, I apologize for this &ndash; So in the end of the process creation if this rule is set then the <code>MpProcessTable-&gt;CreateThreadNotifyLock</code> value will be incremented:</p>

<p><img src="/images/wdFilter/part2/ThreadNotifyLock.png" alt="alt image" title="Set CreateThreadNotifyLock" /></p>

<p>Getting back into the actual function, if all the conditions are met, then first thing is to decrement <code>CreateThreadNotifyLock</code> and remove the <strong>ThreadNotifyRoutineExSet</strong> from the ProcessCtx, once this is done, a handle to the Process Object will be obtained (<code>ObOpenObjectByPointer</code> with ObjectType as <em>PsProcessType</em>) this handle will be used in order to retrieve the Process CommandLine, inside <code>MpGetProcessCommandLineByHandle</code>, this function pretty much uses <code>ZwQueryInformationProcess</code> with ProcessInformationClass set to <em>ProcessCommandLineInformation</em>. This command line is going to be compared against the one inside <code>ProcessCtx-&gt;ProcessCmdLine</code>, in case they don&rsquo;t match then the function will get the <code>MP_IO_PRIORITY</code>, the <code>AuxPidCreationTime</code> and it will call <code>MpSendSyncMonitorNotification</code> with both Command Lines as the <em>Data</em>.</p>

<p><img src="/images/wdFilter/part2/TamperedCommandLine.png" alt="alt image" title="Tampered command line" /></p>

<blockquote>
<p>As seen on the image, if someone modifies the command line from the <code>PEB</code> this callback would notify <strong>MsMpEng</strong> of the tampered command line (Of course if the rules and flags for that ProcessCtx are set)</p>
</blockquote>

<h3 id="mploadimagenotifyroutine">MpLoadImageNotifyRoutine</h3>

<p><code>MpLoadImageNotifyRoutine</code> is the callback routine that gets triggered whenever an image is loaded or mapped into memory. In order to register this callback the driver uses the function <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetloadimagenotifyroutine" target="_blank">PsSetLoadImageNotifyRoutine</a>.</p>

<p>Getting into the actual callback code, first thing is to check if the image to be load is going to be mapped into user space or kernel space, checking the bit <code>Properties.SystemModeImage</code> inside the <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_image_info" target="_blank"><code>IMAGE_INFO</code></a>. In case it is a kernel-mode component the information of the image will be added to a <code>DRIVER_INFO</code> structure and then chained into the Loaded drivers list entry &ndash; Similar to the process creation adding boot process to the boot process list &ndash; this is done inside <code>MpAddDriverInfo</code>.</p>

<p>After this check, the <strong>ProcessCtx</strong> will be obtained and <code>ProcessCtx-&gt;ProcessRules</code> will be checked to see if <strong>NotifyWow64cpuLoad</strong> (<code>0x800</code>) is set. In case the rule is set, the function will proceed to compare the <em>FullImageName</em> byte by byte against the string <em>\Windows\System32\Wow64cpu.dll</em>. If they match the <code>ProcessCtx-&gt;ProcessFlags</code> will be OR&rsquo;ed with <strong>ImageWow64cpuLoaded</strong> (<code>0x200</code>) and the <em>ImageBase</em> will be written to <code>ProcessCtx-&gt;Wow64CpuImageBase</code> &ndash; If you remember first part of the series this field was named as <em>ImageBase</em>, I&rsquo;ve double-checked and this field is only set here in the whole code, that&rsquo;s why I renamed it.</p>

<p><img src="/images/wdFilter/part2/ProcessCtxWow64Cpu.png" alt="alt image" title="Process Context with Wow64cpu imagebase" /></p>

<p>From here on the main functionality of the routine starts &ndash; Just to make it clear, this point of the code is reached even if the <em>ImageName</em> don&rsquo;t match or the <strong>NotifyWow64cpuLoad</strong> is not set &ndash; this piece of code will first check if the <code>IMAGE_INFO</code> has the <em>ExtendedInfoPresent</em> bit set, if <em>ExtendedInfoPresent</em> is set then <code>IMAGE_INFO</code> is contained inside <code>IMAGE_INFO_EX</code> which keeps a pointer to the <em>FileObject</em>, this pointer will be used to retrieve a <strong>StreamContext</strong> (<code>MpGetStreamContextFromFileObject</code>) &ndash; Basically a structure defined by the minifilter that&rsquo;s associated to a Stream objects, we&rsquo;ll discuss this much more when we get to how the filtering works &ndash; with the <strong>StreamCtx</strong> and the <strong>ProcessCtx</strong> the following checks are done:</p>

<ul>
<li>If <code>StreamCtx-&gt;StreamCtxRules</code> has <strong>NotifyImageLoadRule</strong> (<code>0x8000</code>) active, then <strong>NotifyImageLoadPerStreamFlag</strong> is set.</li>
<li>If <code>ProcessCtx-&gt;ProcessRules</code> has <strong>NotifyImageLoadRule</strong> (<code>0x8000000</code>) active, then <strong>NotifyImageLoadPerProcessFlag</strong> is set.</li>
<li>If <code>ProcessCtx-&gt;ProcessRules</code> has <code>0x200</code> active (Haven&rsquo;t figured out this value yet), in case is not set then <strong>AsyncNotificationFlag</strong> is activated.</li>
</ul>

<p>If <strong>AsyncNotificationFlag</strong> is set the function will create an <code>AsyncMessageData</code> structure where the union <em>TypeOfMessage</em> will take the structure <code>ImageLoadAndProcessNotify</code>, we already saw this structure in the previous post, the main difference is that <code>AsyncMessageData-&gt;TypeOfOperation</code> will be set to <strong>LoadImage</strong> (<code>0x3</code>). Lastly the notification will be send by calling MpAsyncSendNotification.</p>

<p><img src="/images/wdFilter/part2/AsyncLoadImage.png" alt="alt image" title="Async load image notify" /></p>

<p>For the other two cases, the notification will be send synchronously, and the sent data will be the same for both cases. Only thing that differ will be the <em>OperationType</em> and the <em>Rule</em> &ndash; We&rsquo;ll discuss this params shortly when we look into how synchronous messages are sent.</p>

<ul>
<li><strong>NotifyImageLoadPerProcessFlag</strong> -&gt; <em>OperationType</em> = <strong>NewImageLoadPerProcess</strong> (<code>0x5</code>) and <em>Rule</em> = <code>ProcessCtx-&gt;ProcessRules</code></li>
<li><strong>NotifyImageLoadPerStreamFlag</strong> -&gt; <em>OperationType</em> = <strong>NewImageLoadPerStream</strong> (<code>0x1</code>) and <em>Rule</em> = <code>StreamCtx-&gt;StreamCtxRules</code></li>
</ul>

<p>Finally function <code>MpSendSyncMonitorNotification</code> is called with the parameter <em>Data</em> as a UNICODE_STRING with the normalized name <em>FullImageName</em> of the loaded image.</p>

<p><img src="/images/wdFilter/part2/SyncLoadImage.png" alt="alt image" title="Sync load image notify" /></p>

<p>One edge case where the code flow is a bit different is when <strong>ImageWow64cpuLoaded</strong> is set on the <code>ProcessCtx-&gt;ProcessFlags</code>. If this happens, then an <code>AsyncMessageData</code> structure of size 0x30 is allocated and the <em>TypeOfMessage</em> will contain the following structure:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _Wow64CpuLoadMessage
{
  INT ProcessId;
  INT ThreadId;
  PVOID Wow64CpuImageBase;
} Wow64CpuLoadMessage, <span style="color:#ff79c6">*</span>PWow64CpuLoadMessage;</code></pre></div>
<p>finally with <code>AsyncMessageData</code> populated the routine will call <code>FltSendMessage</code> &ndash; Fun fact, the <code>AsyncMessageData-&gt;SizeOfData</code> is set to <code>0x70</code> when actually the size of the structure is <code>0x30</code>, even parameter <em>SenderBufferLength</em> of <code>FltSendMessage</code> is set to <code>0x30</code>, this could lead to some potential error if <code>AsyncMessageData-&gt;SizeOfData</code> is used by <strong>MsMpEng</strong>.</p>

<p><img src="/images/wdFilter/part2/Wow64CpuLoadMessage.png" alt="alt image" title="Wow64Cpu load async notification" /></p>

<blockquote>
<p>So to explain a bit the flow, once <strong>Wow64cpu.dll</strong> is loaded this callback will set <strong>ImageWow64cpuLoaded</strong> in the <code>ProcessCtx-&gt;ProcessFlags</code> and will continue the execution through the main path. Next time this process loads an image, since <strong>ImageWow64cpuLoaded</strong> was previously set, the code will follow this path before taking the main path.</p>
</blockquote>

<h3 id="synchronous-notifications">Synchronous notifications</h3>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpSendSyncMonitorNotification</span>(
    MP_SYNC_NOTIFICATION OperationType, 
    PAuxPidCreationTime ProcessIdAndCreationTime, 
    PVOID Data, 
    PMP_IO_PRIORITY MpIoPriority,
    PULONG Rule
);

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">enum</span> _MP_SYNC_NOTIFICATION_OPERATION 
{
  NewImageLoadPerStream <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x1</span>,
  RegistryEventSync <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2</span>,
  NewThreadDifferentProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x3</span>,
  NewImageLoadPerProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x5</span>,
  NewThreadSameProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x6</span>,
  NewThreadProcessCmdLine <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x7</span>,
} MP_SYNC_NOTIFICATION_OPERATION;</code></pre></div>
</div>

<p><code>MpSendSyncMonitorNotification</code> is the one in charge of sending the synchronous messages through out the <strong>MicrosoftMalwareProtectionPort</strong>, in order for this function to execute the flag <strong>SyncMonitorNotificationFlag</strong> from the <code>MP_DATA</code> must be set. After this check has been done, the code will check if the <em>OperationType</em> is within the range of the <code>MP_SYNC_NOTIFICATION</code> enum, also it will check that none of the other parameters is <code>NULL</code>.</p>

<p>If every check is fulfilled, the code will proceed to obtain the size of the parameter <em>Data</em> &ndash; As we saw during the post, the data provided in this parameter differs on each type of operation &ndash; to do this the code uses the function <code>MpConstructSyncMonitorVariableData</code>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">ULONG MpConstructSyncMonitorVariableData(
  INT OperationType, 
  PVOID Data, 
  PVOID <span style="color:#ff79c6">*</span>__shifted(SyncMessageData,<span style="color:#bd93f9">0x30</span>) DataToSend, 
  ULONG SizeOfData
)</code></pre></div>
<p>this function can be used in two ways:</p>

<ul>
<li>To obtain the size of the data to send (<em>DataToSend</em> == <code>NULL</code>)</li>
<li>To fill te buffer that&rsquo;s going to be send using the data from the parameter <em>Data</em></li>
</ul>

<p>In the first case the pseudocode would look something like this:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>DataToSend) {
  <span style="color:#ff79c6">switch</span> (OperationType) {
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">NewImageLoadPerStream</span>:
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">NewImageLoadPerProcess</span>:
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">NewThreadAndCmdLine</span>:
      <span style="color:#ff79c6">return</span> (UNICODE_STRING <span style="color:#ff79c6">*</span>) Data<span style="color:#ff79c6">-&gt;</span>Length <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0xA</span>;
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">RegistryEventSync</span>:
      <span style="color:#ff79c6">return</span> (RegistryNotifySyncMessage) Data<span style="color:#ff79c6">-&gt;</span>RegDataLength;
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">NewThreadDifferentProcess</span>:
      <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">sizeof</span>(AuxPidCreationTime);
    <span style="color:#ff79c6">case</span> <span style="color:#8be9fd;font-style:italic">NewThreadSameProcess</span>:
      <span style="color:#ff79c6">return</span> <span style="color:#ff79c6">sizeof</span>(ThreadNotifySyncMessage);
  }
}</code></pre></div>
</div>

<p>getting back to the main function, after calling <code>MpConstructSyncMonitorVariableData</code> for the first time the code will obtain the size of the data to send, this size will be added to the size of the message header (<code>0x30</code>) and with the whole size a pool will be allocated and filled accordingly. The message header has the following definition</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _SyncMessageData
{
  SHORT Magic;      <span style="color:#6272a4">// Set to 0x5D 
</span><span style="color:#6272a4"></span>  SHORT SizeHeader; <span style="color:#6272a4">// Sizeof 0x30 
</span><span style="color:#6272a4"></span>  ULONG TotalSize;
  MP_IO_PRIORITY MpIoPriority;
  INT TypeOfOperation;
  AuxPidCreationTime CurrentProcess;
  INT SizeOfData;
  <span style="color:#ff79c6">union</span> SyncVariableData {
    WCHAR <span style="color:#ff79c6">*</span> NewThreadAndCmdLine;
    WCHAR <span style="color:#ff79c6">*</span> NewImageLoadPerStream;
    WCHAR <span style="color:#ff79c6">*</span> NewImageLoadPerProcess;
    RegistryNotifySyncMessage RegistryEventSync;
    AuxPidCreationTime NewThreadDifferentProcess;
    ThreadNotifySyncMessage NewThreadSameProcess;
  };
} SyncMessageData, <span style="color:#ff79c6">*</span>PSyncMessageData;</code></pre></div>
</div>

<p>lastly before sending the message the variable data has to be copied into the <code>SyncMessageData</code> structure, to do this <code>MpConstructSyncMonitorVariableData</code> is called again but this time the parameter <em>DataToSend</em> is pointing to the structure <code>SyncMessageData</code> shifted by <code>0x30</code> (Pointing to the variable data), in this case the function will just copy the data from the buffer <em>Data</em> to the buffer <em>DataToSend</em> &ndash; In case the buffer <em>Data</em> is a <code>UNICODE_STRING</code> the <code>UNICODE_STRING.Buffer</code> will be copied using <code>memcpy_s</code>.</p>

<p>At this point everything is ready to send the data to <strong>MsMpEng</strong>, just one more check needs to be done, inside <code>MpAcquireSendingSyncMonitorNotification</code> which will basically check that <code>MpData-&gt;SendSyncNotificationFlag</code> is active and after this the function will wait on <code>MpData-&gt;SendingSyncSemaphore</code> using <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/fltkernel/nf-fltkernel-fltcancellablewaitforsingleobject" target="_blank">FltCancellableWaitForSingleObject</a> &ndash; The timeout used for this wait comes from the variable <code>MpData-&gt;SyncMonitorNotificationTimeout</code> &ndash; in case the wait returns anything other than <code>STATUS_SUCCESS</code> the main function won&rsquo;t send any message and will increment and set accordingly the following two variables:</p>

<ul>
<li>MpData-&gt;ErrorSyncNotificationsCount[OperationType]</li>
<li>MpData-&gt;ErrorSyncNotificationsStatus[OperationType]</li>
</ul>

<p>In case the wait succeeds, <code>FltSendMessage</code> will be called and based on the returned status different variables will be filled. First variable is a structure that keeps a counter of the notifications and the total timestamp of them (For each <em>OperationType</em>). The structure array can be found in the variable <code>MpData-&gt;SyncNotifications[OperationType]</code> and the definition of it looks like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_SYNC_NOTIFICATIONS
{
  INT64 Timestamp;
  INT NotificationsCount;
} MP_SYNC_NOTIFICATIONS, <span style="color:#ff79c6">*</span>PMP_SYNC_NOTIFICATIONS;</code></pre></div>
<p>In case <code>FltSendMessage</code> returns an error the following variables will be updated:</p>

<ul>
<li>MpData-&gt;ErrorSyncNotificationsCount[OperationType]</li>
<li>MpData-&gt;ErrorSyncNotificationsStatus[OperationType]</li>
<li>MpData-&gt;SyncNotificationsIoTimeoutCount[OperationType] -&gt; Incremented just in case the returned status from <code>FltSendMessage</code> is <code>STATUS_TIMEOUT</code></li>
</ul>

<p>if <code>FltSendMessage</code> returned <code>STATUS_SUCCESS</code> then the function will proceed to check the reply buffer. This buffer should contain the same <em>OperationType</em> in offset <code>0x8</code> if this is the case then it will proceed to reset the <code>ProcessCtx-&gt;ProcessRules</code> or <code>StreamCtx-&gt;StreamCtxRule</code> that triggered this specific notification &ndash; It uses the parameter <em>Rule</em> &ndash; This can be seen in the following image:</p>

<p><img src="/images/wdFilter/part2/ResetRuleSwitch.png" alt="alt image" title="Switch to reset rule" /></p>

<blockquote>
<p>There are two more variables in this last step <code>MpData-&gt;SyncNotificationRecvCount[OperationType]</code> and <code>MpData-&gt;SyncNotificationsRecvErrorCount[OperationType]</code>. The latter is incremend in case the ReplyBuffer check doesn&rsquo;t match, the former in the other case.</p>
</blockquote>

<h3 id="asynchronous-notifications">Asynchronous Notifications</h3>

<p>In this section I will explain how does the driver handles sending the asynchronous notifications, there are two functions in charge of doing this. <code>MpAsyncSendNotification</code> which is in charge of adding the message to the async messages queue and <code>MpAsyncpWorkerThread</code> which is a worker thread checking the async messages queue and sending the messages if there are any.</p>

<h4 id="mpasyncpworkerthread">MpAsyncpWorkerThread</h4>

<p>In the first part of the series we already mention this worker thread. We saw that it is initialized, along with the async structure, inside <code>MpAsyncInitialize</code>. This function uses <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-pscreatesystemthread" target="_blank">PsCreateSystemThread</a> to create the worker thread, setting up <code>MpAsyncpWorkerThread</code> as the <em>StartRoutine</em> &ndash; No <em>StartContext</em> is passed into this new thread.</p>

<p>This thread will work mainly with the structure <code>MP_ASYNC</code>, this structure has the following definition (However much I tried to cross-reference this structure, I couldn&rsquo;t manage to get more fields for now. That&rsquo;s the main reason why I&rsquo;m missing many fields):</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_ASYNC
{
  SHORT Magic;      <span style="color:#6272a4">// Set to 0xDA07
</span><span style="color:#6272a4"></span>  SHORT StructSize; <span style="color:#6272a4">// Sizeof 0x180
</span><span style="color:#6272a4"></span>  LIST_ENTRY HighPriorityNotificationsList;
  LIST_ENTRY NotificationsList;
  PETHREAD WorkerThread;
  KEVENT AsyncNotificationEvent;
  KSEMAPHORE AsyncSemaphore;
  FAST_MUTEX AsyncFastMutex;
  INT NotificationsCount;
  INT64 field_A8;
  INT64 field_B0;
  INT64 field_B8;
  PAGED_LOOKASIDE_LIST NotificationsLookaside;
  INT64 TotalSizeNotificationsSent;
  INT64 TotalSizeRemainingNotifications;
  INT FailedNotifications;
  INT64 field_158;
  INT64 field_160;
  INT64 field_168;
  INT64 field_170;
  INT64 field_178;
} MP_ASYNC, <span style="color:#ff79c6">*</span>PMP_ASYNC;</code></pre></div>
</div>

<p>Once the worker thread starts executing it will enter an infinite loop waiting for two synchronization objects, <code>MpAsync-&gt;AsyncSemaphore</code> and <code>MpAsync-&gt;AsyncNotificationEvent</code>. In order to do this it uses <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-kewaitformultipleobjects" target="_blank">KeWaitForMultipleObjects</a></p>

<p><img src="/images/wdFilter/part2/KeWaitForMultipleObjects.png" alt="alt image" title="KeWaitForMultipleObjects" /></p>

<blockquote>
<p>I want to stop in this call and how is used for a second because I think is pretty cool, as we can see <em>WaitType</em> is set to <strong>WaitAny</strong> which means it will wait until any of the objects attains a signaled state. Also using <strong>WaitAny</strong> means that if the function returns <code>STATUS_SUCCESS</code>, it will actually return the zero-based index of the object as the <code>NTSTATUS</code>. Taking this into account, since the Event is set as the first element of the Objects array whenever the Event is signaled the returned value will be <code>STATUS_WAIT_0</code>, which corresponds to <code>0x0</code>. Which, again as seen in the image, would make the condition of the for-loop <code>FALSE</code> which would make the loop stop and the thread would terminate by calling <code>PsTerminateSystemThread</code>.</p>
</blockquote>

<p>In the case the semaphore is the signaled object, the thread will proceed to obtain the data that must be sent to <strong>MsMpEng</strong>. To do this, first the value <code>MpConfig.AsyncStarvationLimit</code> will be compared against the global variable <code>AsyncStarvationLimit</code> &ndash; If they are the same the global <code>AsyncStarvationLimit</code> will be set to <code>0x0</code> &ndash; In case they don&rsquo;t match, data will be searched on the <code>MpAsync-&gt;HighPriorityNotificationsList</code>, if any entry is found in the <code>LIST_ENTRY</code> then <code>AsyncStarvationLimit</code> will be incremented by one. If no entries are found then <code>MpAsync-&gt;NotificationsList</code> will be checked and if an entry is found <code>AsyncStarvationLimit</code> is clear. In case the starvation limit is reached the list entries will be checked in reverse order, first the normal priority then the higher. The following pseudo-horrible-code shows this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">if</span> (MpConfig.AsyncStarvationLimit <span style="color:#ff79c6">==</span> _InterlockedCompareExchange(
                                        <span style="color:#ff79c6">&amp;</span>AsyncStarvationLimit,
                                        <span style="color:#bd93f9">0</span>,
                                        MpConfig.AsyncStarvationLimit)) {
  <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">&amp;</span>MpAsync<span style="color:#ff79c6">-&gt;</span>NotificationsList <span style="color:#ff79c6">!=</span> MpAsync<span style="color:#ff79c6">-&gt;</span>NotificationsList.Flink)
    <span style="color:#ff79c6">goto</span> SendMessage;

  <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">&amp;</span>MpAsync<span style="color:#ff79c6">-&gt;</span>HighPriorityNotificationsList <span style="color:#ff79c6">!=</span> MpAsync<span style="color:#ff79c6">-&gt;</span>HighPriorityNotificationsList.Flink) {
<span style="color:#8be9fd;font-style:italic">IncrementLimit</span>:
    _InterlockedAdd(<span style="color:#ff79c6">&amp;</span>AsyncStarvationLimit, <span style="color:#bd93f9">1</span>);
    <span style="color:#ff79c6">goto</span> SendMessage
  }
}

<span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">&amp;</span>MpAsync<span style="color:#ff79c6">-&gt;</span>HighPriorityNotificationsList <span style="color:#ff79c6">!=</span> MpAsync<span style="color:#ff79c6">-&gt;</span>HighPriorityNotificationsList.Flink)
  <span style="color:#ff79c6">goto</span> IncrementLimit

<span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">&amp;</span>MpAsync<span style="color:#ff79c6">-&gt;</span>NotificationsList <span style="color:#ff79c6">!=</span> MpAsync<span style="color:#ff79c6">-&gt;</span>NotificationsList.Flink) {
  _InterlockedCompareExchange(<span style="color:#ff79c6">&amp;</span>AsyncStarvationLimit, <span style="color:#bd93f9">0</span>, AsyncStarvationLimit); <span style="color:#6272a4">// Atomic set to 0
</span><span style="color:#6272a4"></span>  <span style="color:#ff79c6">goto</span> SendMessage;
}</code></pre></div>
<blockquote>
<p>As you can see, messages from <code>MpAsync-&gt;HighPriorityNotificationsList</code> have a higher priority because this <code>LIST_ENTRY</code> will be checked first unless the starvation limit is reached</p>
</blockquote>

<p>The next part is pretty straightforward, if an entry is found in any of the two list entries then the following steps will take part:</p>

<ul>
<li>Decrement <code>MpAsync-&gt;NotificationsCount</code></li>
<li>Subtract the data size from <code>MpAsync-&gt;TotalSizeRemainingNotifications</code></li>
<li>Set the <em>Magic</em> and <em>Size</em> of <code>MP_ASYNC_NOTIFICATION</code> (We will see this structure shortly) to <code>0xBABAFAFA</code></li>
<li>Push or free, in case the max depth has been reached, the <code>MP_ASYNC_NOTIFICATION</code> entry to the lookaside <code>MpAsync-&gt;AsyncNotificationsLookaside</code></li>
<li>Send the actual message using <code>FltSendMessage</code></li>
<li>In case of error increment <code>MpAsync-&gt;FailedNotifications</code></li>
<li>Add the data size to <code>MpAsync-&gt;TotalSizeNotificationsSent</code></li>
</ul>

<p><img src="/images/wdFilter/part2/AsyncFltSendMessage.png" alt="alt image" title="Async notification FltSendMessage" /></p>

<p>And after that the thread would iterate again over the for-loop waiting for any of the two objects to be signaled.</p>

<blockquote>
<p>Just to complete the full circle on this worker thread, function <code>MpAsyncpShutdownWorkerThreads</code> is the one that calls <code>KeSetEvent</code> with <code>MpAsync-&gt;AsyncNotificationEvent</code> as the event to signal, which as we saw before would end the loop and terminate the thread. This function is called from within <code>MpAsyncShutdown</code> which is in charge of cleaning all related to async notifications.</p>
</blockquote>

<h4 id="mpasyncsendnotification">MpAsyncSendNotification</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpAsyncSendNotification</span>(
  PVOID <span style="color:#ff79c6">*</span>__shifted(AsyncMessageData,<span style="color:#bd93f9">8</span>) AsyncMessageBuffer,
  ULONG SizeOfBuffer, 
  INT PriorityFlag, 
  PProcessCtx ProcessCtx
);</code></pre></div>
<p>We&rsquo;ve already seen a couple of cases where the code will create a <strong>AsyncMessageData</strong> structure and populate it with the data that&rsquo;s going to be send afterwards to <strong>MsMpEng</strong>. We just saw how this data is sent, now we are going to see how this data is added to the previously seen list entries.</p>

<p>The function in charge of this is <code>MpAsyncSendNotification</code>, which will first do a sanity check on <em>AsyncMessageBuffer</em> and <em>SizeOfBuffer</em>. If checks are fulfilled function will test if the <code>SenderBuffer-&gt;TypeOfOperation</code> is less than <code>0xA</code>, if it&rsquo;s the case, the value <code>MpData-&gt;AsyncNotificationCount</code> will be incremented and assigned to <code>SenderBuffer-&gt;NotificationNumber</code> &ndash; The Possible values of <em>TypeOfOperation</em> are the following:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">enum</span> _MP_ASYNC_NOTIFICATION_OPERATION
{
  CreateProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x0</span>, 
  RegistryEvent <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x1</span>,
  SendFile <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x2</span>,
  LoadImage <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x3</span>,
  OpenProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x4</span>,
  RawVolumeWrite <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x5</span>, <span style="color:#6272a4">// High-Priority
</span><span style="color:#6272a4"></span>  CreateThread <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x6</span>,
  DocOpen <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x7</span>,
  PostMount <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x8</span>, <span style="color:#6272a4">// High-Priority
</span><span style="color:#6272a4"></span>  OpenDesktop <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x9</span>,
  PanicMode <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xB</span>,
  CheckJournal <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xC</span>, <span style="color:#6272a4">// High-Priority
</span><span style="color:#6272a4"></span>  TrustedOrUntrustedProcess <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xD</span>, <span style="color:#6272a4">// High-Priority
</span><span style="color:#6272a4"></span>  LogPrint <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xE</span>,
  Wow64cpuLoad <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xF</span>,
  OpenWithoutRead <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x10</span>,
  FolderGuardEvents <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x11</span>,
  DlpOnFileObjectClose <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x13</span>,
} MP_ASYNC_NOTIFICATION_OPERATION;</code></pre></div>
</div>

<p>next step is to increment the <code>ProcessCtx-&gt;NotificationsSent</code> &ndash; If there is a <em>ProcessCtx</em> &ndash; once this is done an entry from <code>MpAsync-&gt;AsyncNotificationsLookaside</code> will be popped or allocated and the following structure will be initialized in that buffer:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_ASYNC_NOTIFICATION
{
  SHORT Magic;        <span style="color:#6272a4">// Set to 0xDA08
</span><span style="color:#6272a4"></span>  SHORT StructSize;   <span style="color:#6272a4">// Sizeof 0x18 - Header Size
</span><span style="color:#6272a4"></span>  LIST_ENTRY AsyncNotificationsList;
  PVOID <span style="color:#ff79c6">*</span><span style="color:#50fa7b">__shifted</span>(AsyncMessageData,<span style="color:#bd93f9">8</span>) pMessageBuffer;
  INT MessageBufferSize;
} MP_ASYNC_NOTIFICATION, <span style="color:#ff79c6">*</span>PMP_ASYNC_NOTIFICATION;</code></pre></div>
<p>Once this structure is initialized there&rsquo;s tow possible paths, first path in case <code>MpAsync-&gt;NotificationsCount</code> is less than <code>MpConfig.MaxAsyncNotificationCount</code>. In this case, the initialized structure will be inserted at the end of <code>MpAsync-&gt;HighPriorityNotificationsList</code> or <code>MpAsync-&gt;NotificationsList</code> based on the <em>PriorityFlag</em> &ndash; If is set then is chained to the former, in the other case to the latter &ndash; then <code>MpAsync-&gt;NotificationsCount</code> is incremented, <em>MessageBufferSize</em> is added to <code>MpAsync-&gt;TotalSizeRemainingNotifications</code> and lastly the semaphore is signaled &ndash; <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-kereleasesemaphore" target="_blank">KeReleaseSemaphore</a></p>

<p><img src="/images/wdFilter/part2/AsyncNotificationBeforeSignal.png" alt="alt image" title="Async notification list entries before signal" /></p>

<p>The second path is taken when <code>MpAsync-&gt;NotificationsCount</code> is greater or equal to <code>MpConfig.MaxAsyncNotificationCount</code>, if this happens then the first entry of <code>MpAsync-&gt;HighPriorityNotificationsList</code> or <code>MpAsync-&gt;NotificationsList</code> (Again based on the <em>PriorityFlag</em>) will be unchained from the <code>LIST_ENTRY</code> and the newly created entry will be inserted at the end of it. Before finishing, as we saw in the worker thread, the function will increment <code>MpAsync-&gt;AsyncMessagesFailed</code> and push/free the unchained entry to/from the lookaside list (After setting the first bytes to <code>0xBABAFAFA</code>)</p>

<blockquote>
<p>This is basically to make sure there will be enough resources to allocate a pool from the lookaside list in case a new notification must be created, also this makes sure the newer notifications are the ones kept on the <code>LIST_ENTRY</code> in case the worker thread is not getting enough execution time to free the notifications list</p>
</blockquote>

<h3 id="conclusion">Conclusion</h3>

<p>And that&rsquo;s all for this part folks! Sorry again for the long post but I&rsquo;m trying to explain and clarify as much as possible &ndash; And even with theses long posts I&rsquo;m leaving some stuff out &ndash; This part was a bit messy, not being able to know which process or options trigger some paths makes things a bit harder. Anyway, I hope you guys liked and still want to keep reading the series! This is just the tip of the iceberg!! On the next post we&rsquo;ll look into the registered callback for objects (<em>PsProcessType</em> and <em>ExDesktopObjectType</em>) and also we will look into how drivers information is saved and how their verification is done.</p>

<p>If there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a></p>
]]></content></item><item><title>Dissecting the Windows Defender Driver - WdFilter (Part 1)</title><link>https://n4r1b.com/posts/2020/01/dissecting-the-windows-defender-driver-wdfilter-part-1/</link><pubDate>Wed, 29 Jan 2020 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2020/01/dissecting-the-windows-defender-driver-wdfilter-part-1/</guid><description>I&amp;rsquo;m back again! For the next couple (Or maybe more) posts I&amp;rsquo;ll be explaining how WdFilter works. I&amp;rsquo;ve always been very interested on how AVs work (Nowadays I would say EDRs though) and their development at kernel level. And since, unfortunately I don&amp;rsquo;t have access to the source code of any, my only chance is to reverse them (Or to write my own 😆). And of course what a better product to check than the one written by the company who developed the OS.</description><content type="html"><![CDATA[

<p>I&rsquo;m back again! For the next couple (Or maybe more) posts I&rsquo;ll be explaining how WdFilter works. I&rsquo;ve always been very interested on how AVs work (Nowadays I would say EDRs though) and their development at kernel level. And since, unfortunately I don&rsquo;t have access to the source code of any, my only chance is to reverse them (Or to write my own 😆). And of course what a better product to check than the one written by the company who developed the OS.</p>

<p>For those who don&rsquo;t know, WdFilter is the main kernel component of Windows Defender. Roughly, this Driver works as a Minifilter from the load order group &ldquo;FSFilter Anti-Virus&rdquo;, this means that is attached to the File System stack (Actually, quite high - Big Altitude) and handles I/O operations in some Pre/Post callbacks. Not only that, this driver also implements other techniques to get information of what&rsquo;s going on in the system. The goal of this series of post is to have a solid understanding on how this works under the hood.</p>

<blockquote>
<p>A couple of remarks before moving forward. I&rsquo;ll try to put together all the posts in a way that it makes sense, but since there are many components, flags and structures involved in many places some things may not be clear at first. Also since I&rsquo;m still working on reversing the driver so I apologize in advance for not having all the structures fully reversed and same applies to flags I&rsquo;ll try to post some header files on my Github and keep them updated :)</p>
</blockquote>

<h1 id="initialization">Initialization</h1>

<blockquote>
<p>For this research I&rsquo;m looking at <strong>WdFilter</strong> version 4.18.1910.4, <strong>WdFilter</strong> gets updated a lot, thou changes are not huge so this research should be at least of some help for future versions :)</p>

<p>SHA256: <code>52D2A7A085896AC8A4FF92201FC87587EDF86B930825840974C6BC09BFB27E5B</code></p>
</blockquote>

<p>So without further ado, let&rsquo;s get into the <code>DriverEntry</code>. As we saw with <strong>WdBoot</strong> first steps are to check if running on <code>SafeBootMode</code> and initialize the WPP tracing. With this behind, we get into the allocation of the main structure, <strong>MpData</strong>. In the version of the driver we are studying it has a size of <code>0xCC0</code> bytes and is allocated in a NonPaged Pool with tag <code>MPfd</code>. Once we have the Pool allocated for the structure the code will proceed to call <code>MpInitializeGlobals</code> which will initialize some structures inside <strong>MpData</strong> (PagedLookasideLists, EResources, Timer among others) also this function will be in charge of computing a mask which determines the OS version running on the system, this can be seen in the following image &ndash; <code>MpVerifyWindowsVersion</code> receives the MajorVersion, MinorVersion, ServicePack and BuildNumber and end up calling <code>RtlVerifyVersionInfo</code> to verify if the running OS version is higher.</p>

<p><img src="/images/wdFilter/part1/OsVersion.png" alt="alt image" title="OS Version Mask" /></p>

<p>Also inside this function some pointers to function will be obtained, specifically inside <code>MpGetSystemRoutines</code>, this function will use <code>MmGetSystemRoutineAddress</code> and save the returned address into <strong>MpData</strong>. &ndash; The <em>OsVersionMask</em> field comes into play here, because some pointers will only be obtained in certain OS versions, for example <code>FltRequestFileInfoOnCreateCompletion</code> will only be retrieved if running Windows 10 build 17726 or higher &ndash; Going back to the initialization function, one last thing it will do is to create the following SIDs:</p>

<ul>
<li>MpServiceSID</li>
<li>NriServiceSID</li>
<li>TrustedInstallerSID</li>
</ul>

<p>After this, the initialization of <strong>MpData</strong> is completed, even though there&rsquo;s still plenty of members that will be filled in other functions, here you can see this <strong>Huge</strong> structure &ndash; Still missing <strong>A LOT</strong> of fields.</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DATA
{
  SHORT Magic;      <span style="color:#6272a4">// Set to 0xDA00
</span><span style="color:#6272a4"></span>  SHORT StructSize; <span style="color:#6272a4">// Sizeof 0xCC0
</span><span style="color:#6272a4"></span>  PDRIVER_OBJECT pDriverObject;
  PFLT_FILTER MpFilter;
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pPsSetCreateProcessNotifyRoutineEx)(PCREATE_PROCESS_NOTIFY_ROUTINE_EX, BOOLEAN);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pPsSetCreateProcessNotifyRoutineEx2)(PSCREATEPROCESSNOTIFYTYPE, PVOID, BOOLEAN);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pPsSetCreateThreadNotifyRoutineEx)(PSCREATETHREADNOTIFYTYPE, PVOID);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pObRegisterCallbacks)(POB_CALLBACK_REGISTRATION, PVOID <span style="color:#ff79c6">*</span>);
  <span style="color:#8be9fd">void</span> (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pObUnRegisterCallbacks)(PVOID);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFltRegisterForDataScan)(<span style="color:#ff79c6">const</span> PFLT_INSTANCE);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFltCreateSectionForDataScan)(PFLT_INSTANCE Instance, PFILE_OBJECT FileObject, PFLT_CONTEXT SectionContext, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PLARGE_INTEGER MaximumSize, ULONG SectionPageProtection, ULONG AllocationAttributes, ULONG Flags, PHANDLE SectionHandle, PVOID <span style="color:#ff79c6">*</span>SectionObject, PLARGE_INTEGER SectionFileSize);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFltCloseSectionForDataScan)(PFLT_CONTEXT);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFltRequestFileInfoOnCreateCompletion)(PFLT_FILTER, PFLT_CALLBACK_DATA, ULONG);
  PVOID (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFltRetrieveFileInfoOnCreateCompletion)(PFLT_FILTER Filter, PFLT_CALLBACK_DATA Data, ULONG InfoClass, PULONG Size);
  NTSTATUS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pFsRtlQueryCachedVdl)(PFILE_OBJECT FileObject, PLONGLONG Vdl);
  PVOID pIoBoostThreadIo;
  PVOID pKeSetActualBasePriorityThread;
  PVOID pSeGetCachedSigningLevel;
  PIO_FOEXT_SILO_PARAMETERS (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pIoGetSiloParameters)(<span style="color:#ff79c6">const</span> PFILE_OBJECT);
  BYTE field_90;
  BYTE PanicModeFlag;
  BYTE field_92;
  BYTE field_93;
  INT ScannedFilesCount;
  INT field_98;
  INT field_9C;
  PEPROCESS MsMpEngProcess;
  HANDLE MsMpEngProcessId;
  INT ConnectionPortCookieSet;
  PFLT_PORT FltProtectionControlPort;
  PFLT_PORT ProtectionControlPortServerCookie;
  PFLT_PORT FltProtectionPort;
  PFLT_PORT ProtectionPortServerCookie;
  PFLT_PORT FltProtectionVeryLowIoPort;
  PFLT_PORT ProtectionVeryLowIoServerCookie;
  PFLT_PORT FltProtectionRemoteIoPort;
  PFLT_PORT ProtectionRemoteIoServerCookie;
  PFLT_PORT FltProtectionAsyncPort;
  PFLT_PORT ProtectionAsyncServerCookie;
  INT SomeScanFileFlag;
  INT SendSyncNotificationFlag;
  KSEMAPHORE ScanFileSemaphore1;
  KSEMAPHORE ScanFileSempahore2;
  KSEMAPHORE SendingSyncSemaphore;
  PVOID pBootSectorCache;
  LIST_ENTRY FltInstanceCtxList;
  LIST_ENTRY FltStreamCtxList;
  PCWSTR RegistryParametersPath;
  BYTE DriverVerifiedFlag;
  BYTE field_1A1;
  BYTE field_1A2;
  BYTE field_1A3;
  INT VerifyDriverLevelValue;
  INT64 ResetTimer;
  INT FileScanConsecutiveTimeoutsCount;
  INT field_1B4;
  KDPC WdFilterDPC;
  KTIMER WdFilterTimer;
  ERESOURCE MpDataResource;
  INT64 AsyncNotificationCount;
  INT OsVersionMask;
  INT MonitorFlags;
  INT64 field_2B0;
  INT64 field_2B8;
  PAGED_LOOKASIDE_LIST CompletionContextLookaside;
  NPAGED_LOOKASIDE_LIST WriteContextLookaside;
  NPAGED_LOOKASIDE_LIST field_3C0;
  PAGED_LOOKASIDE_LIST InstanceContextLookaside;
  PAGED_LOOKASIDE_LIST FltInputMessagesLookaside;
  PAGED_LOOKASIDE_LIST FltOutputMessagesLookaside;
  ULONG MpFilterEcpSize;
  INT64 field_5C8;
  INT64 field_5D0;
  INT64 field_5D8;
  INT64 field_5E0;
  INT64 field_5E8;
  INT64 field_5F0;
  INT64 field_5F8;
  NPAGED_LOOKASIDE_LIST ExtraCreateParamsLookaside;
  PVOID ObRegistrationHandle;
  PSID MpServiceSID;
  PSID NriServiceSID;
  PSID TrustedInstallerSID;
  INT MaxLocalScanTimeout;
  INT MaxNetworkScanTimeout;
  INT field_6A8;
  INT UnsetObAndRegCallback;
  BYTE RawVolumeWriteFlag;
  BYTE MpOrWdFlag;
  BYTE field_6B2;
  BYTE field_6B3;
  INT field_6B4;
  PVOID PowerSettingCbHandle;
  BYTE LowPowerEpochOn;
  BYTE field_6C1;
  BYTE field_6C2;
  BYTE field_6C3;
  <span style="color:#8be9fd">int</span> field_6C4;
  INT64 MachineUptime;
  MP_CSRSS_HOOK_DATA <span style="color:#ff79c6">*</span>pCsrssHookData;
  PCALLBACK_OBJECT pProcessNotificationCallback;
  PCALLBACK_OBJECT pNriNotificationCallback;
  INT64 NriNotificationCallbackHandle;
  INT64 field_6F0;
  INT64 field_6F8;
  LIST_ENTRY field_700;
  FAST_MUTEX MpDataFastMutex;
  INT64 field_748;
  INT64 field_750;
  INT64 field_758;
  INT64 field_760;
  INT64 field_768;
  INT64 field_770;
  INT64 field_778;
  PAGED_LOOKASIDE_LIST PagedLookasideMPbc;
  INT field_800;
  INT field_804;
  INT64 field_808;
  INT64 field_810;
  INT64 field_818;
  INT64 field_820;
  INT64 field_828;
  INT64 field_830;
  INT64 field_838;
  INT64 field_840;
  INT64 field_848;
  INT64 field_850;
  INT64 field_858;
  INT64 field_860;
  INT CsvFileStateCacheType;
  INT FileStateCachePolicy;
  INT64 field_870;
  INT field_878;
  INT field_87C;
  INT CounterFileSystemTypeCSVFS;
  INT field_884;
  INT field_888;
  INT RefsFileStateCacheType;
  INT FileStateCachePolicy1;
  INT64 field_898;
  INT field_8A0;
  INT field_8A4;
  INT CounterFileSystemTypeREFS;
  INT field_8AC;
  INT field_8B0;
  INT64 FltSendMessageTimeStamp;
  INT FltSendMessageCount;
  INT field_8C4;
  INT SomethingWithSettingProcessInfo;
  INT FltSendMessageError;
  INT FltSendMessageErrorCode;
  INT FltSendMessageStatusTimeout;
  INT FltSendMessageReplyBufferMismatch;
  INT AllowFilterManualDetach;
  LIST_ENTRY BootScanCtxList;
  ERESOURCE ExResource1;
  ERESOURCE ExResource2;
  INT field_9C0;
  INT field_9C4;
  PUNICODE_STRING SystemRootPath;
  INT field_9D0;
  INT field_9D4;
  BYTE OpenWithoutReadNotificationFlag;
  RTL_GENERIC_TABLE RtlGenericTable;
  FAST_MUTEX WdFilterGenericTableMutex;
  MP_SYNC_NOTIFICATIONS_STATUS SyncNotifications[<span style="color:#bd93f9">8</span>];
  INT SyncNotificationRecvCount[<span style="color:#bd93f9">8</span>];
  INT SyncNotificationsCount[<span style="color:#bd93f9">8</span>];
  INT SyncNotificationsStatus[<span style="color:#bd93f9">8</span>];
  INT SyncNotificationsIoTimeoutCount[<span style="color:#bd93f9">8</span>];
  INT SyncNotificationsRecvErrorCount[<span style="color:#bd93f9">8</span>];
  INT MonitorNotificationFlag;
  INT field_B84;
  INT64 SyncMonitorNotificationTimeout;
  INT64 RandNumber;
  BYTE MpEaString[<span style="color:#bd93f9">256</span>];
  INT AsyncDirectoryNotificationFlag;
  BYTE DataLossPreventionFlag;
  BYTE field_C9D;
  BYTE field_C9E;
  BYTE field_C9F;
  INT64 field_CA0;
  INT64 field_CA8;
  INT64 field_CB0;
  INT64 field_CB8;
} MP_DATA, <span style="color:#ff79c6">*</span>PMP_DATA;</code></pre></div>
</div>

<p>Next step is to setup the parameters/config of the the driver, this will be done inside <code>MpLoadRegistryParameters</code>. This function will setup a <code>RTL_REGISTRY_QUERY_TABLE</code> by iterating over an array of structures that I coined <code>MP_CONFIG_PARAMS</code>:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_CONFIG_PARAMS
{
  PCWSTR Name;
  PMP_CONFIG <span style="color:#ff79c6">*</span>pMpConfig;
  INT64 DefaultData;
} MP_CONFIG_PARAMS, <span style="color:#ff79c6">*</span>PMP_CONFIG_PARAMS</code></pre></div>
</div>

<p>the following image shows some entries of this array:</p>

<p><img src="/images/wdFilter/part1/MpConfigParams.png" alt="alt image" title="MP_CONFIG_PARAMS array" /></p>

<p>As you can see the second member of this structure is a pointer inside the structure <code>MP_CONFIG</code>, this address is the one that&rsquo;s gonna be set as the <code>EntryContext</code> in the <code>QueryTable</code>. Finally, the function will call <code>RtlQueryRegistryValuesEx</code> with the registry path being <code>HKLM\System\CurrentControlSet\Services\WdFilter\Parameters</code> after this call has been made the values returned in the <code>EntryContext</code> will be check to see if they match some criteria, if they don&rsquo;t match they will be set to their default value. The <code>MP_CONFIG</code> has the following definition:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// Sizeof 0x5C
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_CONFIG
{
  INT   ResetToUnknownTimer;
  INT   MaxLocalScanTimeout;
  INT   MaxNetworkScanTimeout;
  INT   MaxProcessCreationMessageTimeout;
  INT   MaxConsecutiveTimeoutsUntilPassThrough;
  INT   StartScanningAgainTimer;
  INT   DebugPassthroughEnabled;
  INT   MaxAsyncNotificationCount;
  INT   AsyncStarvationLimit;
  INT   AsyncTimeout;
  INT   AllowManualDetach;
  INT   MaxCopyCacheSize;
  INT   KnownBadHashSize;
  BYTE  DirectionalScanningNonNTFS;
  BYTE  DisableQueryNameNormalize;
  BYTE  ThreadBoostingFlag;
  INT   CsvFileStateCacheType;
  INT   RefsFileStateCacheType;
  INT   FileStateCachePolicy;
  INT   DisableReadHooking;
  INT   FolderGuardDispatchTimer;
  INT   FolderGuardDispatchLimit;
  INT   DisableTransactionCallback;
} MP_CONFIG, <span style="color:#ff79c6">*</span>PMP_CONFIG;</code></pre></div>
</div>

<p>With the <strong>MpConfig</strong> structure populated, some default values will be copied into <strong>MpData</strong> inside <code>MpSetDefaultConfigs</code>, then function <code>MpSetBufferLimits</code> will set the different limits both for Input and Output messages that will be used for the communication with the UserSpace process &ndash; <strong>MsMpEng.exe</strong>.</p>

<blockquote>
<p>I will leave how this communication works for another post, since is a big part of the driver and I believe it deserves it&rsquo;s own part. But basically the driver can receive different messages through a communication port and each of this message has his own data and size, and of course, each one executes a different operation.</p>
</blockquote>

<p>Last thing regarding initialization of <strong>MpData</strong> is to initialize things related to thread boosting, this will be done inside <code>MpInitializeBoostManager</code>, for now is not relevant we will see more about this thread boosting in other posts.</p>

<p>From now on, the code will start initializing <strong>a lot</strong> of different structures, each one meant for something different, I&rsquo;ll mention all of them but for this post I&rsquo;ll focus only on some of them. First function is <code>MpInitializeProcessTable</code>, as the name implies this function will initialize a structure that will keep track of the process in the system, to do this it will allocate a pool of size <code>0x800</code> that will contain an array of <code>LIST_ENTRY</code> &ndash; Each list entry is of size <code>0x10</code> so we have <code>0x80</code> entries in the array &ndash; this <code>LIST_ENTRY</code> is actually a shifted pointer into the structure I named <code>ProcessCtx</code> that contains the information regarding a process. The definition of the process table looks something like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_PROCESS_TABLE
{
  SHORT Magic;  <span style="color:#6272a4">// Set to 0xDA13
</span><span style="color:#6272a4"></span>  SHORT Size;   <span style="color:#6272a4">// Sizeof 0x1C0
</span><span style="color:#6272a4"></span>  ERESOURCE ProcessTableResource;
  PAGED_LOOKASIDE_LIST ProcessCtxLookaside;
  PAGED_LOOKASIDE_LIST ProcessCtxListLookaside;
  LIST_ENTRY <span style="color:#ff79c6">*</span><span style="color:#50fa7b">__shifted</span>(ProcessCtx,<span style="color:#bd93f9">8</span>) (<span style="color:#ff79c6">*</span>ProcessCtxArray)[<span style="color:#bd93f9">0x80</span>];
  KEVENT ProcessTableEvent;
  _DWORD BeingAccessed;
  INT TrustedProcessCtxCounter;
  INT UntrustedProcessCtxCounter;
  INT Unk;
  INT CreateThreadNotifyLock;
} MP_PROCESS_TABLE, <span style="color:#ff79c6">*</span>PMP_PROCESS_TABLE;</code></pre></div>
<p>After this, the <code>DriverEntry</code> will call <code>MpInitBootSectorCache</code> which will allocate a pool of size <code>0x64</code> and tag <code>MPgb</code> and save a pointer in <code>MpData-&gt;pBootSectorCache</code> &ndash; We&rsquo;ll see more about the checks of the Boot sector in another post.</p>

<p>Then, based on the value saved on <code>MpConfig.MaxCopyCacheSize</code> another pool will be allocated and this time the pointer to the pool will be saved in the global variable <code>MpCopyCacheData</code> &ndash; The value of <code>MaxCopyCacheSize</code> cannot be higher than <code>0x200</code> and in order to allocate the pool this value is left shifted 6 times, so the max size would be <code>0x8000</code> &ndash; With this done, the next step is to initialize the following strucures and callbacks:</p>

<ul>
<li><p>Process Exclusion structure, initialized inside <code>MpInitializeProcessExclusions</code> with a size of <code>0x78</code>, tag <code>MPps</code> and saved in the global <code>MpProcessExclusion</code>.</p></li>

<li><p>Power setting callback, this is done inside <code>MpPowerStatusInitialize</code>, which receives as parameter the address of <code>MpData-&gt;PowerSettingCbHandle</code> and this function will use <code>PoRegisterPowerSettingCallback</code> to set up a callback on the power setting <code>GUID_LOW_POWER_EPOCH</code> upon successful registration of the callback the Handle will be saved in the parameter &ndash; We will see the actual callback function in the end of this article.</p></li>

<li><p>The transactional NTFS structure, which will be initialized inside <code>MpTxfInitialize</code> with a size of <code>0x140</code>, tag <code>MPtd</code> and saved in a global I named <code>MpTxfData</code>.</p></li>

<li><p>Async worker thread alongside the Async structure, this will be initialized inside <code>MpAsyncInitialize</code> and the structure will mainly keep two list entries of messages that are enqueued to be sent by the async worker thread. This thread is initialized inside this function too, and the function <code>MpAsyncpWorkerThread</code> is set as the StartRoutine of it.</p></li>

<li><p>The registry data structure, which will be initialized inside <code>MpRegInitialize</code>, of size <code>0x500</code> and tag <code>MPrD</code>. This is another big and important structure that will be used mainly in the RegistryCallback &ndash; We will get into this callback in the next post.</p></li>

<li><p>Document rules structure, initialized inside <code>MpInitializeDocOpenRules</code> with a size of <code>0x100</code>, tag <code>MPdo</code> and saved in the global <code>MpBmDocOpenRules</code> &ndash; A bit further down we&rsquo;ll see more about this quite interesting structure.</p></li>

<li><p>Folder Guard structure, which is initialized inside <code>MpFgInitialize</code> only on systems running Windows 10 build 16000 or higher has a size of <code>0x240</code>, tag <code>MPFg</code> and saved in the global <code>MpFolderGuard</code>. The structure will keep a pointer to a <strong>RTL_AVL_TABLE</strong> table and a <strong>RTL_GENERIC_TABLE</strong> and it will be used mainly to allow or revoke access to files/folders.</p></li>

<li><p>Lastly, the drivers info structure, which is initialized inside <code>MpInitializeDriverInfo</code>, this structure is tied to the ELAM driver, and is the one that will be used mainly on the function registered for the callback <code>\Callback\WdEbNotificationCallback</code>. When we get into how this function and this structure is used we will be able to intertwine what we saw in the post about the <a href="https://n4r1b.com/en/posts/2019/11/understanding-wdboot-windows-defender-elam/" target="_blank"><strong>WdBoot</strong></a> with what <strong>WdFilter</strong> does with that data.</p></li>
</ul>

<p>Reached this point we will find ourselves with a good amount of allocated pools and initialized structures:</p>

<p><img src="/images/wdFilter/part1/PoolUsed.png" alt="alt image" title="Pools Used" /></p>

<p>The next step in the <code>DriverEntry</code> is to initialize both the minifilter, inside <code>MpInitializeFltMgr</code>, and the communication ports, inside <code>MpCreateCommPorts</code>. The former will choose a specific <code>OperationRegistration</code> for the <code>FLT_REGISTRATION</code> structure based on the configuration and the <code>OsVersionMask</code>, with this <code>FilterRegistration</code> it will register the minifilter (<code>FltRegisterFilter</code>). The latter will first set up a security descriptor using the <strong>MpServiceSID</strong> and this security descriptor will be used in the <code>ObjectAttributes</code> given as argument to <code>FltCreateCommunicationPort</code>. Four different ports will be created:</p>

<ul>
<li>MicrosoftMalwareProtectionControlPort (This is the only port that will registers a MessageNotifyCallback)</li>
<li>MicrosoftMalwareProtectionPort</li>
<li>MicrosoftMalwareProtectionVeryLowIoPort</li>
<li>MicrosoftMalwareProtectionRemoteIoPort</li>
</ul>

<p>From this point, roughly, the <code>DriverEntry</code> will register callbacks for the following events:</p>

<ul>
<li>Process Creation</li>
<li>Image Load</li>
<li>Thread Creation</li>
<li>Image Verification</li>
<li>Object Operations (ProcessType and DesktopObjectType)</li>
<li>Registry Operations</li>
</ul>

<blockquote>
<p>Since the post is already quite long, for this part I will only focus on the first two</p>
</blockquote>

<p>After setting the the Image Verification callback the driver will start filtering (<code>FltStartFiltering</code>) and after registering the last two callbacks the driver initialization would be done. Of course, if at any point any of the aforementioned steps fail the driver will cleanup everything.</p>

<h2 id="mpsetprocessnotifyroutine">MpSetProcessNotifyRoutine</h2>

<p>The first callback registration we will dig into is the process creation, this callback is register inside <code>MpSetProcessNotifyRoutine</code>. First thing this function will do is check if <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex2" target="_blank"><code>PsSetCreateProcessNotifyRoutineEx2</code></a> is available (Windows 10 build 14980 - <code>OsVersionMask &amp; 0x80</code>), in case it is then it will use this function to register the callback, if is not available then it will check <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex" target="_blank"><code>PsSetCreateProcessNotifyRoutineEx</code></a> lastly if this one isn&rsquo;t available either then it will resort in <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine" target="_blank"><code>PsSetCreateProcessNotifyRoutine</code></a>. Once one of the callback routine has been registered, the code will then proceed to create two callback objects <code>\Callback\WdProcessNotificationCallback</code> and <code>\Callback\WdNriNotificationCallback</code>. For the latter, the code will also register a callback function &ndash; <code>MpNriNotificationCallback</code></p>

<blockquote>
<p>To get more information on this Callback Objects and others, make sure to check the research <a href="https://twitter.com/0xcpu" target="_blank">0xcpu</a> and I have been conducting on them <a href="https://github.com/0xcpu/ExecutiveCallbackObjects" target="_blank">https://github.com/0xcpu/ExecutiveCallbackObjects</a></p>
</blockquote>

<h3 id="mpcreateprocessnotifyroutineex-mpcreateprocessnotifyroutine">MpCreateProcessNotifyRoutineEx - MpCreateProcessNotifyRoutine</h3>

<p>In this section I will explain what does the callback routine registered for the process creation does. As can be seen on the section title, there can be two routines, the first one is registered by the <code>..Ex2</code> and <code>..Ex</code> while the second one is registered by <code>PsSetCreateProcessNotifyRoutine</code>.</p>

<blockquote>
<p>The difference between the <code>..Ex</code> and the <code>..Ex2</code> functions is basically that the latter allows to provide a <code>PSCREATEPROCESSNOTIFYTYPE</code> and even though this value can only be set to <code>PsCreateProcessNotifySubsystems</code> maybe in the future they will add more value for example one to get only notifications from the WSL subsystem. On the other hand, the difference from this two against <code>PsSetCreateProcessNotifyRoutine</code> is that in the latter the register routine protoype is <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pcreate_process_notify_routine" target="_blank"><code>CREATE_PROCESS_NOTIFY_ROUTINE</code></a> while for the other two the prototype is <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pcreate_process_notify_routine_ex" target="_blank">CREATE_PROCESS_NOTIFY_ROUTINE_EX</a></p>
</blockquote>

<p>Both functions are pretty similar, moreover, they share a lot of the code. There&rsquo;s only a couple of difference between them, the main differences being:</p>

<ul>
<li>MpCreateProcessNotifyRoutineEx can take advantage of having the structure <code>PS_CREATE_NOTIFY_INFO</code>, for example if the flag <strong>FileOpenNameAvailable</strong> is set then it can retrieve the ImageFileName without the need of getting a handle to the process.</li>
<li>MpCreateProcessNotifyRoutineEx can deny the creation of the process setting the value <strong>CreationStatus</strong> to an error.</li>
<li>The last difference is that function MpCreateProcessNotifyRoutineEx has also the ability to add processes to the boot process list entry, by calling <code>MpAddBootProcessEntry</code></li>
</ul>

<p>Getting into the actual code, as I mentioned above, in case we don&rsquo;t have the flag <strong>FileOpenNameAvailable</strong> or the case we don&rsquo;t have <code>PS_CREATE_NOTIFY_INFO</code> the code will proceed to obtain a handle to the process (<code>ZwOpenProcess</code>) and with this handle it will call <code>MpGetProcessNameByHandle</code>, which basically calls <code>ZwQueryInformationProcess</code> with <code>ProcessImageFileName</code> as the ProcessInformationClass. Once the callback routine has the ImageFileName it will proceed to obtain the normalized name, to do this it will call the function <code>MpGetImageNormalizedName</code>, this function will mainly call <code>FltGetFileNameInformationUnsafe</code> with NameOptions <code>FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT</code>. Finally, the callback routine will end up calling <code>MpHandleProcessNotification</code>, which is the main function of this callback.</p>

<h4 id="mphandleprocessnotification">MpHandleProcessNotification</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#8be9fd">void</span> <span style="color:#ff79c6">__fastcall</span> <span style="color:#50fa7b">MpHandleProcessNotification</span>(
  _In_  PEPROCESS       Process, 
  _In_  HANDLE          ParentId, 
  _In_  HANDLE          ProcessId, 
  _In_  BOOLEAN         Create, 
  _In_  BOOLEAN         IsTransacted, 
  _In_  PUNICODE_STRING ImageFileName, 
  _In_  PUNICODE_STRING CommandLine, 
  _Out_ PBYTE           AccessDenied
);</code></pre></div>
<p>This function has two very clear code paths, which are defined by the <strong>Create</strong> flag. In the case where the process is being created the first, and probably one of the most important steps in the filter, is to create the ProcessContext structure. This is done inside <code>MpCreateProcessContext</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#ff79c6">__fastcall</span> MpCreateProcessContext(
  _In_  HANDLE          ProcessId, 
  _In_  LONGLONG        CreationTime, 
  _In_  PUNICODE_STRING FileNameAndCmdLine[<span style="color:#bd93f9">2</span>], <span style="color:#6272a4">// This is probably a struct with two UNICODE_STRING
</span><span style="color:#6272a4"></span>  _Out_ PProcessCtx     <span style="color:#ff79c6">*</span>ProcessCtx
)</code></pre></div>
<p>this function will mainly allocate memory from the Lookaside <code>MpProcessTable-&gt;ProcessCtxLookaside</code> to hold one Process Context &ndash; Size <code>0xC0</code> - Tag <code>MPpX</code> &ndash; after the memory is allocated it will start filling the members of the Process Context structure, this structure looks something like this:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ProcessCtx
{
  SHORT Magic;        <span style="color:#6272a4">// Set to 0xDA0F
</span><span style="color:#6272a4"></span>  SHORT StructSize;   <span style="color:#6272a4">// Sizeof 0xC0
</span><span style="color:#6272a4"></span>  LIST_ENTRY ProcessCtxList ;
  HANDLE ProcessId;
  QWORD CreationTime;
  PUNICODE_STRING ProcessCmdLine;
  INT RefCount;
  DWORD ProcessFlags;
  DWORD ProcessRules;
  QWORD SthWithCodeInjection;   <span style="color:#6272a4">// Requires further investigation 
</span><span style="color:#6272a4"></span>  QWORD SthWithCodeInjection1;  <span style="color:#6272a4">// Both fields used in MpAllowCodeInjection
</span><span style="color:#6272a4"></span>  PMP_DOC_RULE pDocRule;
  BOOLEAN (<span style="color:#ff79c6">__fastcall</span> <span style="color:#ff79c6">*</span>pCsrssPreScanHook)(PFLT_CALLBACK_DATA, FltStreamCtx <span style="color:#ff79c6">*</span>);
  INT field_60;
  INT NotificationsSent;
  INT InjectionsHandlesCount;
  INT field_6C;
  PVOID Wow64CpuImageBase;
  INT ProcessSubsystemInformation;
  PUNICODE_STRING ImageFileName;
  BYTE HipRules[<span style="color:#bd93f9">16</span>];
  BYTE HipRules1[<span style="color:#bd93f9">16</span>];
  QWORD field_A8;
  QWORD field_B0;
  _PS_PROTECTION ProcessProtection;
  INT StreamHandleCtxCount;
} ProcessCtx, <span style="color:#ff79c6">*</span>PProcessCtx;</code></pre></div>
</div>

<p>Once the Process Context (ProcessCtx from now on) has been retrieved or created, the function will proceed to see if a doc rule should be attached to this Process. This is done inside <code>MpSetProcessDocOpenRule</code> and there are two structures involved. One that keeps a list of all the documents rules and one for each rule.</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DOC_OPEN_RULES
{
  SHORT Magic;        <span style="color:#6272a4">// Set to 0xDA14
</span><span style="color:#6272a4"></span>  SHORT StructSize;   <span style="color:#6272a4">// Sizeof 0x100 
</span><span style="color:#6272a4"></span>  SINGLE_LIST_ENTRY <span style="color:#ff79c6">*</span><span style="color:#50fa7b">__shifted</span>(MP_DOC_RULE,<span style="color:#bd93f9">8</span>) DocObjectsList;
  ERESOURCE DocRulesResource;
  <span style="color:#ff79c6">struct</span> _PAGED_LOOKASIDE_LIST DocObjectsLookasideList;
} MP_DOC_OPEN_RULES, <span style="color:#ff79c6">*</span>PMP_DOC_OPEN_RULES;

<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_DOC_RULE
{
  SHORT Magic;        <span style="color:#6272a4">// Set to 0xDA15
</span><span style="color:#6272a4"></span>  SHORT StructSize;   <span style="color:#6272a4">// Sizeof 0x228
</span><span style="color:#6272a4"></span>  INT RefCount;
  SINGLE_LIST_ENTRY SingleListEntryDocRules;
  WCHAR DocProcessName[<span style="color:#bd93f9">261</span>];
  PCWSTR RuleExtension;
} MP_DOC_RULE, <span style="color:#ff79c6">*</span>PMP_DOC_RULE;</code></pre></div>
</div>

<p>The code will basically iterate the single list entry comparing the ImageFileName with the DocProcessName, if any of the rules matches, then that a pointer the <code>MP_DOC_RULE</code> structure will be saved in the <code>ProcessCtx-&gt;pDocRule</code>.</p>

<p>Next step is to check if the process which context has been created is <code>csrss.exe</code> &ndash; <code>MpSetProcessPreScanHook</code> &ndash; in case it is, a pointer to <code>CsrssPreScanHook</code> will be saved in <code>ProcessCtx.pCsrssPreScanHook</code> and the flag <code>MpData-&gt;pCsrssHookData-&gt;HookSetFlag</code> will be set. This is only done for the ProcessCtx of <code>csrss.exe</code></p>

<p><img src="/images/wdFilter/part1/CsrssHook.png" alt="alt image" title="Csrss Hook" /></p>

<p>The last step before notifying the creation of the process is to check if the process matches some exceptions and set the <code>ProcessCtx.ProcessFlags</code> accordingly. To do this check there are three functions:</p>

<ul>
<li>MpSetProcessExempt</li>
<li>MpSetProcessHardening</li>
<li>MpSetProcessHardeningExclusion</li>
</ul>

<p>The first one will iterate over the single list entry of the following structure &ndash; I know, there&rsquo;s <strong>A LOT</strong> of structures.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// Sizeof 0x20
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_PROCESS_EXCLUDED
{
  SINGLE_LIST_ENTRY ExcludedProcessList;
  UNICODE_STRING ProcessPath;
  BYTE NoBackslashFlag;
  BYTE WildcardPathFlag;
} MP_PROCESS_EXCLUDED, <span style="color:#ff79c6">*</span>PMP_PROCESS_EXCLUDED;</code></pre></div>
<p>and it will check <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/fltkernel/nf-fltkernel-fltparsefilename" target="_blank">FinalComponent</a> of the ImageFileName is either prefix or equal to any of the ones from the list, in case it matches it will set the ProcessFlags by applying an OR with <code>0x1</code>. The driver has the capabilitie to add Process/Paths to the <code>MP_PROCESS_EXCLUDED</code> list based on a message received from user space &ndash; <strong>MsMpEng.exe</strong> &ndash; Here we can see a list of process excluded using this criteria</p>

<p><img src="/images/wdFilter/part1/ProcessExcluded.png" alt="alt image" title="Process excluded" /></p>

<blockquote>
<p>There&rsquo;s one special case in this check, when the process is <strong>MsMpEng</strong> in this case the ProcessFlags will be ORed with <code>0x9</code></p>
</blockquote>

<p>The second check will first check if the FinalComponent matches <strong>mpcmdrun.exe</strong> or <strong>msmpeng.exe</strong>, in case it does using the previously created <strong>MpServiceSID</strong> it will check if the access token of the process matches that SID. If none of those process name match then it will check against <strong>nissrv.exe</strong> and <strong>NriServiceSID</strong>. If any of this situations is matched succesfully the ProcessFlags will be ORed with <code>0x10</code>.</p>

<blockquote>
<p>There&rsquo;s another possible situation if we are running MpFilter instead of WdFilter, in this case process name will be compared agains <strong>msseces.exe</strong> and if it matches the ProcessFlag will be ORed against <code>0x80</code></p>
</blockquote>

<p>The last check will first create, if needed, a list entry of hardened excluded process. The values for this list entry are hardcoded in <strong>WdFilter</strong> in an structure that keeps the name, a flag that indicates to what system does it applies and lastly the mask value that will be applied to the ProcessFlags</p>

<p><img src="/images/wdFilter/part1/HardenedExcludedProcess.png" alt="alt image" title="Hardened Process excluded" /></p>

<p>with those values the following structure will be filled</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// Sizeof 0x20
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_PROCESS_HARDENING_EXCLUDED
{
  LIST_ENTRY ProcessExcludedList;
  PUNICODE_STRING ProcessPath;
  INT ProcessHardeningExcludedMask;
} MP_PROCESS_HARDENING_EXCLUDED, <span style="color:#ff79c6">*</span>PMP_PROCESS_HARDENING_EXCLUDED;</code></pre></div>
<p>once the structure is filled the procedure of the check is quite standard, the code compares the name and if it matches then it applies the ProcessHardeningExcludedFlag to the <code>ProcessCtx.ProcessFlags</code>. In the following image we can see the list of process in the <code>MP_PROCESS_HARDENING_EXCLUDED</code> of my system</p>

<p><img src="/images/wdFilter/part1/ProcessHardeningExclusion.png" alt="alt image" title="Hardened Process" /></p>

<p>One last detail regarding the process exclusion, is that a reference to both structures we just saw is kept in another structure &ndash; Yep, since there are not many structures already&hellip; there&rsquo;s one more 😆.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#6272a4">// Sizeof 0x78
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_PROCESS_EXCLUSION
{
  ERESOURCE ProcessExclusionResource;
  MP_PROCESS_EXCLUDED <span style="color:#ff79c6">*</span>ProcessExclusionList;
  MP_PROCESS_HARDENING_EXCLUDED <span style="color:#ff79c6">*</span>ProcessHardenedExclusionList;
} MP_PROCESS_EXCLUSION, <span style="color:#ff79c6">*</span>PMP_PROCESS_EXCLUSION;</code></pre></div>
<p>After all this, the &ldquo;default&rdquo; ProcessCtx is ready and now is time to notify the callback <code>\Callback\WdProcessNotificationCallback</code>. <strong>Argument1</strong> will contain the following structure</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">typdef <span style="color:#ff79c6">struct</span> _MP_PROCESS_CB_NOTIFY
{
  HANDLE ProcessId;
  HANDLE ParentId;
  PUNICODE_STRING ImageFileName;
  INT OperationType;  <span style="color:#6272a4">// ProcessCreation = 1; ProcessTermination = 2; SetProcessInfo = 3
</span><span style="color:#6272a4"></span>  BYTE ProcessFlags;
} MP_PROCESS_CB_NOTIFY, <span style="color:#ff79c6">*</span>PMP_PROCESS_CB_NOTIFY;</code></pre></div>
<blockquote>
<p>For the sake of brevity, I won&rsquo;t explain more details about this. Please refer to the <a href="https://github.com/0xcpu/ExecutiveCallbackObjects/tree/master/WdProcessNotificationCallback" target="_blank">Github</a> to learn more about this callback.</p>
</blockquote>

<p>After notifying the callback we just need one last step to finish the ProcessNotification callback, this step is to send a message to the user space process listening to port <code>ProtectionPortServerCookie</code>.</p>

<p>Before getting into the function that creates and send the message, I&rsquo;ll explain quickly the case when the flag <strong>Create</strong> is not set, which means the process is exiting. In this case the ProcessCtx will be obtained by the process Id, and with this ProcessCtx the structure <code>MP_PROCESS_CB_NOTIFY</code> will be populated and the callback notified. After this <code>MpSendProcessMessage</code> will be called to create and send the message.</p>

<p>One last detail is the call to <code>MpCopyCacheProcessTerminate</code> which will iterate over an array of <code>MP_COPY_CACHE_ENTRY</code></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_COPY_CACHE_ENTRY
{
  DWORD Flags;
  HANDLE ProcessId;
  HANDLE ThreadId;
  UNICODE_STRING FileName;
  QWORD FileSize;
  QWORD TimeStamp;
  INT64 qword38;
} MP_COPY_CACHE_ENTRY, <span style="color:#ff79c6">*</span>PMP_COPY_CACHE_ENTRY;</code></pre></div>
<h4 id="mpsendprocessmessage">MpSendProcessMessage</h4>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#ff79c6">__fastcall</span> MpSendProcessMessage(
  _In_  BYTE                CreateFlag,
  _In_  PEPROCESS           Process, 
  _In_  HANDLE              ProcessId, 
  _In_  BOOLEAN             IsTransacted, 
  _In_  HANDLE              ParentId, 
  _In_  PAuxPidCreationTime ParentPidAndCreationTime, 
  _In_  PUNICODE_STRING     ImageFileName, 
  _In_  PProcessCtx         ProcessCtx, 
  _In_  PUNICODE_STRING     CommandLine, 
  _Out_ PBYTE               AccessDenied
)</code></pre></div>
<p>This function, and a lot of other functions we will see during this series of posts, handle the creation of a message with some specific data that will be sent to <strong>MsMpEng</strong>. This data can be send synchronously or asynchronously (Using the worker thread I mentioned above) &ndash; The message will be created differently, even though sometimes they use the async method but then send that message synchronously.</p>

<p>In the case of this function both message will be created using the asynchronous structure but if the parameter CreateFlag is <code>0x1</code> then the message will be sent synchronously (<code>FltSendMessage</code>), in case is <code>0x0</code> it will be enqueued and the worker thread will take care of it.</p>

<p>I&rsquo;ll try to explain this as short and simple as possible. All async messages will be created with a function called <code>MpAsyncCreateNotification</code>. This function receives two parameters, first one is an outparam that will return a shifted pointer inside the allocated buffer that&rsquo;s gonna be send as message, while the second parameter is the size to allocate.</p>

<p>So after that call we will end up with a buffer that needs to be filled with the specific data. And again, this buffer is shifted 8 bytes into the structure I named <code>AsyncMessageData</code>. This structure will look something like this</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _AsyncMessageData
{
  INT Magic;
  INT Size;
  INT64 NotificationNumber;
  DWORD SizeOfData;
  INT RefCount;
  INT TypeOfOperation;
  <span style="color:#ff79c6">union</span> {
    <span style="color:#6272a4">// This are the ones I have for now
</span><span style="color:#6272a4"></span>    ImageLoadAndProcessNotifyMessage ImageLoadAndProcessNotify;
    TrustedOrUntrustedProcessMessage TrustedProcess;
    ThreadNotifyMessage ThreadNotify;
    CheckJournalMessage CheckJournal;
  };
} AsyncMessageData, <span style="color:#ff79c6">*</span>PAsyncMessageData;</code></pre></div>
<p>As we can see, this struct contains a union where the specific data for each type of different message will start. In this case we will focus on the data regarding ProcessNotify, this structure looks something like this:</p>

<div class="highlight-wrapper">
    <div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"> 
<span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _ImageLoadAndProcessNotifyMessage
{
  AuxPidCreationTime ParentProcess;   <span style="color:#6272a4">// ZwOpenProcess -&gt; PsGetProcessCreateTimeQuadPart
</span><span style="color:#6272a4"></span>  AuxPidCreationTime CurrentProcess;  <span style="color:#6272a4">// ZwOpenProcess -&gt; PsGetProcessCreateTimeQuadPart
</span><span style="color:#6272a4"></span>  BYTE CreateFlag;
  BYTE ProcessFlags;
  BYTE UnkGap[<span style="color:#bd93f9">10</span>];  <span style="color:#6272a4">// Weird alignment :S 
</span><span style="color:#6272a4"></span>  DWORD FileNameLength;
  DWORD OffsetToImageFileName;
  DWORD SessionId;
  DWORD CommandLineLenght;
  DWORD OffsetToCommandLine;
  DWORD TokenElevationType;
  DWORD TokenElevation;
  DWORD TokenIntegrityLevel;
  DWORD Unk;
  AuxPidCreationTime CreatorProcess;  <span style="color:#6272a4">// Parameter -&gt; ParentPidAndCreationTime
</span><span style="color:#6272a4"></span>} ImageLoadAndProcessNotifyMessage, <span style="color:#ff79c6">*</span>PImageLoadAndProcessNotifyMessage;</code></pre></div>
</div>

<p>This would be the structure without a ImageFileName and without CommandLine, in case there is any of those or even both, the strings would be after this data and the members <code>OffsetToImageFileName</code> and <code>OffsetToCommandLine</code> would contain the relative offset to the start of each string (Relative from the start of the inner structure).</p>

<blockquote>
<p>The structure AuxPidCreationTime you can see inside the struct is just an strucutre containing the PID as a ULONG and the CreationTime as ULONG64. If anyone knows an already defined structure with that data please let me know and I&rsquo;ll change it.</p>
</blockquote>

<p><img src="/images/wdFilter/part1/SendProcessMessage.png" alt="alt image" title="Send Process Message" /></p>

<p>Once the message is sent, in the case of using <code>FltSendMessage</code>, the function will proceed to check the status of the call and proceed to fill some fields of <strong>MpData</strong> accordingly</p>

<ul>
<li>FltSendMessageCount</li>
<li>FltSendMessageError - In case it failed</li>
<li>FltSendMessageStatusTimeout - In case the status was <code>STATUS_TIMEOUT</code></li>
</ul>

<p>If everything went well, the code will check the <code>ReplyBuffer</code> (First byte should be <code>0x5D</code> and Second Word should be <code>0x60</code>, Size of the reply message). Among the things this reply buffer can contain is wheter the creation of the process is allowed or not (Byte <code>0x48</code>)</p>

<p>And finally the last step before finishing is to set up the process info (Mainly with the information received from the <code>ReplyBuffer</code>) after doing that it will test the ProcessFlags &ndash; <code>ProcessFlags &amp; 0x20 || ProcessFlags &amp; 0x18</code> &ndash; to add the process either to the Trusted or Untrusted process list. This is done inside <code>MpSetTrustedProcess</code> or <code>MpSetUntrustedProcess</code> respectively, but the post is already long enought so we will see those functions in the next part!</p>

<h3 id="mppowerstatuscallback">MpPowerStatusCallback</h3>

<p>One last thing before finishing, I said before I was going to talk a bit about the power-setting callback routine registered during the initialization.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C">NTSTATUS <span style="color:#50fa7b">MpPowerStatusCallback</span>(
  LPCGUID SettingGuid, 
  PVOID Value, 
  ULONG ValueLength, 
  PVOID Context
  )
{
  <span style="color:#ff79c6">if</span> (Value <span style="color:#ff79c6">&amp;&amp;</span> Value <span style="color:#ff79c6">==</span> <span style="color:#bd93f9">4</span> <span style="color:#ff79c6">&amp;&amp;</span> IsEqualGUID(SettingGuid, GUID_LOW_POWER_EPOCH)) {
    <span style="color:#ff79c6">if</span> ( <span style="color:#ff79c6">*</span>(ULONG <span style="color:#ff79c6">*</span>) Value ) {
      <span style="color:#ff79c6">if</span> ( <span style="color:#ff79c6">*</span>(ULONG <span style="color:#ff79c6">*</span>) Value <span style="color:#ff79c6">==</span> <span style="color:#bd93f9">1</span> ) {
        MpData<span style="color:#ff79c6">-&gt;</span>LowPowerEpochOn <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>;
        MpData<span style="color:#ff79c6">-&gt;</span>MachineUptime <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;
      }
    } <span style="color:#ff79c6">else</span> {
      MpData<span style="color:#ff79c6">-&gt;</span>MachineUptime <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">*</span>(ULONG64 <span style="color:#ff79c6">*</span>) <span style="color:#bd93f9">0xFFFFF78000000014</span>;
    }
  }
  <span style="color:#ff79c6">return</span> STATUS_SUCCESS;
}</code></pre></div>
<p>Because of my lack of knowledge on Power Management plus the fact that there&rsquo;s practically non-info on that GUID and the only thing related to Microsoft and low power epoch I managed to find is this strucutre: <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/pepfx/ns-pepfx-_pep_low_power_epoch" target="_blank">PEP_LOW_POWER_EPOCH</a> in the documentation, but actually it doesn&rsquo;t explain much, just that is used for a deprecated notification. I&rsquo;m not comfortable saying anything in regard to this function, I just put it here and if somebody knows more about this <strong>Please</strong> reach out to me! I would love to hear more about this.</p>

<h3 id="conclusion">Conclusion</h3>

<p>That&rsquo;s gonna be all for this part, sorry for the <strong>Super</strong> long post I really tried to be as clear and concise as possible but there&rsquo;s plenty of things going on in the driver, so things may seem a bit messy for now, but bear with me throughout all the posts things will start to make sense and I hope in the end we can glue everything together. As always, I hope you guys liked the post! We still have a long way ahead, this is just the tip of the iceberg, but slowly we&rsquo;ll get to the end! In the next post I&rsquo;ll be talking about the image load and thread creation callbacks, so I hope I&rsquo;ll see you there!</p>

<p>If there&rsquo;s any mistake or something not clear, please don&rsquo;t hesitate to reach out to me on twitter <a href="https://twitter.com/n4r1B" target="_blank">@n4r1b</a></p>

<h3 id="bonus">Bonus</h3>

<p>This little windbg script let us print whatever data we want from all the ProcessCtx in the system. We just need the symbols of WdFilter and tweak the command <code>!list</code> however we like.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c++" data-lang="c++">r @$t0 <span style="color:#ff79c6">=</span> poi(poi(WdFilter<span style="color:#ff79c6">!</span>MpProcessTable)<span style="color:#ff79c6">+</span><span style="color:#bd93f9">180</span>); <span style="color:#6272a4">// Pointer to MpProcessTable-&gt;ProcessCtxArray
</span><span style="color:#6272a4"></span>.<span style="color:#ff79c6">for</span> (r $t1 <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>; @$t1 <span style="color:#ff79c6">!=</span> <span style="color:#bd93f9">0x80</span>; r $t1 <span style="color:#ff79c6">=</span> @$t1<span style="color:#ff79c6">+</span><span style="color:#bd93f9">1</span>)  <span style="color:#6272a4">// Array size 0x80
</span><span style="color:#6272a4"></span>{  
  r @$t2 <span style="color:#ff79c6">=</span> @$t0<span style="color:#ff79c6">+</span><span style="color:#bd93f9">10</span><span style="color:#ff79c6">*</span>@$t1;                        <span style="color:#6272a4">// Move pointer to next LIST_ENTRY
</span><span style="color:#6272a4"></span>  .<span style="color:#ff79c6">if</span> ( @$t2 <span style="color:#ff79c6">==</span> poi(@$t2) ) {                   <span style="color:#6272a4">// Check if our pointer value is the same as Blink
</span><span style="color:#6272a4"></span>    .<span style="color:#ff79c6">continue</span>                                   
  } 
  .<span style="color:#ff79c6">else</span> {                                       <span style="color:#6272a4">// We walk the LIST_ENTRY and print whatever
</span><span style="color:#6272a4"></span>                                                <span style="color:#6272a4">// member we want from ProcessCtx in this case
</span><span style="color:#6272a4"></span>                                                <span style="color:#6272a4">// ProcessCtx.ProcessId and ProcessCtx.ProcessCmdLine 
</span><span style="color:#6272a4"></span>   <span style="color:#ff79c6">!</span>list <span style="color:#ff79c6">-</span>t nt<span style="color:#ff79c6">!</span>_LIST_ENTRY.Flink <span style="color:#ff79c6">-</span>x <span style="color:#f1fa8c">&#34;dd @$extret+10 L1; dS /c100 poi(@$extret+20)&#34;</span> <span style="color:#ff79c6">-</span>a <span style="color:#f1fa8c">&#34;L1&#34;</span> poi(@$t2) 
  } 
}
</code></pre></div>
<p>If you run the above script you should see something like this:</p>

<p><img src="/images/wdFilter/part1/ListProcess.png" alt="alt image" title="List ProcessCtx" /></p>
]]></content></item><item><title>Understanding WdBoot (Windows Defender ELAM)</title><link>https://n4r1b.com/posts/2019/11/understanding-wdboot-windows-defender-elam/</link><pubDate>Tue, 05 Nov 2019 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2019/11/understanding-wdboot-windows-defender-elam/</guid><description>Finally I&amp;rsquo;m going to talk about the Windows Defender ELAM Driver! Ever since I worked in an AV vendor I&amp;rsquo;ve always been interested by the features Microsoft release to help fight malware, and the ELAM is one of this features. It was introduced on Windows 8 and as a big overview basically it gives a way for a specially signed driver to execute before the initalization of boot drivers and allow or not their execution (Oficial Microsoft documentation).</description><content type="html"><![CDATA[

<p>Finally I&rsquo;m going to talk about the Windows Defender ELAM Driver! Ever since I worked in an AV vendor I&rsquo;ve always been interested by the features Microsoft release to help fight malware, and the ELAM is one of this features. It was introduced on Windows 8 and as a big overview basically it gives a way for a specially signed driver to execute before the initalization of boot drivers and allow or not their execution <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/install/early-launch-antimalware" target="_blank">(Oficial Microsoft documentation)</a>.</p>

<blockquote>
<p><strong>*DISCLAIMER*</strong></p>

<p>This investigation has been done on a system running Windows 10 Pro Version 1903 (OS Build 19013.1) and <code>WdBoot.sys</code> version <code>4.18.1910.4</code></p>
</blockquote>

<h2 id="wdboot-init">WdBoot Init</h2>

<p>First let&rsquo;s have in mind that <code>winload</code> already load all the boot-start drivers and their dependencies into memory but now these drivers must be initialized, here is where ELAM drivers come into play (There&rsquo;s a couple drivers initialized before the ELAM driver, for example <code>CNG.sys</code> which allow ELAM devs to take advantage of the CNG Cryptographic Primitive Functions). Of course, ELAM drivers also have their own initialization phase, so let&rsquo;s get into the initalization of <code>WdBoot</code>. If we set a breakpoint in the DriverEntry we would find the following call stack:
<img src="/images/wdELAM/InitCallStack.png" alt="alt image" title="Call Stack EntryPoint WdBoot" /></p>

<blockquote>
<p>WdBoot, as the other WD drivers, rely on WPP for tracing and logging. This means the code is full of WPP variables and functions, I&rsquo;m not going to describe how it works but you can get more info here <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/wpp-software-tracing" target="_blank">https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/wpp-software-tracing</a></p>
</blockquote>

<p>After initializing WPP, the code will proceed to try an delete the value <code>ElamInfo</code> from the <code>WdBoot</code> key in the Service registry tree , this value basically will hold all the data recolected by the ELAM driver but later I will explain how and when is set (This key is not always set). The next step is to initialize the structure <code>MpEbGlobals</code>, this is the main global structure of WdBoot. Microsoft provides the name but not the declaration of it, so I&rsquo;m afraid this will be a spoiler but the declaration looks something like the following:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#6272a4">// sizeof(MP_EP_GLOBALS) == 0xB0
</span><span style="color:#6272a4"></span><span style="color:#ff79c6">typedef</span> <span style="color:#ff79c6">struct</span> _MP_EP_GLOBALS
{
  UNICODE_STRING RegistryPath;
  PVOID pHandleRegistration;
  PVOID IoUnregisterBootDriverCallback;
  DWORD Magic; <span style="color:#6272a4">// Set to 0x28EB01
</span><span style="color:#6272a4"></span>  DWORD SignaturesVersionMajor;
  DWORD SignaturesVersionMinor;
  LIST_ENTRY DriversListEntry;
  PSLIST_ENTRY ElamRegistryEntries;
  PCALLBACK_OBJECT pWdCallbackObject;
  LARGE_INTEGER Cookie;
  _QWORD Unk_Unused1;
  SLIST_HEADER SlistHeader;
  DWORD LoadedDriversCount;
  DWORD LoadedDriversArrayLen;
  PVOID LoadedDriversArray; 
  DWORD TotalModulesEntryLen;
  BYTE EntryPointWdFilter[<span style="color:#bd93f9">32</span>];
  BYTE FlagWdOrMp;
  BYTE FlagTestMode;
  BYTE FlagPersistElamInfo;
  _QWORD Unk_Unused2;
} MP_EP_GLOBALS, <span style="color:#ff79c6">*</span>PMP_EP_GLOBALS;</code></pre></div>
<p>This structure will be first set to zero, then the Magic, DriversListEntry, SlistHeader, FlagWdOrMp, FlagTestMode and RegistryPath will be all init/set.</p>

<p><img src="/images/wdELAM/InitMpGlobals.png" alt="alt image" title="Init MP_EP_GLOBALS" /></p>

<p>Next step is to create the callback, the name of the callback will be different depending on the FlagWdOrMp. This flag basically determines if the driver must look for Windows Defender or Microsoft Antimalware Platform. In this case I will focus on WD case, the callback will be created with the function <code>ExCreateCallback</code> and the callback name will be <code>\Callback\WdEbNotificationCallback</code> the callback object will be saved in the corresponding member of <code>MP_EP_GLOBALS</code>.</p>

<p>Then function <code>MpEbInitModuleInformation</code> will be called, this function will initialize the array that will contain the modules information, to do this a pool of size 0x200 will be allocated (Tag <code>Ebib</code>), the last byte of the first 0x40 members of the array will be set to 1 (This will be used later to check if the position of the array has been written or not). Finally, the variable <code>LoadedDriversArray</code> will be set to the address of the pool and the variable <code>LoadedDriversArrayLen</code> will be set to set to 0x800 (Actually it comes from <code>LoadedDriversArrayLen &amp; 0x1f | 0x800</code> but I&rsquo;ve always seen it being 0x800), when used this value will all the time be shifted right by 5 (0x40).</p>

<p>Once that&rsquo;s done the address of <code>IoRegisterBootDriverCallback</code> and <code>IoUnregisterBootDriverCallback</code> will be obtained dynamically using <code>MmGetSystemRoutineAddress</code> (In case any of those two functions is not supported <code>WdBoot</code> will finish with <code>STATUS_NOT_SUPPORTED</code>). After that the fun part begins, first the driver will load the signatures (<code>MpEbLoadSignatures</code>)</p>

<blockquote>
<p>Microsoft provides a bit of info on where this signatures should be saved. Take into acount that the ELAM Hive is unloaded after it has been used so to update it first it need to mounted (It can be found in the following path <code>\Windows\System32\config\ELAM</code>). <a href="https://docs.microsoft.com/en-gb/windows-hardware/drivers/install/elam-driver-requirements#malware-signatures" target="_blank">More Info</a></p>
</blockquote>

<p>This function is pretty straight-forward, it will obtain a handle to the ELAM Registry which contains the key <code>Windows Defender</code> and inside this key we can found the value <code>Measured</code> (This value is measured by Measured Boot)</p>

<p><img src="/images/wdELAM/RegHiveELAM.png" alt="alt image" title="ELAM Hive" /></p>

<p>This value contains the sigantures, so <code>MpEbLoadSignaturesEx</code> will open a handle to it and <code>MpEbGetSignatures</code> will query this value to obtain the data, also it will size of the data. Both the data and the size will be returned in out parameters from <code>MpEbLoadSignatures</code>. Next step is to load the signatures from that data, the function in charge of doing that is <code>EbLoadSignatureData</code> and is quite interesting so we will look into it a bit more in-depth.</p>

<h4 id="ebloadsignaturedata">EbLoadSignatureData</h4>

<blockquote>
<p>First, I have to acknowledge that the Federal Office for Information Security (BSI) did an investigation on TPM where they analyse a bit of the ELAM and they did a great job in how the signatures loading work, make sure to check it out <a href="https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Cyber-Sicherheit/SiSyPHus/Workpackage5_TPM-Nutzung.pdf?__blob=publicationFile&amp;v=2" target="_blank">here</a></p>
</blockquote>

<p>This function accepts two arguments, first one is the data previously obtained and second is the size of this data. The function will first check if the data is valid, to do this it uses the four first bytes:</p>

<pre><code>1: kd&gt; db rcx L4
ffffab06`9329c00c  ac 00 01 00 
</code></pre>

<p>These bytes will be used in the following way, first one is used as a Magic and the rest are used to obtain the offset to the actual signatures</p>

<pre><code>tmp = BYTE1(Data) | (WORD2(Data) &lt;&lt; 8)
OffsetToSignatures = Data + tmp + 4 // We add the first four bytes
</code></pre>

<p>Then it will authenticate the data to make sure it has not been tampered, to do this it uses the function <code>EbAuthenticateSignatureData</code>.</p>

<pre><code>NTSTATUS __fastcall EbAuthenticateSignatureData(
    PUCHAR SignaturesData,
    ULONG SignaturesDataSize,
    _BCRYPT_RSAKEY_BLOB *MpPublicKeyRaw, 
    DWORD PublicKeySize, 
    PVOID EncryptedSignature, 
    DWORD EncryptedSignatureSize
)
</code></pre>

<p>To authenticate the data it first will obtain request the algorithm <code>SHA1</code> to the <code>Microsoft Primitive Provider</code>. This will be used to hash the data containing the signatures, then it will request the algorithm <code>RSA</code> to import a public key (This public key is embeded in the driver, and is stored in the variable <code>g_MpPublicKeyRaw</code>) which will be used to decrypt the encrypted signature and verify if it matches the previous calculated hash (<code>BCryptVerifySignature</code>) if it does then the signatures will be loaded. In order to load the signatures, the driver will parse the SignaturesData in the following way (This is a pseudocode of the real implementation, it does not include error checking and non initialized variables are):</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c">ULONG   i <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>;
ULONG   code <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x80000000</span>;

<span style="color:#ff79c6">while</span>(i <span style="color:#ff79c6">&lt;=</span> SignaturesDataSize) {
    tag <span style="color:#ff79c6">=</span> BYTE(SignaturesData <span style="color:#ff79c6">+</span> i);
    EntrySize <span style="color:#ff79c6">=</span> BYTE1(SignaturesData <span style="color:#ff79c6">+</span> i) <span style="color:#ff79c6">|</span> 
              (BYTE2(SignaturesData <span style="color:#ff79c6">+</span> i) <span style="color:#ff79c6">|</span> 
              (BYTE3(SignaturesData <span style="color:#ff79c6">+</span> i) <span style="color:#ff79c6">&lt;&lt;</span> <span style="color:#bd93f9">8</span>) <span style="color:#ff79c6">&lt;&lt;</span> <span style="color:#bd93f9">8</span>);
    <span style="color:#ff79c6">switch</span>(tag) {
        <span style="color:#ff79c6">case</span> <span style="color:#bd93f9">0xA9</span><span style="color:#ff79c6">:</span>
            SigSize <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">*</span>(DWORD <span style="color:#ff79c6">*</span>)(SignaturesData <span style="color:#ff79c6">+</span> i <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">4</span>)
            <span style="color:#ff79c6">if</span> ( BYTE(SignaturesData <span style="color:#ff79c6">+</span> SigSize <span style="color:#ff79c6">+</span> i <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">8</span>) <span style="color:#ff79c6">==</span> <span style="color:#bd93f9">9</span> ) {
                AddSignature((SignaturesData <span style="color:#ff79c6">+</span> i <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">8</span>), SigSize, code);
            }
            <span style="color:#ff79c6">break</span>;
        <span style="color:#ff79c6">case</span> <span style="color:#bd93f9">0x5C</span><span style="color:#ff79c6">:</span>
            code <span style="color:#ff79c6">=</span> <span style="color:#ff79c6">*</span>(DWORD <span style="color:#ff79c6">*</span>)(SignaturesData <span style="color:#ff79c6">+</span> i <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">4</span>);
            <span style="color:#ff79c6">break</span>;
        <span style="color:#ff79c6">case</span> <span style="color:#bd93f9">0x5D</span><span style="color:#ff79c6">:</span>
            code <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0x80000000</span>;
            <span style="color:#ff79c6">break</span>;
    }
    i <span style="color:#ff79c6">+=</span> <span style="color:#bd93f9">4</span> <span style="color:#ff79c6">+</span> EntrySize;
}</code></pre></div>
<p>I hope this makes sense, here we can see a picture highlighting the different components taken into account by the parser:</p>

<p><img src="/images/wdELAM/Signtures.png" alt="alt image" title="Signature Parser" /></p>

<p>As you can see, the Signature per se is a 16 Bytes hash obtained when the tag byte is <code>0xA9</code>, also we can see tag <code>0x5C</code> contains some kind of strucute that has what it looks like the name of the signature I didn&rsquo;t look too much into this but in the Signatures Database values like <code>Trojan:Win64/Necurs.A</code> can be found.</p>

<p>Next we need to look into how the function <code>AddSignatures</code> saves the corresponding signature in a global array of signatures. First of all, the values will be added in the form of the following structure:</p>

<pre><code>struct SIGNATURE_DATA
{
  DWORD Code;
  BYTE SignatureType;
  BYTE SignatureClassification;
  WORD SigantureSize;
  PVOID pSignature;
};
</code></pre>

<p>where the values <code>SignatureType</code> and <code>SignatureClassification</code> take some value of the following enums:</p>

<pre><code>enum SIG_TYPE {
    THUMBPRINT_HASH = 1,
    CERTIFICATE_PUBLISHER = 2,
    ISSUER_NAME = 3,
    IMAGE_HASH = 4,
    REGISTRY = 6,
    VERSION_INFO = 7
}

enum SIG_CLASS {
    KnownGoodImage = 0,
    KnownBadImage = 1,
    KnownBadImageBootCritical = 3,
    UnknownImage = 4
}
</code></pre>

<p>The function won&rsquo;t do much more than allocate a pool to save the signature (Tag <code>EBeg</code>), increment the global variable that contains the size of the signatures array, and populate the structure I just mentioned. Once all the signatures have been loaded, the driver will sort this array (<code>MpQuickSort</code> based on the SignatureType) after this has been done it will iterate through the array looking for signatures with type <code>VERSION_INFO</code> or <code>REGISTRY</code>. In the first case, the pSignature will point to what it looks like a Major/Minor version (Probably the Signatures Database version) and the latter case will set two flags that will be aftewards check to see if a Registry Callback must be registered or not (In this investigation I didn&rsquo;t see this being used so I won&rsquo;t get much into it, I believe this must be something old since they are using <code>CmRegisterCallback</code> to register the callback and this function is obsolete since Windows Vista). That&rsquo;s pretty much how the signatures are loaded, after this has been done th driver will register a BootDriverCallback (<code>IoRegisterBootDriverCallback</code>) and proceed to enumerate the modules.</p>

<blockquote>
<p>Because I wanted to learn a bit more about Javascript Scripting in WinDBG, I though this was a great opportunity to get into it. So I wrote a little script that can displays all the signatures. It&rsquo;s not clean at all, just wanted to get my hands dirty with JS WinDBG scripting 😁</p>

<p><a href="https://github.com/n4r1b/Windbg_WdBootScript" target="_blank">https://github.com/n4r1b/Windbg_WdBootScript</a></p>
</blockquote>

<h4 id="mpebenumeratemodules">MpEbEnumerateModules</h4>

<p>This function is the last executed in the initialization of <code>WdBoot</code>, as the name implies, it will enumerate the modules loaded by <code>winload</code> and save this data to use it when the BootDrivers callback routine gets executed. First thing this function will do is call <code>MpEbGetModuleInformation</code>, this function does the following:</p>

<p><img src="/images/wdELAM/FunFunction.png" alt="alt image" title="MpEbGetModuleInformation" /></p>

<p>returning from this function we will have an array with all the loaded modules and the size of each element from this array, as seen in the next image:</p>

<p><img src="/images/wdELAM/ModulesArray.png" alt="alt image" title="Modules Array" /></p>

<p>With this data, the function will iterate each entry of this array and for each value it will execute <code>MpEbAllocateDriverInfoEx</code> which will initialize a structure I coined <code>MODULE_ENTRY</code> which I observed that has the following declaration:</p>

<pre><code>// sizeof(MODULE_ENTRY) == 0xB0
struct MODULE_ENTRY
{
  _QWORD Magic;         // Set to 0xB0EB01
  _QWORD WdFilterFlag;  // Set to 0xFBFBFBFBFAFAFAFA
  PVOID SameIndexSlist;
  _QWORD IndexHash;
  LIST_ENTRY DriversListEntry;
  UNICODE_STRING DriverImageName;
  UNICODE_STRING DriverRegistryPath;
  UNICODE_STRING CertPublisher;
  UNICODE_STRING CertIssuer;
  PVOID pImageHashPool;
  DWORD ImageHashAlgorithm;
  DWORD ImageHashLength;
  PVOID pCertThumbprintPool;
  DWORD ThumbprintHashAlgorithm;
  DWORD CertificateThumbprintLength;
  PVOID ImageBase;
  _QWORD ImageSize;
  DWORD ImageFlags;
  DWORD DriverClassification;
  _QWORD ModuleEntryEnd;
};
</code></pre>

<p><code>MpEbAllocateDriverInfoEx</code> will also set the ImageBase, ImageSize, DriverImageName and set the Flink and Blink of the DriverListEntry. Getting back to <code>MpEbEnumerateModules</code>, it will proceed to calculate the IndexHash value with the following algorithm</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"> WCHAR  upper;
 _QWORD IndexHash <span style="color:#ff79c6">=</span>  <span style="color:#bd93f9">0x4CB2F</span>;
 <span style="color:#ff79c6">while</span>(<span style="color:#ff79c6">*</span>DriverImageName.Buffer) {
     upper <span style="color:#ff79c6">=</span> RtlUpcaseUnicodeChar(<span style="color:#ff79c6">*</span>DriverImageName.Buffer);
     IndexHash <span style="color:#ff79c6">=</span> HIBYTE(upper) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (upper <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> IndexHash);
     DriverImageName.Buffer<span style="color:#ff79c6">++</span>;
 }</code></pre></div>
<p>This value will then be used to calculate the index of this <code>MODULE_ENTRY</code> in the <code>LoadedDriversArray</code> using the following algorithm:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"> <span style="color:#6272a4">// Thanks Hex-Rays :)
</span><span style="color:#6272a4"></span>DWROD size <span style="color:#ff79c6">=</span> (LoadedDriversArrayLen <span style="color:#ff79c6">&gt;&gt;</span> <span style="color:#bd93f9">5</span>) <span style="color:#ff79c6">-</span> <span style="color:#bd93f9">1</span>;
_QWORD tmp <span style="color:#ff79c6">=</span> IndexHash <span style="color:#ff79c6">&amp;</span> (<span style="color:#ff79c6">-</span><span style="color:#bd93f9">1</span> <span style="color:#ff79c6">&lt;&lt;</span> (LoadedDriversArrayLen <span style="color:#ff79c6">&amp;</span> <span style="color:#bd93f9">0x1F</span>))
_QWORD idx <span style="color:#ff79c6">=</span> (<span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE6(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE5(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE4(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE3(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE2(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE1(tmp) <span style="color:#ff79c6">+</span> 
              <span style="color:#bd93f9">0x25</span> <span style="color:#ff79c6">*</span> (BYTE(tmp) <span style="color:#ff79c6">+</span> <span style="color:#bd93f9">0xB15DCB</span>))))))) <span style="color:#ff79c6">+</span> HIBYTE(tmp)) <span style="color:#ff79c6">&amp;</span> size;</code></pre></div>
<blockquote>
<p>Try it yourself! (Using ASCII not Unicode) <a href="https://onlinegdb.com/BksOWHicH" target="_blank">https://onlinegdb.com/BksOWHicH</a></p>

<p>Please let me know if you recognize this algorithm, I couldn&rsquo;t find anything for the constants <code>0xB15DCB</code> and <code>0x4CB2F</code></p>
</blockquote>

<p>This non-sense will make more sense once when we see the BootDriver Callback routine. For now let&rsquo;s finish this function, since the size of the array may be shorter than the number of loaded modules there is chance to have collisions in the index value, that&rsquo;s when the member <code>SameIndexSlist</code> comes into play, this member will keep a single linked list (Is not really a SLIST_ENTRY because last entry doesn&rsquo;t point to NULL) for the Drivers which their computed index collide. And actually, the value saved in the <code>LoadedDriversArray</code> is a pointer to the <code>SameIndexSlist</code>. Then the function will check if the name of the module matches <code>WdFilter.sys</code> in the case it does it will set the WdFilterFlag and it will call <code>MpEbGetEntryPointSnapshot</code> which is the one that fills the member <code>EntryPointWdFilter</code> with the first 32 bytes from the <code>WdFilter</code> entrypoint. When it finishes doing this with every module, it will return from this function to the DriverEntry which will proceed to return STATUS_SUCCESS. That&rsquo;s pretty much how the initialization works, now let&rsquo;s get into the BootDriver Callback routine.</p>

<h2 id="mpebbootdrivercallback">MpEbBootDriverCallback</h2>

<p>This is probably the main function of WdBoot, this function will determine the classification of the Driver and of course depending on this the driver will be able to initialize or not. This function was registered previously with the call to <code>IoRegisterBootDriverCallback</code>. The prototype of this callback is provided by Microsoft in the <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-boot_driver_callback_function" target="_blank">WDK</a>.</p>

<pre><code>void BootDriverCallbackFunction(
  PVOID CallbackContext,
  BDCB_CALLBACK_TYPE Classification,
  PBDCB_IMAGE_INFORMATION ImageInformation
)
</code></pre>

<p>Both <code>BDCB_CALLBACK_TYPE</code> and <code>_BDCB_IMAGE_INFORMATION</code> are also included in the WDK, so I won&rsquo;t get much into them. First thing this function will check if the <code>BDCB_CALLBACK_TYPE</code> is set to <code>BdCbStatusUpdate</code> (This is basically a status update provided by the system to a boot-start driver), if it is, then it will check if the driver is classified as <code>BdCbClassificationKnownBadImage</code>, in this case it will set the value <code>ptrSlistEntry</code> of the global variable <code>MpEbGlobals</code>, then it will proceed to notify all callbacks registered for <a href="#WdEbNotificationCallback"><code>WdEbNotificationCallback</code></a> and in case the flag <code>FlagPersistElamInfo</code> is set, as the name implies, it will proceed to save the colected data (<code>MpEbPersistElamInformation</code>). I will not go into much detail on how it does this, but it will basically pack all the data from each <code>MODULE_ENTRY</code> and save it along with the SignaturesVersionMajor and SignaturesVersionMinor in the key with value <code>ElamInfo</code> inside <code>HKLM\SYSTEM\CurrentControlSet\Services\WdBoot</code>.</p>

<p>In the case the Classification is set to <code>BdCbInitializeImage</code>, then it will proceed to try and determine the <code>BDCB_CLASSIFICATION</code>. To do this, first thing the code will do is set the Classification to <code>BdCbClassificationUnknownImage</code>, then it will try to obtain the appropriate <code>MODULE_ENTRY</code>, the function in charge of doing this is <code>MpEbGetModuleEntry</code> and this is where the previous non-sense code will make sense. Since inside the structure <code>_BDCB_IMAGE_INFORMATION</code> we have the ImageName, the driver can calculate the IndexHash with the name and then retreive the actual index (And of course, iterate the <code>SameIndexSlist</code> if necessary)</p>

<blockquote>
<p>I&rsquo;m not an expert in optimization, but here is clear that this is much faster than iterating each memeber of the  <code>LoadedDriversArray</code> to compare the ImageName with the <code>DriverImageName</code> from each <code>MODULE_ENTRY</code>. And optimization is key in ELAM Drivers, Microsoft specifies some performance requirements that ELAM Drivers must meet.</p>
</blockquote>

<p>In case the <code>MODULE_ENTRY</code> is not found, then <code>MpEbBootDriverCallback</code> will proceed to create this entry with the function <code>MpEbAllocateDriverInfoEx2</code> and it will also compute the <code>IndexHash</code> and it will save the newly create entry in the <code>LoadedDriversArray</code>. Then, the function <code>MpEbCopyImageInformation</code> will finish filling the <code>MODULE_ENTRY</code>, from the name of the function is pretty clear what it does, it copies all the info from <code>_BDCB_IMAGE_INFORMATION</code> into the appropiate member of <code>MODULE_ENTRY</code>. Then the function in charge of deciding the Driver classification will be called (<code>EbLookupProperty</code>), this function will pass-through the parameters to <code>EbLookupPropertyEx</code>.</p>

<h4 id="eblookuppropertyex">EbLookupPropertyEx</h4>

<p>This is <strong>the</strong> function, the returning result from this function will determine the classification of the driver. It is a recursive function, that has different behaviour when being called by <code>MpEbBootDriverCallback</code> than when is being called recursively (Even the arguments types change). It will be easier to understand this function by looking at the decompiler code:</p>

<p><img src="/images/wdELAM/LookupProperty.png" alt="alt image" title="Lookup Property" /></p>

<p>First of all, the Tag value corresponds to the following enum:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c"><span style="color:#ff79c6">enum</span> LOOKUP_PROPERTY {
  CertThumbprintProperty <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">1</span>,
  CertPublisherProperty <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">2</span>,
  CertIssuerProperty <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">3</span>,
  ImageHashProperty <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">4</span>,
  EbBootDriverCallback <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">5</span>,
  EbRegistryCallback <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">6</span>
}</code></pre></div>
<p>As seen on the code, this is a recursive call which will try to match one of the following driver properties with the previously loaded signatures:</p>

<ul>
<li>Certificate Issuer</li>
<li>Certificate Publisher</li>
<li>Certificate Thumbprint</li>
<li>ImageHash</li>
</ul>

<p>So, basically when this function comes from <code>MpEbBootDriverCallback</code>, it will be called in the following way <code>EbLookupProperty(5, &amp;ModuleEntry-&gt;DriversListEntry, 0x90)</code>, which will lead to the first execution of the recursive lookup, since this execution Tag won&rsquo;t be <code>EbBootDriverCallback</code> and will be different from <code>EbRegistryCallback</code>, the function will prepare a <code>SIGNATURE_DATA</code> structure to call <code>MpBinarySearch</code>. As the name implies, this function will do a binary search to try and find a matching <code>SIGNATURE_DATA</code> in the array of signatures (Remember this array is kept in a global variable) in case it finds a match it will return the <code>SIGNATURE_DATA</code>. After this te recursive call returns with the signature classification, and here is where the collapsed if in the previous decompiled code does the magic:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c">SigClass <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0</span>; <span style="color:#6272a4">// KnownGoodImage
</span><span style="color:#6272a4"></span>ImageHashClass <span style="color:#ff79c6">=</span> EbLookupPropertyEx(<span style="color:#bd93f9">4</span>,...);
<span style="color:#ff79c6">if</span> (ImageHashClass) {
    SigClass <span style="color:#ff79c6">=</span> ImageHashClass;
}
<span style="color:#ff79c6">return</span> SigClass;</code></pre></div>
<p>So in the end, this function will return in <code>rax</code> one of the values from the <code>SIG_CLASS</code> enum. With this value we go back to <code>MpEbBootDriverCallback</code> where this value will be checked in the following way:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-c" data-lang="c">SigClass <span style="color:#ff79c6">=</span> EbLookupProperty(<span style="color:#bd93f9">5</span>,...);
<span style="color:#ff79c6">if</span> (SigClass) 
{
    <span style="color:#ff79c6">if</span> (SigClass <span style="color:#ff79c6">-</span> <span style="color:#bd93f9">1</span>) 
    {
        <span style="color:#8be9fd">int</span> tmp <span style="color:#ff79c6">=</span> SigClass <span style="color:#ff79c6">-</span> <span style="color:#bd93f9">2</span>; 
        <span style="color:#ff79c6">if</span> (<span style="color:#ff79c6">!</span>tmp <span style="color:#ff79c6">||</span> tmp <span style="color:#ff79c6">!=</span> <span style="color:#bd93f9">1</span>) 
        {
            ImageInformation<span style="color:#ff79c6">-&gt;</span>Classification <span style="color:#ff79c6">=</span> 
                        BdCbClassificationUnknown;
            ModuleEntry<span style="color:#ff79c6">-&gt;</span>DriverClassification <span style="color:#ff79c6">=</span>
                        BdCbClassificationUnknown;
        } 
        <span style="color:#ff79c6">else</span> 
        {
            ImageInformation<span style="color:#ff79c6">-&gt;</span>Classification <span style="color:#ff79c6">=</span> 
                        BdCbClassificationKnownBadImageBootCritical;
            ModuleEntry<span style="color:#ff79c6">-&gt;</span>DriverClassification <span style="color:#ff79c6">=</span>
                        BdCbClassificationKnownBadImageBootCritical;            
        }
    } 
    <span style="color:#ff79c6">else</span> 
    {
        ImageInformation<span style="color:#ff79c6">-&gt;</span>Classification <span style="color:#ff79c6">=</span> 
                    BdCbClassificationKnownBadImage;
        ModuleEntry<span style="color:#ff79c6">-&gt;</span>DriverClassification <span style="color:#ff79c6">=</span>
                    BdCbClassificationKnownBadImage;
    }
} 
<span style="color:#ff79c6">else</span> 
{
    ImageInformation<span style="color:#ff79c6">-&gt;</span>Classification <span style="color:#ff79c6">=</span> 
                BdCbClassificationKnownGoodImage;
    ModuleEntry<span style="color:#ff79c6">-&gt;</span>DriverClassification <span style="color:#ff79c6">=</span> 
                BdCbClassificationKnownGoodImage;
}</code></pre></div>
<p>If you check the <code>BDCB_CLASSIFICATION</code> you&rsquo;ll see that there&rsquo;s a bit of a mismatch between the returned value and the value assigned to Classification:</p>

<ul>
<li>LookupProperty return 0 == Assign BDCB_CLASSIFICATION 1 (KnownGoodImage)</li>
<li>LookupProperty return 1 == Assign BDCB_CLASSIFICATION 2 (KnownBadImage)</li>
<li>LookupProperty return 3 == Assign BDCB_CLASSIFICATION 3 (BadImageBootCritical)</li>
<li>LookupProperty return 4 == Assign BDCB_CLASSIFICATION 0 (UnknownImage)</li>
</ul>

<p>There&rsquo;s one last situation, when the driver that&rsquo;s going to be initialized is <code>WdFilter</code> in this case the callback will again get the first 32 bytes of <code>WdFilter</code> and compare them agains the ones obtained previously in the initialization of the <code>WdBoot</code>, in case there&rsquo;s a mismatch the entrypoint will be restored to it&rsquo;s original, the member <code>ModuleEntry-&gt;DriverClassification</code> will be set to 6 (Probably a classification that indicates that some driver tried to modify this Driver) and lastly the flag <code>FlagPersistElamInfo</code> will be set (Of course this will be logged through WPP).</p>

<p><img src="/images/wdELAM/CheckWdFilter.png" alt="alt image" title="Check WdFilter" /></p>

<p>Finally, this routine will link the <code>DriversListEntry</code> from the <code>MpEbGlobals</code> variable with the <code>DriversListEntry</code> from each <code>MODULE_ENTRY</code>. And it will add up the corresponding value to the <code>TotalModulesEntryLength</code>, this value is the sum of the lengths of various components of the <code>MODULE_ENTRY</code> and it will only be used in case the ELAM info is persisted, to know the size they must allocate for the data (Take into account that the info is only saved on BdCbStatusUpdate, and here we don&rsquo;t have the <code>MODULE_ENTRY</code> info so the code needs a way to know how much data it needs to allocate, that&rsquo;s why this value is saved as a global variable).</p>

<p><img src="/images/wdELAM/LinkedList.png" alt="alt image" title="Linked List" /></p>

<h2 id="conclusions">Conclusions</h2>

<p>And that&rsquo;s more or less how the Windows Defender ELAM driver works. A couple more things regarding this technology. First of all, it doesn&rsquo;t provide security again bootkits (There are other things for that, but not ELAM), also ELAM drivers must be signed with the Early Launch EKU &ldquo;1.3.6.1.4.1.311.61.4.1&rdquo; and only Microsoft can sign certificates with this signature and only Anti-Malware vendors qualify for it so is not really something for general use. Finally the default policy is set to <code>PNP_INITIALIZE_BAD_CRITICAL_DRIVERS</code>, which means Unknown and BadButCritical drivers will be allowed to initialize this can be changed in the registry</p>

<blockquote>
<p><code>HKLM\System\CurrentControlSet\Control\EarlyLaunch\DriverLoadPolicy</code></p>
</blockquote>

<p>One last thing, Microsoft provides a sample ELAM code that can be found here <a href="https://github.com/Microsoft/Windows-driver-samples/tree/master/security/elam" target="_blank">https://github.com/Microsoft/Windows-driver-samples/tree/master/security/elam</a> make sure to check it out! They use WDF which is quite cool (Even thou the WdBoot uses WDM 😅)</p>

<p>So, that&rsquo;s all folks. As always I really hope you learnt something and managed to get an overview on how Microsoft implemented their ELAM Driver. Feel free to contact me regarding any questions or any mistakes you may find. And thank you for reading this extra-long post! :)</p>

<h3 id="a-name-wdebnotificationcallback-a-bonus-wdebnotificationcallback"><a name="WdEbNotificationCallback"></a> Bonus: WdEbNotificationCallback</h3>

<p>In this section I will explain a bit on what happens when the <code>WdEbNotificationCallback</code> is notified, which driver register for this callback and what parameters it receives.</p>

<blockquote>
<p>If you are interested in ExecutiveCallbackObjects and want to dig more into them, make sure to check the investigation <a href="https://twitter.com/0xcpu" target="_blank">0xcpu</a> and me are doing on them (And feel free to contribute)</p>

<p><a href="https://github.com/0xcpu/ExecutiveCallbackObjects" target="_blank">https://github.com/0xcpu/ExecutiveCallbackObjects</a></p>
</blockquote>

<p>As we saw before, this callback is notified inside the <code>MpEbBootDriverCallback</code> when the <code>BDCB_CALLBACK_TYPE</code> is set to <code>BdCbStatusUpdate</code> and the <code>_BDCB_IMAGE_INFORMATION</code> specifies the driver as <code>BdCbClassificationKnownBadImage</code>. When this happens, then the function <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-exnotifycallback" target="_blank"><code>ExNotifyCallback</code></a> is executed</p>

<blockquote>
<p>This function notifies every registered routine for the callback object that is specified as the first parameter. Parameter two and three will be passed to the callback routine as Argument1 and Argument2.</p>
</blockquote>

<p>If we search for occurrences of the string <code>\Callback\WdEbNotificationCallback</code> inside <code>Systemroot\System32</code>, we will see besides <code>WdBoot</code> we also find a match on <code>WdFilter</code>. So cross-referencing this string on <code>WdFilter</code> we can find that function <code>MpInitializeDriverInfo</code> is registering the function <code>MpBootDriverCallback</code> for this callback object (<a href="https://docs.microsoft.com/en-gb/windows-hardware/drivers/ddi/wdm/nf-wdm-exregistercallback" target="_blank"><code>ExRegisterCallback</code></a>). So let&rsquo;s take a quick look into the function <code>MpBootDriverCallback</code>:</p>

<p><img src="/images/wdELAM/MpBootDriverCallback.png" alt="alt image" title="MpBootDriverCallback" /></p>

<p>As we can see they are checking both Argument1 and Argument2, to make sure the notification comes from <code>WdBoot</code> and not from some other driver trying to impersonate this notification.</p>

<blockquote>
<p><img src="/images/wdELAM/ExNotifyCallback.png" alt="alt image" title="ExNotifyCallback" /></p>
</blockquote>

<p>Actually, Argument1 is a pointer to the <code>Magic</code> member of the <code>MP_EP_GLOBALS</code> structure. With this pointer, is pretty simple for <code>WdFilter</code> to use the <code>DriversListEntry</code> to iterate over the loaded drivers and get the information from the <code>MODULE_ENTRY</code> structure. And in fact, <code>MpCopyDriverEntry</code> does this and saves a local copy of the loaded drivers, creating another list entry that will be used afterwards in the function <code>MpQueryLoadedDrivers</code>. For now I&rsquo;ll leave it here because we have plans on doing a full research on <code>WdFilter</code> where we will explain this and much more.</p>
]]></content></item><item><title>Transition from an EFI Bootloader to the Kernel in Windows x64</title><link>https://n4r1b.com/posts/2019/09/transition-from-an-efi-bootloader-to-the-kernel-in-windows-x64/</link><pubDate>Wed, 18 Sep 2019 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2019/09/transition-from-an-efi-bootloader-to-the-kernel-in-windows-x64/</guid><description>In my previous post I explained how the Bootloader loads the essential Drivers so the Kernel can run. On that post I mentioned how the Bootloader has two main tasks. First task is to load the OS into memory and the second task is to manage the transition from the Bootloader to this recently loaded OS. I roughly explained first task. And I thought it could be interesting to give a little overview on how the second task is done.</description><content type="html"><![CDATA[

<p>In my previous post I explained how the Bootloader loads the essential Drivers so the Kernel can run. On that post I mentioned how the Bootloader has two main tasks. First task is to load the OS into memory and the second task is to manage the transition from the Bootloader to this recently loaded OS. I roughly explained first task. And I thought it could be interesting to give a little overview on how the second task is done. So, here we go!</p>

<p>This task is done by the function <code>OslExecuteTransition</code>, specifically <code>OslArchTransferToKernel</code>. In the following image you can see the decompiled code of this function:</p>

<p><img src="/images/transKernel/transfer_2_kernel.jpg" alt="OslArchTransferToKernel" style="margin:auto;"/></p>

<p>First instruction basically stands for <a href="https://www.felixcloutier.com/x86/wbinvd" target="_blank"><em>Write back and Invalidate Cache</em></a> and basically writes back modified cache lines to main memory and invalidates the internals caches. Next, the corresponding values are assigned to the GDTR(<code>lgdt</code>) and the IDTR(<code>lidt</code>), then the following bits from <a href="https://en.wikipedia.org/wiki/Control_register#CR4" target="_blank">CR4</a> are set:</p>

<ul>
<li>Bit 7: Page Global Enabled</li>
<li>Bit 9: OSFXSR</li>
<li>Bit 10: OSXMMEXCPT</li>
</ul>

<p>The same is done with the following bits of <a href="https://en.wikipedia.org/wiki/Control_register#CR0" target="_blank">CR0</a>:</p>

<ul>
<li>Bit 5: Numeric error</li>
<li>Bit 16: Write protect</li>
<li>Bit 18: Alignment mask</li>
</ul>

<p>and the bits 0 (System call Extensions) and 8 (Long Mode Enable) from the <a href="https://en.wikipedia.org/wiki/Control_register#EFER" target="_blank">EFER</a>(This value is obtained reading the MSR <code>0xC0000080</code>). Being in a x64 machine we have the new <a href="https://en.wikipedia.org/wiki/Control_register#CR8" target="_blank">CR8</a> which prioritize external interrupts, this value is set to zero which means no external interruptions will be prioritized. Lastly the selector pointed by <a href="https://en.wikipedia.org/wiki/Task_state_segment" target="_blank">TSS</a> to the register TR, and after this everything is ready to execute the <em>far return</em> (Previously the EIP of the kernel and the <em>Segment Selector</em> of type Code and CPL 0 have been pushed to the stack).</p>

<blockquote>
<p>The far return takes the IP and the CS from the stack, that&rsquo;s why those values where pushed into it. The instruction <code>retfq</code> is used instead of the instruction <code>retf</code> because the Bootloader runs in Long Mode, this means that each entry in the stack is 64 bits long, so in order to retrieve the IP and the CS from the stack it needs to read 64 bits not 32 bits.</p>
</blockquote>

<p><img src="/images/transKernel/transition_retfq.jpg" alt="alt img" title="retfq transition" /></p>

<p>As indicated in the Chapter 7 of the <a href="https://uefi.org/specifications" target="_blank"><strong>UEFI Specification v2.8</strong></a>, if the load of the OS was successful then the UEFI Loader can call the function <code>ExitBootService</code> which frees all the EFI Drivers of type <code>EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER</code>, if this call returns <code>EFI_SUCCESS</code> then the UEFI Loader owns all available memory in the system and is also responsible for system execution to continue. The EFI Drivers of type <code>EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER</code> are kept in memory and can be used with paging and virtual addresses as long as the service has described all the virtual space it will use by calling to the function <code>SetVirtualAddressMap</code>. Having in mind that <strong>Winload.efi</strong> is a UEFI Loader, logically it has to take charge of everything I just said. And it does! Inside the function <code>OslExecuteTransition</code> the first function getting called is <code>OslFwpKernelSetupPhase1</code> which is in charge of doing what I explained previoulsy. This function only receive one parameter (The <code>LOADER_PARAMETER_BLOCK</code>)</p>

<p><img src="/images/transKernel/ExitBootService.jpg" alt="ExitBootService" style="margin:auto;"/></p>

<p>this function also sets does the mapping of the physical to the virtual addresses, as explained before, calling <code>SetVirtualAddressMap</code>. (<strong>NOTE:</strong> The member <em>EfiInformation</em> seen in the following picture doesn&rsquo;t have that name, corresponds to the last member of the structure <code>_FIRMWARE_INFORMATION_LOADER_BLOCK</code> and in the symbols it shows as <code>u</code>. I coined that name because it contains the structure <code>_EFI_FIRMWARE_INFORMATION</code>)</p>

<p><img src="/images/transKernel/SetVirtualAddress.jpg" alt="alt img" title="SetVirtualAddressMap" /></p>

<blockquote>
<p><strong>Curious fact:</strong> Quarkslab presented a POC of a Bootkit in 2013, <a href="https://github.com/quarkslab/dreamboot" target="_blank">Dreamboot</a> which relies on hooking the function <code>OslArchTransferToKernel</code>. At this point, in memory we can find all the structures the kernel needs to work by itself, so clearly is a good moment to have a &ldquo;hook&rdquo;</p>

<p>More info on their paper (French) <a href="https://www.sstic.org/media/SSTIC2013/SSTIC-actes/dreamboot_et_uefi/SSTIC2013-Article-dreamboot_et_uefi-kaczmarek.pdf" target="_blank">https://www.sstic.org/media/SSTIC2013/SSTIC-actes/dreamboot_et_uefi/SSTIC2013-Article-dreamboot_et_uefi-kaczmarek.pdf</a></p>
</blockquote>

<h2 id="conclusions">Conclusions</h2>

<p>This is a big overview, I skipped a lot of stuff that&rsquo;s going on inside <code>OslFwpKernelSetupPhase1</code> I just wanted to explain in a &ldquo;simple&rdquo; way how this goes and the role UEFI plays in all this. On the other hand, I still need to read the book <em>Rootkits and Bootkits</em> by Alex Matrosov, Eugene Rodionov, and Sergey Bratus, but I&rsquo;m pretty sure they explain all this much better and detailed, so I believe it should be a good read for everyone interested on this topic (Also the UEFI Specification is an incredible source of knowledge). As always, I hope you enjoyed and feel free to contact me to discuss more or if there&rsquo;s any mistake</p>
]]></content></item><item><title>How does the OS Loader loads the essential Drivers</title><link>https://n4r1b.com/posts/2019/03/how-does-the-os-loader-loads-the-essential-drivers/</link><pubDate>Tue, 26 Mar 2019 00:00:00 +0000</pubDate><guid>https://n4r1b.com/posts/2019/03/how-does-the-os-loader-loads-the-essential-drivers/</guid><description>Welcome back! This time we are going to see something previous to the Kernel (Yes! There is something before the Kernel 😅), specifically we are going to check how the OS Loader loads some essential Drivers into memory. To the research I&amp;rsquo;m going to focus on the Early Launch Anti-Malware (ELAM) Driver. The main motivation to focus on this Driver is that on a near future I would like to write a post on going on depth on how the ELAM Driver works and how it helps protect the system from possible Rootkits.</description><content type="html"><![CDATA[

<p>Welcome back! This time we are going to see something previous to the Kernel (Yes! There is something before the Kernel 😅), specifically we are going to check how the OS Loader loads some essential Drivers into memory. To the research I&rsquo;m going to focus on the Early Launch Anti-Malware (ELAM) Driver. The main motivation to focus on this Driver is that on a near future I would like to write a post on going on depth on how the ELAM Driver works and how it helps protect the system from possible Rootkits.</p>

<h2 id="os-loader">OS Loader</h2>

<p>First the Boot Manager will write the OS Loader into memory and give control to it, which will be in charge of loading the Windows Kernel once it finishes this process the loading phases will be done and the control will be given to the Kernel, and from this point onward we can say we are actually on Windows.</p>

<p>To be able to debug the OS Loader we need to activate the <code>/bootdebug</code> option of the Windows Bootloader entry inside the <strong>Boot Configuration Data (BCD)</strong>, to do this Windows provides a program call <code>bcdedit.exe</code> which will allow us to change the Boot Configuration. After we done this if we reboot the system with a remote debugging session attached to it we will break inside the OS Loader, more specifically inside the function <code>BlBdStart</code> which is the function in charge of checking the connection to the remote machine and loading the symbols to be able to debug <code>DbgLoadImageSymbols</code>. This function comes from <code>BlBdInitalize</code> which as the name implies is in charge of initializing everything necessary to debug (I guess the BlBd prefix meand Bootloader BootDebug). An going up on the call stack again we end up on <code>InitializeLibrary</code> which is the function that does everything necessary for the Bootloader to be able to execute, here we find functions like:</p>

<ul>
<li><code>PltInitializePciConfiguration</code></li>
<li><code>SpaceBootInitialize</code></li>
<li><code>BlNetInitialize</code></li>
<li><code>BlpIoInitialize</code></li>
</ul>

<p>Names are pretry self explanatory so I will not get into more details (but feel free to check them!). Going forward with the execution we will get into the main code of the Bootloader (<code>OslMain</code>) and his private version <code>OslpMain</code> (Actually where all the &ldquo;magic&rdquo; will happen)</p>

<p>This function has to perform two tasks, the first one loads the OS (<code>OslPrepareTarget</code>) and the second perform the transition to the loaded OS (<code>OslExecuteTransition</code>). In this post I will only talks about the first function roughly, as you can imagine it has a lot of code 🤣. The Kernel loading process may vary depending on the options that are activated in the <strong>BCD</strong> and to determine if an option is active the function <code>BcdUtilGetBootOption</code> will be used, this function is used quite a lot so we will see a bit on how it works:</p>

<p><img src="/images/oslLoadDrivers/bcdGetOption.jpg" alt="BcdUtilGetBootOption pseudocode" style="margin:auto;"/></p>

<p>As you can see, it will walk a structure and compare if the type that is being looked (Let&rsquo;s understand type as option) is among the options of the boot configuration. The structure is the following (All credit to <a href="https://doxygen.reactos.org/d5/d8b/struct__BL__BCD__OPTION.html" target="_blank">ReactOS</a>)</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#ff79c6">struct</span> _BL_BCD_OPTION
{
  ULONG Type;
  ULONG DataOffset;
  ULONG DataSize;
  ULONG ListOffset;
  ULONG NextEntryOffset;
  ULONG Active;
};
</code></pre></div>
<blockquote>
<p>If we want to the get the name of one of the constants we can try an search on the <a href="https://docs.microsoft.com/en-us/windows/security/information-protection/bitlocker/bcd-settings-and-bitlocker" target="_blank">Microsoft documentation</a> and if it&rsquo;s not there probably Geoff Chappell has it on his <strong>incredible</strong> <a href="https://www.geoffchappell.com/notes/windows/boot/bcd/elements.htm" target="_blank">documentation</a>)</p>
</blockquote>

<h2 id="oslploadallmodules">OslpLoadAllModules</h2>

<p>Allow me to fast-forward directly to one of the main functions in the Bootloader <code>OslpLoadAllModules</code>, believe me, this function does <strong>a lot</strong> I&rsquo;ll try to resume it to get into the point that concern us.</p>

<p>First it gets the boot flags (<code>OslpGetBootDriverFlags</code>), with this it will check a couple of things. First if the 5-level paging is active, if is the case the Bootloader will load the followinf kernel <strong>ntkrla57.exe</strong>. Then it will check the flags <code>BCDE_OSLOADER_TYPE_KERNEL_PATH</code> and <code>BCDE_OSLOADER_TYPE_HAL_PATH</code>, if they are set it will load the values from the flag (This value is a string). Finally, it will check the arch of the machine to see if it has to load any microcode update for the arch.</p>

<blockquote>
<p>This drivers have the name <strong>mcupdate_[OsArch]</strong> basically they contain microcode updates specif for the CPU. If you check on your PC and you see that the modification date of the one corresponding to your arch is different to the other. Then probably a KB updated the Driver that matches your arch (Ex. <a href="https://support.microsoft.com/en-us/help/4465065/kb4465065-intel-microcode-updates" target="_blank">https://support.microsoft.com/en-us/help/4465065/kb4465065-intel-microcode-updates</a>)</p>
</blockquote>

<p>Next the function will allocate space for Kernel and the Hal, and both are loaded by calling <code>OslLoadImage</code>. Then the api schema is loaded, for this the <code>.apiset</code> section is obtained from the DLL <code>apisetschema.dll</code>, and with this section the schema is created (<code>ApiSetCreateSchema</code>) and written (<code>ApiSetComposeSchema</code>). At this point if the KD is active the DLLs necessary will be loaded and the <em>LastGoodSettingFlag</em> is checked if the jump is not taken the Bootloeader proceed to load the <em>mcupdate.dll</em>. One last step before loading the Drivers is to load the OS extensions, to do this the Bootloader search the signature <em>CSRT</em> in the ACPI table</p>

<blockquote>
<p>This signature corresponds with the table <em>Core System Resources Table</em>, and if the system has any <em>Core System Resource</em> (DMA Controllers, Interrup Controller, etc&hellip;) which is non-standard then it must be indicated on this table and therefore the table <em>Root System Description Table</em> (RSDT) must have a pointer to this <em>System Description Tables</em> (SDT).
More info on this table <a href="https://uefi.org/sites/default/files/resources/CSRT%20v2.pdf" target="_blank">here</a></p>
</blockquote>

<p>Lastly, <em>ntoskrnl.exe</em> and <em>hal.dll</em> import functions from other Drivers, and these need to be loaded. In the end, this is how the member <em>LoadOrderListHead</em> of the <a href="#loader_param_block_notes"><code>LOADER_PARAMETER_BLOCK</code></a> looked (At the point I was investigating this I was running Windows 10 version 1809)</p>

<p><img src="/images/oslLoadDrivers/modules_loaded_before_drivers.jpg" alt="LoadOrderListHead" style="margin:auto;"/></p>

<blockquote>
<p>When debuging this neither <code>OslLoadImage</code> nor <code>OslLoadDrivers</code> load the symbols (They don&rsquo;t call <code>DbgLoadImageSymbols</code>) so we won&rsquo;t have their symbols in the debugger, and to be honest <strong>nt</strong> symbols are quite handy 🤣. WinDbg give us the option to load the symbols if we know the ImageBase which we can get from the <code>LOADER_PARAMETER_BLOCK</code>.
The command is <code>.reload /f /i [ModuleName]=[ModuleImageBase]</code></p>

<video style="margin-top:10px" width="100%" controls>
  <source src="/videos/oslLoadDrivers/video_reload.mov" type="video/mp4">
</video>
</blockquote>

<h1 id="loading-the-drivers">Loading the Drivers</h1>

<p>Finally! How the essential Drivers are loaded. We are still on the function <code>OslpLoadAllModules</code> (As I mentioned in the beginning, I will focus on the ELAM Driver but the process can be extrapolated to other Drivers if there&rsquo;s anything exclusive from the ELAM I will mention it)</p>

<p>The first function necessary to load the drivers is <code>OslGetBootDrivers</code>, the first thing it will do is get the list of Drivers to load, this list is obtained within the function <code>OslHiveFindDrivers</code>, which mainly calls <code>CmpFindDrivers</code>. This function loads the Data Cell (<code>_CELL_DATA</code>) of the <em>Service</em> key inside the <em>CurrentControlSet</em>, with this cell the code iterate the <em>Service</em> key and the function <code>CmpIsLoadType</code> will check if each entry has the <em>Start</em> key with value equals <code>0x0</code>, if so, the <code>_BOOT_DRIVER_LIST_ENTRY</code> is initialized by calling <code>CmpAddDriverToList</code>, this function basically reads the data from the entry and fills in the structure. This goes on with all the elements within <code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services</code> and finally we will have the member <em>BootDriverListHead</em> of the <code>LOADER_PARAMETER_BLOCK</code> with all the essentials drivers to be loaded.</p>

<blockquote>
<p>I didn&rsquo;t manage to find the complete structure of the member <em>BootDriverListHead</em> anywhere (If anyone knows it please contact me!). The most similar structure is the <a href="https://doxygen.reactos.org/d2/d92/struct__BOOT__DRIVER__LIST__ENTRY.html" target="_blank">_BOOT_DRIVER_LIST_ENTRY</a> from ReactOS. But I&rsquo;m not sure if Microsft added more values or maybe I&rsquo;m mistaken. Based on what I saw, it would be something like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#ff79c6">struct</span> _BOOT_DRIVER_LIST_ENTRY 
{
    LIST_ENTRY Link;
    UNICODE_STRING PathToDriver;
    UNICODE_STRING RegistryPath;
    PLDR_DATA_TABLE_ENTRY DriverLdrTableEntry;
    ULONG DriverLoadNtStatus;
    ULONG Unknown; <span style="color:#6272a4">/* It&#39;s obtained in the function ImgpValidateImageHash, 
</span><span style="color:#6272a4">                      probably related with some integitry check, please contact me
</span><span style="color:#6272a4">                      if you have more info */</span>  
    PHHIVE Hive;
    UNICODE_STRING HiveName;
    UNICODE_STRING DriverDependencies;
    UNICODE_STRING DriverGroup;
    UNICODE_STRING DriverRootName;
    ULONG DriverTag;
    ULONG DriverErrorControl;
}
</code></pre></div></blockquote>

<p>Next, the dependencies for this Drivers will be added to the <code>_BOOT_DRIVER_LIST_ENTRY</code> (Checking the subkey <em>PendingDriverOperations</em>). Finally, the function <code>CmpSortDriverList</code> will sort the Drivers based on the value <em>List</em> from the subkey <em>ServiceGroupOrder</em> within the key <em>Control</em> (This Data Cell was previously loaded).</p>

<blockquote>
<p>This is explained (Better than me) by Microsoft in the following artice <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/install/specifying-driver-load-order" target="_blank">https://docs.microsoft.com/en-us/windows-hardware/drivers/install/specifying-driver-load-order</a></p>
</blockquote>

<p>The list would end up like this (Command: <code>r @$t0=[Addr BootDriverList]; r @$t1=[Addr BootDriverList.Link]; .while(@$t0 != @$t1) {dS /c 80 @$t1+10; r @$t1=poi(@$t1)}</code> the command <code>!list</code> would make this easier)</p>

<p><img src="/images/oslLoadDrivers/BootOrderedList.jpg" alt="alt img" title="Boot Ordered List" /></p>

<p>Two filters will be applied to this list, one by Group (<code>OslpFilterDriverListOnGroup</code>), this one will receive the string <strong>Early-Launch</strong>, which will copy the ELAM Driver from the <em>BootDriverListHead</em> to the <em>EarlyLaunchListHead</em>. In the image it can be seen how the Driver <strong>WdBoot.sys</strong> (Windows Defender ELAM) belongs to the group Early-Launch.</p>

<p><img src="/images/oslLoadDrivers/wdboot.jpg" alt="alt img" title="Boot Ordered List" /></p>

<p>The second filter is based on the Service (<code>OslpFilterDriverListOnServices</code>), this one is applied multiple times. First time to copy the <strong>Core Drivers</strong> to the <em>CoreDriverListHead</em>, second time to copy the <strong>TmpCoreDrivers</strong> and lastly to copy the <strong>Extension Drivers</strong>. Now Everything is ready to load the Drivers.</p>

<blockquote>
<p>To get the Core Drivers the <strong>DriverRootName</strong> is compared against the following list (Within the .rdata of the binary):</p>

<ul>
<li>VERIFIEREXT</li>
<li>WDF01000</li>
<li>ACPIEX</li>
<li>CNG</li>
<li>MSSECFLT</li>
<li>SGRMAGENT</li>
<li>LXSS</li>
<li>PALCORE</li>
</ul>
</blockquote>

<h3 id="oslloaddrivers">OslLoadDrivers</h3>

<p>The first Driver that will be loaded are the <strong>Core Drivers</strong>, then the <strong>TmpCore Drivers</strong>, next the <strong>ELAM Drivers</strong>. Before loading the ELAM Driver the Bootloader checks that the boot flag <code>0x260000E1</code>(BCDE_OSLOADER_TYPE_DISABLE_ELAM_DRIVERS) is not active, if the option is active it disable the loading of ELAM Drivers. In our case is not active so the function <code>OslLoadDrivers</code> is called, this function generates the full path to the Driver (<code>BlLdrBuildImagePath</code>) and calls <code>OslLoadImage</code>, from here we start going deeper into functions (With the same parameters) until we get to <code>LdrpLoadImage</code>:</p>

<p><img src="/images/oslLoadDrivers/stack_osload.jpg" alt="alt img" title="Call Stack OS Load" /></p>

<p>This function first check if the Driver is already in the <code>LDR_DATA_TABLE</code> (Basically the function <code>BlLdrFindDataTableEntry</code> iterate the table and check if the name of the Driver is already there). In case the Driver is not found in the table, the <em>Flags</em> of the Driver will be processed with the function <code>OslpLdrExProcesssImageFlags</code> (This function is obtained from some kind of vTable that contains functions that help in the loading process)</p>

<p><img src="/images/oslLoadDrivers/vtable.jpg" alt="alt img" title="Load Process vTable" /></p>

<p>After the <em>Flags</em> had been processed, the Driver will be load into memory using the function <code>BlImgLoadPEImageEx</code>. This function will obtain a <em>&ldquo;handle&rdquo;</em> to the file calling <code>ImgpOpenFile</code></p>

<blockquote>
<p>I call this Handle but really is a structure, in ReactOS they call this structure <a href="https://doxygen.reactos.org/d4/d94/struct__BL__IMG__FILE.html" target="_blank"><code>_BL_IMG_FILE</code></a>, and betweent other things it contains the <em>FileName</em> and the <em>FileSize</em></p>
</blockquote>

<p>with this handle the function <code>ImgpLoadPEImage</code> will be executed. This will load the PE, the steps are the normal steps to load a PE (<strong>NOTE:</strong> I will not get into al the Digital Signature and Checksum stuff, is to complex for me, I need to investigate more about it to not mess it up). The atributes of the file are retrieved with a call to <code>BlFileGetInformation</code>, then the NT header will loaded and three things will be checked:</p>

<ul>
<li>ntHeaders-&gt;FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64</li>
<li>ntHeaders-&gt;OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION</li>
<li>ntHeaders-&gt;OptionalHeader.DllCharacteristics &amp; IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY</li>
</ul>

<p>if those are met, the type of hash for the integrity is obtained (<code>0x8004</code> -&gt; <code>CALG_SHA_256</code>), then the virtual size of the image is allocated and the sections are copied. When the image is mapped in memory the digest is checked and then the image is relocated <code>LdrRelocateImage</code> and finally the physical address of the image is obtained (Not sure why it does this thou)</p>

<p><img src="/images/oslLoadDrivers/physical_address.jpg" alt="alt img" title="Physical Address Image" /></p>

<p>To finish, the <em>SymbolicPath</em> and the loaded Driver is added to the <code>LDR_TABLE_ENTRY</code>, at this point doing this is trivial, all the info to do this is accesible, the function in charge of doing this is <code>BlLdrAllocateDataTableEntry</code> and since a picture is worth a thousands words:</p>

<p><img src="/images/oslLoadDrivers/add_data_table_entry.jpg" alt="alt img" title="Add entry LDR_TABLE" /></p>

<p>the <code>LIST_ENTRY</code> of the new entry will be linked and the imports of the Driver will be loaded <code>LdrpLoadImports</code> and they will be binded through the call to <code>BlLdrBindImportReferences</code>. And that&rsquo;s pretty much all (Roughly, but I guess if you are reading this you have IDA 😉). Now the code will start returning until <code>OslLoadDrivers</code> where the member <em>DriverLoadNtStatus</em> will be set and the <em>NTSTATUS</em> is returned.</p>

<p>A picture of how the <code>_BOOT_DRIVER_LIST_ENTRY</code> would end up looking after the Windows Defender ELAM is loaded (The member <em>DriverTag</em> is 0xFFFFFFFF because the WdBoot Driver doesn&rsquo;t have this key on the registry):</p>

<p><img src="/images/oslLoadDrivers/boot_driver_entry.jpg" alt="alt img" title="Boot Driver entry" /></p>

<h2 id="conclusions">Conclusions</h2>

<p>That&rsquo;s all folks, I&rsquo;ll leave some notes down below to explain some things a bit more in depth. As I mention if I have time I would like to talk about the WD ELAM Driver in the next entry. I hope I&rsquo;ve raised some curiosity and I encourage you to research more because there&rsquo;s still a lot that I didn&rsquo;t mention.</p>

<p>As always, I hope you liked the post. If something is not clear feel free to contact me I&rsquo;m always willing to discuss stuff related to the Bootloade/Kernel and &ndash; It&rsquo;s free!!. I know I left a lot of things aside, sorry for that, but believe me th Bootloeader has A LOT of code and also a lot of complex things. And lastly, if I made a mistake, please contact me so I can fix it, I&rsquo;m open to any critics 😊.</p>

<h2 id="notes">Notes</h2>

<p><a name="loader_param_block_notes"></p>

<h4 id="loader-parameter-block">LOADER_PARAMETER_BLOCK</h4>

<p></a>
The <a href="https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/loader_parameter_block.htm" target="_blank"><code>LOADER_PARAMETER_BLOCK</code></a> is probably the most important structure in the Bootloeader. This structure will be collecting critical information during the loading of the OS, later all this information will passed to the kernel (A reference to this structure is saved in the variable <code>KeLoaderBlock</code>). Thankfully, since version <strong>Windows 10 1803 Redstone 4 (Spring Creators Update)</strong> Microsoft released the prototype of this structure in a header file (Before it was in the symbols but not in a header file)</p>

<pre><code>kd&gt; dt nt!_LOADER_PARAMETER_BLOCK
   +0x000 OsMajorVersion   : Uint4B
   +0x004 OsMinorVersion   : Uint4B
   +0x008 Size             : Uint4B
   +0x00c OsLoaderSecurityVersion : Uint4B
   +0x010 LoadOrderListHead : _LIST_ENTRY
   +0x020 MemoryDescriptorListHead : _LIST_ENTRY
   +0x030 BootDriverListHead : _LIST_ENTRY
   +0x040 EarlyLaunchListHead : _LIST_ENTRY
   +0x050 CoreDriverListHead : _LIST_ENTRY
   +0x060 CoreExtensionsDriverListHead : _LIST_ENTRY
   +0x070 TpmCoreDriverListHead : _LIST_ENTRY
   +0x080 KernelStack      : Uint8B
   +0x088 Prcb             : Uint8B
   +0x090 Process          : Uint8B
   +0x098 Thread           : Uint8B
   +0x0a0 KernelStackSize  : Uint4B
   +0x0a4 RegistryLength   : Uint4B
   +0x0a8 RegistryBase     : Ptr64 Void
   +0x0b0 ConfigurationRoot : Ptr64 _CONFIGURATION_COMPONENT_DATA
   +0x0b8 ArcBootDeviceName : Ptr64 Char
   +0x0c0 ArcHalDeviceName : Ptr64 Char
   +0x0c8 NtBootPathName   : Ptr64 Char
   +0x0d0 NtHalPathName    : Ptr64 Char
   +0x0d8 LoadOptions      : Ptr64 Char
   +0x0e0 NlsData          : Ptr64 _NLS_DATA_BLOCK
   +0x0e8 ArcDiskInformation : Ptr64 _ARC_DISK_INFORMATION
   +0x0f0 Extension        : Ptr64 _LOADER_PARAMETER_EXTENSION
   +0x0f8 u                : &lt;unnamed-tag&gt;
   +0x108 FirmwareInformation : _FIRMWARE_INFORMATION_LOADER_BLOCK
   +0x148 OsBootstatPathName : Ptr64 Char
   +0x150 ArcOSDataDeviceName : Ptr64 Char
   +0x158 ArcWindowsSysPartName : Ptr64 Char
</code></pre>

<p>This applies to <strong>Windows 10 Kernel Version 17763.1.amd64fre.rs5_release.180914-1434</strong> and <a href="https://www.vergiliusproject.com/kernels/x64/Windows%2010%20%7C%202016/1809%20Redstone%205%20(October%20Update)/_LOADER_PARAMETER_BLOCK" target="_blank">here</a> you can find it as a C struct.</p>

<p><a name="system_hive_notes"></p>

<h4 id="systemhive">SystemHive</h4>

<p></a>
The function in charge of loading the System <a href="https://docs.microsoft.com/en-us/windows/desktop/sysinfo/registry-hives" target="_blank">Hive</a> is <code>OslpLoadSystemHive</code>, it receives the parameters:</p>

<ul>
<li>A <strong>DeviceID</strong> which represents an index in the table <code>DmDeviceTable</code>, table that contains the open <em>devices</em> (<a href="#device_notes">Notes DeviceId</a>)</li>
<li>A <code>UNICODE_STRING</code> with the path of the system root (Obtained with the function <code>OslpInitializeSystemRoot</code>)</li>
<li>A pointer to the <code>LOADER_PARAMETER_BLOCK</code></li>
</ul>

<p>This function will generate three strings with the function <code>swprintf_s</code>. First one, the FullPath of the Hive. Second and third strings correspond to the path of the log of changes in the Hive. Next, the function will call <code>OslLoadAndInitializeHive</code> with the following params:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#ff79c6">__int64</span> <span style="color:#50fa7b">OslLoadAndInitializeHive</span>(
  IN      ULONG DeviceID,
  IN      WCHAR <span style="color:#ff79c6">*</span>FullHivePath,
  IN      BOOLEAN FlagControlSet,
  IN      WCHAR <span style="color:#ff79c6">*</span>Log1Path,
  IN      WHCAR <span style="color:#ff79c6">*</span>Log2Path,
  OUT     PVOID RegistryBase,
  OUT     ULONG <span style="color:#ff79c6">*</span>RegistryLength,
  IN      PLOADER_HIVE_RECOVERY_INFO HiveRecoveryInfo,
  OUT     PVOID HiveId
);
</code></pre></div>
<p>First thing is to open the file (<a href="https://doxygen.reactos.org/d5/de2/boot_2environ_2lib_2misc_2image_8c_source.html#l00358" target="_blank"><code>BlImgLoadImageWithProgress2</code></a>) and save a pointer to it on the variable <code>RegistryBase</code>. Afther this the <a href="https://github.com/msuhanov/regf/blob/master/Windows%20registry%20file%20format%20specification.md#windows-81-system-hive" target="_blank">File Header</a> will be filled and finally the call to <code>HiveInitializeAndValidate</code> will initialize the Hive. This function initialize and validates the structure <a href="https://www.nirsoft.net/kernel_struct/vista/HHIVE.html" target="_blank">HHIVE</a></p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp">  Hive <span style="color:#ff79c6">=</span> <span style="color:#bd93f9">0xBEE0BEE0</span>; <span style="color:#6272a4">// Set the signature to the Structure
</span><span style="color:#6272a4"></span>  Hive<span style="color:#ff79c6">-&gt;</span>GetCellRoutine <span style="color:#ff79c6">=</span> HvpGetCellPaged; <span style="color:#6272a4">// Function to get a CellPage
</span><span style="color:#6272a4"></span>  Hive<span style="color:#ff79c6">-&gt;</span>ReleaseCellRoutine <span style="color:#ff79c6">=</span> HvpReleaseCellPaged; <span style="color:#6272a4">// Function to release a CellPage
</span></code></pre></div>
<p>Next, the function <code>HiveAddTableEntry</code> add this Hive to the <code>HiveTable</code>. Since this is the first time this function is called the table will be initialized (Constant to 4 entries), the address of the Hive is copied to the table (<code>BlTblSetEntry</code>) and the <strong>HiveId</strong> is set with the index of this Hive in the table.</p>

<p>Finally, if the <strong>FlagControlSet</strong> is active, the function <code>OslSetControlSet</code> will be called to check if the value <em>Default</em> of the key <em>Select</em> inside the Hive matches any ControlSet (The famous <strong>ControlSet001</strong>) and then it will change the key <em>Current</em> with this number. In memory it will look something like this:</p>

<p><img src="/images/oslLoadDrivers/System_Hive.jpg" alt="alt img" title="System Hive" /></p>

<p><a name="attach_hive_notes"></p>

<h4 id="oslattachhivetoloaderblock">OslAttachHiveToLoaderBlock</h4>

<p></a></p>

<p>This function is quite generic, but I mention it here because after loading the ELAM Driver this function will be called in order to add the ELAM Hive to the Loader Block (I still haven&rsquo;t check how ELAM Drivers work but I guess they need this Hive to work correctly). First, this function will obtain the path to the HIVE (The ELAM Hive in this case)</p>

<p><img src="/images/oslLoadDrivers/elam_hive_path.jpg" alt="alt img" title="ELAM Hive Path" /></p>

<p>Next, the Hive will be loaded by calling <code>HiveLoadHiveFromLocation</code>, which in the end will call <code>OslLoadAndInitializeHive</code> as seen in the notes on the <a href="#system_hive_notes">SystemHive</a>. With the loaded Hive a structure I couldn&rsquo;t find anywhere will start to be filled, this structure has the following format (If it sounds familiar or you know more about it please let me know):</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#282a36;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-cpp" data-lang="cpp"><span style="color:#ff79c6">struct</span> _ATTACHED_HIVE_ENTRY 
{
  LISTR_ENTRY Link;
  WCHAR <span style="color:#ff79c6">*</span> HiveName;
  ULONG Unknow; <span style="color:#6272a4">/* I feel like is some kind of ID, but not sure */</span>
  PVOID HiveBase;
  ULONG HiveSize;
  WCHAR <span style="color:#ff79c6">*</span>StandardHiveName;
  WCHAR <span style="color:#ff79c6">*</span>HiveSubtree;
}
</code></pre></div>
<p>Finally, the structure is linked to the to the member <code>LoaderParamBlock-&gt;Extension-&gt;AttachedHives</code> through the <code>LIST_ENTRY</code>.</p>

<p><img src="/images/oslLoadDrivers/attached_hive_struct.jpg" alt="alt img" title="Attached Hive" /></p>

<p><a name="device_notes"></p>

<h4 id="deviceid">DeviceId</h4>

<p></a></p>

<p>The <strong>DeviceId</strong> is obtained using the function <code>OslpOpenDevices</code>, this function first look to see if the <em>device</em> is already open (<code>BlpDeviceOpen</code>) to do this it will call <code>BlTblFindEntry</code> with first parameter as the table of open <em>devices</em> <code>DmDeviceTable</code>, second as the number of entries in this table <code>DmTableEntries</code> and fourth is a pointer to the  function <code>DeviceTableCompare</code> (This is the function that checks if the <em>device</em> we are looking for is inside the <code>DmTableEntries</code>)</p>

<p>The function <code>OslpOpenDevices</code> will open the <em>device</em> pointed by the variable <code>OslLoadDevice</code> (Also if the boot options <code>BCDE_OSLOADER_TYPE_BSP_DEVICE</code> and <code>BCDE_OSLOADER_TYPE_OS_DATA_DEVICE</code> are set those <em>devices</em> will be open respectively). I will only review the first case, variable <code>OslLoadDevice</code> was previously assigned from the boot flag <code>0x21000001</code> (<code>BCDE_OSLOADER_TYPE_OS_DEVICE</code>). This <em>device</em> is no other than the Volume where the Bootloader reside. In my case the Bootloader (<strong>winload.efi</strong>) is in the Volume <code>C:</code>, the following image shows the <em>device</em> accessing to it from the <code>OslLoadDevice</code> variable and accessing to it through the <code>DmDeviceTable</code> (In this case I know is the index 4)</p>

<p><img src="/images/oslLoadDrivers/guid_deviceObject.jpg" alt="alt img" title="Device Object" /></p>

<blockquote>
<p>In ReactOS the structure pointed by the variable <code>OslLoadDevice</code> is called <a href="https://doxygen.reactos.org/dd/d76/struct__BL__DEVICE__DESCRIPTOR.html#a67f2887f7c88a8e27757add9d869c39d" target="_blank"><code>_BL_DEVICE_DESCRIPTOR</code></a>. I couldn&rsquo;t find any other references to this structure nor a similar structure.</p>
</blockquote>

<p>In the following image we can see how the GUID we obtained previoulsy from the <em>device</em> matches the Volume <code>C:</code>, and also matches the Volume where the Bootloader is stored</p>

<p><img src="/images/oslLoadDrivers/guid_check.jpg" alt="Device Object Check" style="margin:auto;"/></p>

<p>Lastly, and I&rsquo;m not totally sure about this (That&rsquo;s why I left it to the end 🤣). Before I mentioned that the <em>device</em> is the index 4 in the array. If we check with the tool <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/winobj" target="_blank">WinObj</a> the <em>HardDisk0</em>, we can see that the partition 4 points to <em>HardDiskVolume4</em>. On the other hand, the object <em>BootPartition</em> and the object <em>BootDevice</em> point to the same Volume. By this, I guess that when the Bootloader initialize the <em>devices</em> it fills the <code>DmDeviceTable</code> in the order in which the partitions are arranged.</p>

<p><img src="/images/oslLoadDrivers/harddisk_volume4.jpg" alt="alt img" title="HardDisk Volume 4" /></p>

<blockquote>
<p>If I&rsquo;m not wrong the <em>devices</em> are initalized by the function <code>SpaceBootInitialize</code> with the call to <code>SB_CONTROL::BuildDevices</code>, so this would be a good point to confirm this last paragraph (I could be totally wrong assuming <em>devices</em> are initialized, haven&rsquo;t reversed this I just suspect it from the name)</p>
</blockquote>
]]></content></item></channel></rss>