Using PoolTags to Fingerprint Hosts

Commonly, malware will fingerprint the host it executes on, in an attempt to discover more about its environment and act accordingly.

Part of this process is quite often dedicated to analyzing specific data in order to figure out if the malware is running inside a VM, which could just be a honeypot or an analysis environment, and also for detecting the presence of other software.  For example, malware will quite often try to find out if a system monitoring tool is running (procmon, sysmon, etc.) and which AV software is installed.

In this article, we will introduce another method of fingerprinting a host that could be potentially abused by malware.

Common ways of host fingerprinting

In this section we provide a short list of well-known ways of detecting a VM environment, and the presence of other security software, that are often applied by malware. Note that the following list is not exhaustive.

  • Process Enumeration
  • Loaded modules Enumeration
  • File Enumeration
  • Data Extracted from Windows Registry (Hard disk, BIOS etc…)
  • Loaded drivers enumeration
  • Open a handle to specific named device object
  • System Resources Enumeration (CPU cores, RAM, Screen Resolution, etc…)

The PoolTag way

If you have some experience with Windows kernel drivers development & analysis, you should be familiar with the ExAllocatePoolWithTag [1] function that is used in order to allocate memory chunks at kernel level.  The key part here is the ‘Tag’ parameter that is used in order to provide some sort of identification for a specific allocation.

If something goes wrong, for example because of a memory corruption issue, we can use the specified Tag (up to four characters) in order to associate a buffer with a code path in the kernel driver that allocated that memory chunk. This method is adequate for detecting the presence of kernel drivers, and thus software that loads modules in the kernel that could potentially circumvent the fingerprinting methods mentioned above, which rely on information that a driver could potentially alter.  In other words, it is ideal for detecting the stuff that really matters from the malware author’s point of view.

For example, security/monitoring software might try to hide its processes and files by registering callback filters at kernel level.  An analyst might try to harden their VM environment by removing artefacts from the registry and other things that malware is usually searching for.

However, what a security software vendor and/or analyst probably won’t do, is modify specific kernel drivers used by their own program and/or system/VM environment to constantly alter the Tags of their kernel pool allocations.

Getting PoolTag Information

This information can be obtained by calling the  NtQuerySystemInformation [2] function and selecting SystemPoolTagInformation (0x16) [3] for the SysteminformationClass parameter.

The aforementioned function and the associated SysteminformationClass possible values are partially documented on MSDN, but fortunately with some online research we can find some documentation done by researchers. In particular, Alex Ionescu has documented a lot of otherwise undocumented stuff about Windows internals in his NDK [3] project.

For this proof of concept, we wrote our own version of getting and parsing PoolTag information, but if you want to go the GUI way to experiment with the results, then PoolMonEx [4] is a really nice tool to play with.

For instance, the following is a screenshot of our tool’s output.  Source code below.

Which you can compare with regards to the Nbtk tagged allocations results from PoolMonEx as shown below.

QueryPoolTagInfo.cpp

Defs.h

Targetting PoolTag Information

In order to give some sense to the acquired PoolTag information, it is necessary to analyse those drivers that we are interested in. By searching for calls to ExAllocatePoolWithTag we can log specific tags used by those drivers and keep them in our list.

At this point, you should be aware that any driver can use any tag at will, and for that reason it makes sense to try to find some tags that appear to be less common and not otherwise used by standard Windows kernel drivers and/or objects.

With that being said, this method of detecting specific drivers might produce false positives if not used with extra care.

A PoolTag Example List

For the sake of demonstrating a proof of concept we have collected some PoolTag information from specific drivers.

  • VMWare (Guest OS)
    • vm3dmp.sys (Tag: VM3D)
    • vmci.sys (Tags: CTGC, CTMM, QPMM, etc…)
    • vmhgfs.sys (Tags: HGCC, HGAC, HGVS, HGCD etc…)
    • vmmemctl.sys (Tag: VMBL)
    • vsock.sys (Tags: vskg, vskd, vsks, etc…)
  • Process Explorer
    • procexp152.sys (Tags: PEOT, PrcX, etc…)
  • Process Monitor
    • procmon23.sys (Tag: Pmn)
  • Sysmon
    • sysmondrv.sys (Tags: Sys1, Sys2, Sys3, SysA, SysD, SysE, etc…)
  • Avast Internet Security
    • aswsnx.sys (Tags: ‘Snx ‘, Aw++) (We used single quotes in the first because it ends with a space character)
    • aswsp.sys (Tags: pSsA, AsDr)

Conclusion

Just like every other method, this one has its strengths and weaknesses.

This method cannot be easily circumvented, especially in 64-bit Windows where the Kernel Patch Protection (Patch Guard) does not allow us to modify kernel functions among other things, and thus directly hooking those such as NtQuerySystemInformation is not a solution anymore for security and monitoring tools.

Also, this method is not affected by drivers that attempt to hide/block access to specific processes, files, and registry keys, from userland processes.

In addition, this method could be potentially used to fingerprint the host further.

By searching for specific tags of Windows objects that are being introduced in the OS, we can determine its major version.

For example, by comparing the poolTag information (pooltag.txt) that comes with different versions of Windbg, in this case Windows 8.1 x64 and Windows 10 x64 (Build 10.0.15063), we were able to find PoolTags that are used in Windows 10 by the  netio.sys kernel driver such as Nrsd, Nrtr, Nrtw, but not in Windows 8.1

We later did a quick verification by using two VMs, and we could indeed find pool allocations with at least two of the aforementioned tags in Windows 10, while there were none of those in our Windows 8.1 VM.

That being said, it is a common and good practice for kernel driver development to use tags that make some sense based on the module that allocates them and their purpose.

On the other hand, as mentioned already, PoolTags can be used at will and for that reason we have to be careful about which ones we are targeting.

One last thing to mention is that PoolTag information changes all the time, in other words chunks of memory are constantly allocated and de-allocated, and for this reason we should keep this in mind when choosing the PoolTag to search for.

Even though this method might look more experimental than practical, in reality when malware is searching for specific monitoring and security software, PoolTag information can be very reliable.

References

  1. https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/wdm/nf-wdm-exallocatepoolwithtag
  2. https://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx
  3. https://github.com/arizvisa/ndk
  4. http://blogs.microsoft.co.il/pavely/2016/09/14/kernel-pool-monitor-the-gui-version/

CVE-2017-16245 & CVE-2017-16246: Avecto Defendpoint Multiple Vulnerabilities

Avecto Defendpoint is an endpoint protection product which, according to the Avecto website, will:

“Prevent breaches without hindering productivity. Avecto combines best-in-class privilege management and application control, making admin rights removal simple and scalable across desktops and servers to ensure security and compliance.”

This post focuses on the “application control” aspect of Avecto. Last year I discovered two vulnerabilities in the way that application control is implemented, leading to the possibility of a breakout from the application control policy.

Both vulnerabilities were trivial to find and exploit. An exploit could easily be written into a Microsoft Word or Excel macro, for example.

Discovery and analysis

An initial investigation was carried out using Process Hacker. Examining any process running on a machine with Avecto installed, it could be seen that a DLL PGHook.dll had been injected into every process on the machine.

C:\Users\coakley\Desktop\labs.nettitude.com\Blogs\2018\Avecto\Pictures\Avecto_PGHOOK_ProcessHacker.png

The name PGHook.dll gives away that this DLL might be a user mode hooking library. The next step was to load PGHook.dll into IDA pro and have a poke around.

PGHook.dll applies hooks to several Windows API calls. The hooks are used to communicate with an Avecto system service, which then applies Avecto Group Policy settings.

Looking at the entrypoint of the DLL in IDA pro, an issue was immediately apparent:

C:\Users\coakley\Desktop\labs.nettitude.com\Blogs\2018\Avecto\Pictures\IDA_Mutex.PNG

A global mutex is created “Global\PGHOOK<pid>” where <pid> is the current process id. If this mutex already exists, then the rest of the entrypoint code is skipped and PGHook.dll does not install any hooks!

From here, it is easy to exploit this. If an attacker can create a lot of mutexes in the Global namespace for a whole bunch of process id’s, then they can force hooking to be disabled for new processes with those id’s. This method of mutex “squatting” is exactly how CVE-2017-16245 can be exploited.

After finding this, it was time for me to poke around a little further.

When executing a process that is not permitted in the security policy, a dialog box is displayed to the user; in this case wscript.exe was blocked:

C:\Users\coakley\Desktop\labs.nettitude.com\Blogs\2018\Avecto\Pictures\Avecto_Block.png

However, using ProcMon to monitor process creation, we can see that the blocked process wscript.exe does actually execute, and then exits:

C:\Users\coakley\Desktop\labs.nettitude.com\Blogs\2018\Avecto\Pictures\Avecto_WscriptBlocked_A.png

This is quite interesting; if the process is being executed and then terminates, can we block the process termination?

In Process Hacker, examining any running process again, we can see that there is a named pipe handle to \\.\pipe\PGMessagePipe being created and destroyed, quite regularly in each process.

Monitoring this pipe using API Monitor shows that it is used to communicate with a listening SYSTEM process, using the Windows API function TransactNamedPipe:

C:\Users\coakley\Desktop\labs.nettitude.com\Blogs\2018\Avecto\Pictures\Avecto_TransactNamedPipe.png

In the API monitor output, we can see the content of these messages:

<MSG ID=”2″ PID=”184 ” TID=”568″ ParentPID=”2880″ SessionID=”2″ CmdLine=”&quot;C:\Windows\system32\wscript.exe&quot;” CurrentDir=”C:\temp” InheritHandles=”1″ StartSuspended=”1″ MessageTime=”131771712686951286″ />

<MSG DisplayedMsg=”1″ Block=”1″ Status=”0″ />

You will also notice that there is a call to TerminateProcess in the API monitor output. I initially thought this may be the source of the process termination. I verified that this is not the case, by patching the TerminateProcess function with a two byte infinite loop 0xEB 0xFE (jmp -2). The process was still terminated, so this could not be the culprit.

So, each process that attempts to spawn a child process not only creates the actual child, but also tips off the SYSTEM service to the existence of the new process; this is how the new child process is terminated.

The next thing I tried was to prohibit comms with the SYSTEM service over the named pipe, which I achieved by editing the memory of PGHook.DLL in ProcessHacker on a running process.

It turned out that if comms are down, then any child process runs as normal, as it doesn’t get terminated. That is the basis for CVE-2017-16245. There are many other ways to prohibit the named pipe comms from within a process; the example source code provided below (note: will be published in the coming weeks) simply changes the name of the pipe in the process data section.

Proof Of Concept Video

In the following video, the two CVE executables have been white-listed in the Avecto application control policy.

This is an unrealistic scenario; in an ideal world the System Administrator will have locked down the endpoints so that only a curated list of applications are allowed to execute.

The CVE’s are, however, so trivial to exploit, that is it’s not difficult to imagine an attacker or inside threat using a Word macro, browser exploit or other code execution method in combination with these vulnerabilities in order to breakout of the application control policy.

It can be seen that while the two vulnerabilities are quite powerful in their own right, combining them provides a complete break-out solution.

Proof of Concept Source Code

We have opted to keep sample exploit code out of this blog for now.  Once we’re confident that enough time has elapsed for a significant majority of affected users to have patched, we will release sample code as an educational resource.

Conclusion

These two vulnerabilities really illustrate why user mode hooking is not a particularly good method of controlling process creation on Microsoft Windows. If you want to modify process permissions or deny process execution, then a kernel module is the way to go. Several kernel mode callbacks are available that allow you to intercept process creation.

Malicious code will always run with the same privileges as user mode hooks and, given enough time and access to the security product for reverse engineering, they can be bypassed.

CVE Numbers

The following CVE’s have been issued by MITRE:

  • CVE-2017-16245
  • CVE-2017-16246

Affected Versions

All versions up to and including 4.4 are affected.

Disclosure Timeline

  • Vulnerability discovered –  November 2017
  • Vendor notified – November 2017
  • Vendor acknowledged issues – November 2017
  • Vendor fixed issues – February 2018
  • Vendor notified that advisory is now public – 27 July 2018

Python Server for PoshC2

We are delighted to announce the release of our PoshC2 Python Server, allowing cross-platform support.

Over the past six months we have been working on a Python server for PoshC2, which allows it to be run on almost any Unix or Windows based system that is capable of running Python. We have thoroughly tested the server on Kali, and Debian based Linux distributions without any issues. The server-side repository has been named ‘PoshC2_Python’ so as not to confuse it with the Windows PowerShell server version, ‘PoshC2’, which is still widely used in a client environment or enclave when needed. Here are a few of the main advantages we’ve identified of running PoshC2 via Python:

  • Removes the need for Windows
  • Team Collaboration
  • AutoComplete on the Implant Handler
  • GraphViz Visualisation
  • Lower CPU Utilization

Team Collaboration

The Python code enhances the flexibility of PoshC2. One of the main features is cross-platform support, therefore the server will run on both Windows and Unix based systems. The main feature of running the server on Linux is to enhance the team collaboration piece, which has always been limited via a Windows system. The Python server can be installed as a service; see the ‘Systemctl Service’ section below for more details on how to achieve this. It also allows multiple users to connect remotely and run their own implant handler to interact with each implant, while viewing the output from journalctl. Alternatively, the server session can be run from a screen terminal and multiple users can view the same screen session. The best results would be to run this as a systemctl service so it survives a reboot and will automatically re-start.

Almost all features have been ported over to Python from the server side, apart from the compiled executables that were ordinarily generated using .NET’s command line compiler csc.exe. However, instead of generating .NET binaries, we have introduced new template files that are written in C++ that can be modified and used as a template. See the ‘Templates’ section below for more information. This gives the user the ability to modify the template files, customize the binary, change the process the shellcode is injected into, the injection method, hardcode a domain name or any other additional functionality you can think of to enrich the dropper.

This is an example of the C2 server up and running. Similarly to PoshC2, the server window is usually viewed side by side to the Implant Handler to maintain consistency. The server will populate all the payloads only the fly, including the one liners, shellcode, HTA and macro files.

Systemctl Service

The PoshC2 server can now automatically be started as a service using systemctl within Linux. You can choose to either have this functionality enabled or not during the install; by default the service is not created, but it can be enabled by following the steps below. The advantages of having the C2 server installed as a service are endless, but most importantly if you are on a live engagement and the server for some reason fails or reboots, your C2 server will be resilient and bounce back once the system is back up and running.

To add the service, create the following file with the code in the block below:

#> vim /lib/systemd/system/poshc2.service

Once the file is in the correct location, the systemctl command will know how to enable the service, should you require this. To enable the service, run the enable command, followed by start, as shown below.

#> systemctl enable poshc2.service

#> systemctl start poshc2.service

You can also stop or restart the service if you need to change the config or re-run the server for any reason.

#> systemctl stop poshc2.service

#> systemctl restart poshc2.service

The best feature of running PoshC2’s python server as a service is the fact you can view the server output using the journalctl log. If you are running the server on an engagement with multiple users, it is very easy to share the output by running this command when you login via SSH.

#> journalctl -n 20000 -u poshc2.service -f –output cat

Reporting

While this hasn’t changed significantly since the first iteration of PoshC2, it’s one of the most important elements of the tool.  It will fundamentally assist in the SOC detection and response phase of your engagements, i.e. when assessing the response of the Blue Team.  It is, of course, also a professional requirement to have full logs of offensive activity.

One addition to the reporting section is the introduction of the opsec command which is in the pre-implant help. This will provide a list of all files uploaded to the system, including a unique list of hosts touched for reporting purposes.

The output-to-html now uses a GraphViz implementation which is still a work in progress, but aims to visually represent the compromise in action, including all hosts that are connected to the C2 server and how they are communicating back to the infrastructure. For example, if you have a host daisy chaining via an implant this will be displayed on the GraphViz output below. These files are generated when the output-to-html function is run within the pre-implant handler window. All icons are customizable via the output file that is generated or you can switch these out editing the files folder in PoshC2.

It should be noted that proxy aware implants and daisy payloads are still all functioning within the Python server and work the same way as in PoshC2. For more information on Daisy Chaining please refer to the documentation or the following blog:

Z:\Desktop\pyshc2.png

The HTML output has also been improved and now has some additional JavaScript that allows the commands to be searched and all output data truncated for easier viewing. The output can also be searched using the same method. If there are any additional reporting requirements you would like to see in here, please hit us up on Slack or Twitter.

Videos will be released shortly on how to get started with PoshC2, including customizing the Config.py file and editing the source files for better optimization.

Quick Install

To install PoshC2 on Ubuntu from a terminal, run the following:

curl -sSL https://raw.githubusercontent.com/nettitude/PoshC2_Python/master/Install.sh | bash

To get started, follow the instructions on the readthedocs webpage, which walk you through how to customize your install and have a better chance of not being detected within your engagement.

If you have any issues regarding crypto, this could be due to a dependency installation failure. The best way to get around this has been to create a virtualenv in Python and then install the requirements file manually for that virtualenv. For more information, read how to create a virtualenv in Python online.

Wine SharpSocks

But what about SharpSocks? Never fear, SharpSocks works with Wine! If you need to find out how to get Wine installed for SharpSocks, there is a file called Install_SOCKS that has step-by-step instructions on how to achieve this. For those who don’t know what SharpSocks is, the following blog post discusses our release of a SOCKS server for PoshC2in detail.

Templates

As previously mentioned, PoshC2 now has template files that can be optimized prior to starting the service. An example of why you might want to do this is environment detections such as domain name or user. The template files are created using C++; by default there is an executable that creates a file which migrates automatically, and one that stays in the same process.

Signtool

To reduce the likelihood of the binary files being detected, you could also sign the executables that are generated from PoshC2 by using a code signing certificate. This will add some legitimacy to the binary when calling out to the internet.

#> signtool.exe sign /f code_signing_cert.pfx /p password Posh64.exe

Delay

As part of the initial payload, the PowerShell script will attempt to execute. If the C2 Proxy or implant cannot reach the server, the process will wait for 300 seconds (5 minutes) and retry. If required, it will then wait for 600 seconds (10 minutes) and try one final time. This has been implemented as a backup in case your C2 infrastructure is locked down too securely and for some reason doesn’t accept the implant first time. This could be due to a number of environmental detections, including the external IP address. The implant could have passed the domain check but come from a non-whitelisted IP address. This will give you the opportunity to evaluate the IP address and add to the whitelist if this should have been part of the organisations external IP address range given to you. This can all be modified if the timings need to be increased for any reason; all of this code is in the Payloads.py file.

Autoloads

Autoruns have always been a great feature for us. There is nothing worse than having to tell the C2 tool to load the following PowerShell module before running the command when this can all be coded into the tool. PoshC2 has implemented a lot of these by default, but if you want to customize them you can amend the autoloads by editing the AutoLoads.py file and adding extra lines.

Modules

The philosophy of PoshC2 has always been to use a selection of amazing PowerShell cmdlets that have been written by others in the industry. The PoshC2 folder has a Modules folder where all the scripts are loaded from. You can simply add any PowerShell script that conforms to the PowerShell standard into this folder and load using the Implant Handler:

loadmodule Invoke-Mimikatz.ps1

Python Dropper

As you will notice, we have made a small start on the Python dropper to allow for Unix support. This has not been exhaustively tested, however, it is a start at making it possible to support execution on the likes of a macOS based system or similar. There is currently a requirement to have pycrypto on the box that is executing the payload but we are working on solutions to implement the crypto piece without requiring this dependency. Something along the lines of in memory module imports, or similar. If anyone would like to contribute to this side of the PoshC2, please don’t hesitate to get in touch.

A Python implant has limited features right now. Currently you can set the beacon timer and execute commands on the host.

PoshC2 Execution Tips

A pro tip for executing PoshC2 on a client device that is highly monitored and has PoshC2 v5 with script block logging, module logging and transcript Logging is combining the work Dave Hardy did with the PoSHBypass (including the authors of the bypass techniques) and the transcript logging bypass we put together using this gist code snippet:

The script block logging, Module Logging & AMSI bypass was put together here by Dave Hardy:

The Transcript Evasion technique was from here:

From an OpSec perspective, similarly to most C2 frameworks and adversaries, PoshC2 has some default IoCs that it is highly recommended you optimize to avoid detection. These items include:

  • Comms URLS
  • UserAgent
  • Use Domain Fronting
  • Change Default Migration Process (netsh.exe)
  • Change Default Persistence Methods
  • Template Files

When you start PoshC2 ,you have to optimize the Config.py file which will provide you a list of default URLs that can be used. These are publicly available and will most likely get signatured in time. To ensure you are providing the best chance of remaining undetected, you should optimize these URLs. This also goes for the UserAgent string. Prior to sending in any payloads, it is necessary to do reconnaissance against a target. This will often include techniques like web bugs or similar. This will give you a change to identify the default UserAgent for the target estate. This could range from IE11, Chrome, Firefox or even Edge. You should re-configure the UserAgent configuration to be in line with the corporate estate to merge into normal business traffic on the proxy.

As most of us know, domain fronting is the best form of hiding censorship when performing Red Teaming. Unless the organization is performing SSL inspection, there is no way this type of communication can be detected. If the organization is using SSL inspection, its best to use a site that falls into one of these two categories to have the best chance of going under the radar:

  • Financial Services
  • Health Care

Frameworks such as Cobalt Strike and Metasploit also have common indicators of comprise (IoC), such as ‘notepad.exe’ for Metasploit and ‘rundll32.exe’ for Cobalt Strike. PoshC2 has a similar default process that is used for migration; this is netsh.exe. When performing the default migration within PoshC2, e.g. running the ‘migrate’ command, it will always start the process netsh.exe unless directed by the user on the command line. It is highly recommended that you customize this option; the new PoshC2 ‘Inject-Shellcode’ or ‘migrate’ function also has the ability to spoof the parentpid. Note, this works on Windows 7 but has had some failures on Windows 10. Also, the default method for process migration was using the win32 API call ‘CreateRemoteThread’. PoshC2 now has the ability to use ‘RtlCreateUserThread’ which is not quite as widely used across C2 frameworks. This was largely due to the help from @uint_ptr, who is our in house Windows wizard!

You can use the migrate command with all of the above in mind as follows:

  • migrate -procpath c:\windows\system32\searchprotocolhost.exe -suspended -RtlCreateUserThread
  • migrate -procpath c:\windows\system32\svchost.exe -suspended -RtlCreateUserThread -ParentID 4502

From a logging and monitoring perspective, it is always good practice to migrate to a process that is expected to go out to the internet, e.g. Internet Explorer, Outlook, Lync or similar. If the client has an endpoint product that tracks process migration and history, going from netsh.exe out to the internet should be suspicious. Keep this is mind when selecting the process to migrate into.

Here is an example of parent process spoofing in Windows 7. The following command was ran to migrate the process searchprotocolhost.exe and set the parentid of explorer (pid: 432). Note, this was all done using a standard user account.

  • migrate -procpath c:\windows\system32\ searchprotocolhost.exe -suspended -RtlCreateUserThread -ParentID 432

Persistence is also another function that should be completely optimized. PoshC2 has some default persistence methods, however, these are likely to be highly signatured and should be changed accordingly. There are many methods of persistence you can use, depending on your privileges. COM Hijacking is highly recommended or WMI if elevated. DLL Hijacking is also fairly difficult to detect; if you want to create a custom DLL that can be used for DLL hijacking, here is a simple code snippet that can be used to launch another process when the DLL is attached, which is perfect for DLL hijacking.

AMSI Checker

A new feature we’ve added is an Anti-Malware Scan Interface (AMSI) checker. We have baked this into the core-implant module. This does a quick process check using PowerShell and determines if the amsi.dll is loaded into the core implant. If this module is loaded, it will notify you through the C2Server response and provide a way of unhooking this DLL.

The way we unhook this module is using the work Adam Chester (@_xpn_) put together on exploring PowerShell AMSI and logging evasion. The way this function works is by using C# to pinvoke various Win32 API calls to identify where a certain DLL is loaded and its export functions reside in memory. As we own the memory for our process, we can simply overwrite the code in memory, returning the same response as if the malware check was benign.

For visibility, it is possible to identify if PoshC2 is running in another process by using Process Explorer which comes as part of the sysinternals suite (https://docs.microsoft.com/en-us/sysinternals/). This allows you to see if any .NET assemblies have been loaded into the running process. If the process is in fact PoshC2, there is a known Indicator of Compromise when running the CLR v4.0.30319 because you will see a DLL loaded called ‘posh’. This does not appear in .NET version two, as shown in the examples below.

Python 3

In the not too distant future, this will be ported over to Python v3. Currently it’s only designed to work in version 2.7.

Conclusion

In conclusion, both the traditional Windows PoshC2 and the Python Server PoshC2 repositories will be actively maintained by various contributors.  We encourage you to use it, provide feedback and generally contribute to the project.  You can always grab the latest version from GitHub.

github GitHub: https://github.com/nettitude/PoshC2_Python.

COM and the PowerThIEf

Recently, Component Object Model (COM) has come back in a big way, particularly with regards to it being used for persistence and lateral movement. In this blog we will run through how it can also can be used for limited process migration and JavaScript injection within Internet Explorer. We will then finish with how this was put together in our new PowerShell library Invoke-PowerThIEf and run through some situations it can aid you, the red team, in.

Earlier this year I became aware of a technique that involved Junction Folders/CLSID that had been leaked in the Vault 7 dump. It was when I began looking at further applications of these that I also learned about the Component Object Model (COM) ability to interact with and automate Internet Explorer. This, of course, is not a new discovery; a lot of the functionality is well documented on sites like CodeProject. However, it hadn’t been organised into a library that would aid the red team workflow.

This formed the basis of my talk “COM and the PowerThIEf” at SteelCon in Sheffield on 7th July 2018. The slides for the talk can be found at:

The talk itself is here:

Getting up to speed with COM

Before we dive into this, if you are not familiar with COM then I would highly recommend the following resources. These are a selection of some of the recent excellent talks & blog posts on the subject that I would recommend if you want to know more.

Junction Folders

I first came across the Junction Folders/CLSID technique mentioned above in one of b33f’s excellent Patreon videos. As I understand it, this was first used as a method for persistence, in that if you name a folder in the format CLSID.{<CLSID>} then when you navigate to that folder, explorer will perform a lookup in the registry upon the CLSID and then run whatever COM Server has been registered. As part of his DefCon 25 WorkShop (which is worth a read, hosted at https://github.com/FuzzySecurity/DefCon25) he released a tool called Hook-InProcServer that enabled you to build the registry structure required to be used for a COM Hijack or for the JunctionFolders/CLSID technique. These were both being used as a Persistence mechanism and I began wondering if this might be possible to use as a means of Process Migration, at least into explorer.exe.

Step one was to find if it was possible to programmatically navigate to one of the configured folders and – yes – it turns out that it is. In order to be able to navigate, we first need to gain access to any running instances of explorer. Windows makes this easy via the ShellWindows object:

Enumerating the Item property upon this object lists all the current running instances of Explorer and Internet Explorer (I must admit I thought this was curious behaviour). ShellWindows is identified by the CLSID “{9BA05972-F6A8-11CF-A442-00A0C90A8F39}”; the following PowerShell demonstrates activating it.

The objects returned by indexing the .Item collection will be different based upon if it is an explorer and IE instance. An easy check is using the FullName which exists on both and has the name of the application, as shown here.

This article (https://www.thewindowsclub.com/the-secret-behind-the-windows-7-godmode) from 2010 not only contains the Vault7 technique but also shows that it is possible to navigate to a CLSID using the syntax shell:::{CLSID}. Assuming that we have at least one IE window open, we are able to index the ShellWindows.Item object in order to gain access to that window (e.g. to gain access to the first IE window, use $shWin[0].Item). This will provide us an object that represents that instance of IE and is of a type called IWebBrowser2. Looking further into this type, we find in the documentation that it has a method called Navigate2. (https://msdn.microsoft.com/en-us/library/aa752134(v=vs.85).aspx). The remarks on the MSDN page for this method state that it was added to extend the Navigate method in order to “allow for shell integration”.

The following code will activate ShellWindows, assuming the first window is an IE instance (this is a proof of concept) and will then attempt to navigate to the Control Panel via the CLSID for Control Panel (which can be found in the registry).

The following animation shows what happens when this code is run:

Control Panel being navigated to via CLSID ID:

We can then see via a trace from Process Monitor that IE has looked up the CLSID and then navigated to it, eventually opening it up in explorer, which involved launching the DLL within the InProcServer registry key. If we create our own registry keys we then have a method of asking IE (or Explorer) to load a DLL for us all from the comfort of another process. We don’t always want network connections going out from Word.exe, do we? In the case of IE the DLL must be x64. There are methods of configuring the registry entries to execute script; I suggest that you look at subTee’s or bohop’s excellent work for further information.

JavaScript

Once a reference is obtained to an Internet Explorer window it is then possible to access the DOM of that instance. As expected, you then have full access to the page and browser. You can view and edit HTML, inject JavaScript, navigate to other tabs and show/hide the window, for example. The following code snippet demonstrates how it is possible to inject and execute JavaScript:

The difference this time is that we actually have to locate the eval method on the DOM window before being able to call it. This requires using .NET’s Reflection API to locate and Invoke the method.

The following shows what happens this code is run.

Where is this all going?

Well, despite the programming constructs and some of the techniques being well documented, there didn’t appear to be a library out there which brought it all together in order to help a red team in the following situations:

  • The target is using a password manager, e.g. LastPass where key-logging is ineffective.
  • The user is logged into an application and we want to be able to log them out without having to clear all browser history and cookies.
  • The target application is in a background tab and can‘t wait for user to switch tabs. We need to view or get HTML from that page.
  • We want to view a site from the targets IP address, without the target being aware.

This led to me writing the PowerThIEf library which is now hosted at https://github.com/nettitude/Invoke-PowerThIEf.

The functionality included in the initial release is as follows:

  • DumpHtml: Retrieves HTML from the DOM, can use some selectors (but not jQuery style – yet).
  • ExecPayload: Uses the migrate technique from earlier to launch a payload DLL in IE.
  • HookLoginForms: Steals credentials by hooking the login form and monitoring for new windows.
  • InvokeJS : Executes JavaScript in the window of your choice.
  • ListUrls: Lists the urls of all currently opened tabs/windows.
  • Navigate: Navigate to another URL.
  • NewBackgroundTab: Creates a new tab in the background.
  • Show/HideWindow: Shows or Hides a browsing window.

Examples of usage and functionality include:

Extracting HTML from a page:

Logging the user out, in order to capture credentials:

Using the junction folders to trigger a PoshC2 payload:

Capturing credentials in transit entered via LastPass:

Usage

The latest Invoke-PowerThIEf documentation can be found at:

Roadmap

Further functionality is planned in the future and will include

  • Screenshot: Screenshot all the browser windows.
  • CookieThIEf: Steal cookies (session cookies).
  • Refactor DOM event handling: Developing Complex C# wrapped in Powershell is not ideal.
  • Pure C# Module
  • Support for .Net 2.0-3.5

Download

github GitHub: https://github.com/nettitude/Invoke-PowerThIEf