Extending C2 Lateral Movement – Invoke-Pbind

Invoke-Pbind is a mini post exploitation framework written in PowerShell, which builds C2 communications over SMB named pipes using a push rather than a pull mechanism. Pbind was initially created to overcome lateral movement problems, specifically in restricted environments where the server VLAN could not directly talk to the user VLAN (as it should be in every environment). The tool was designed to be integrated with any C2 framework or run as a standalone PowerShell script.

Video Demonstration

If you just want to skip to the video tutorial, then you can find that here and at the end of this post.

The Problem: Segregation and Strict Firewalling

This is useful when you have compromised an organisation and have C2 comms over HTTPS, traversing the corporate proxy server out of the network from user’s workstations, but the target dataset that you are looking to obtain is located down server VLAN with a firewall restricting both inbound and outbound traffic. In that scenario, firewall rules are always going to allow for specific traffic to traverse over pre-approved services. The following diagram illustrates one such situation, where the environment allows limited services from the user VLAN to the server VLAN, but allows no ports in the reverse direction.

What options exist for C2 comms

The following are some options for C2 comms and their mitigations, resulting in failure.

Method Mitigation Result
Direct Internet Access Blocked by Firewall Outbound Fail
Traverse Through HTTP Proxy Blocked by Firewall Outbound Fail
TCP Reverse Shell Blocked or likely detected scanning for open ports Fail
TCP Bind Shell Blocked by Firewall Inbound or service running on open ports, no closed ports detected Fail
ICMP Blocked by Firewall Outbound Fail
Daisy over SMB in User VLAN TCP port 445 blocked from servers to workstations Fail
Daisy over HTTP in User VLAN Same as standard reverse all blocked ports Fail
DNS Authoritive DNS is only permitted by the Proxy server, thus not possible for C2 comms from the server VLAN. Fail

To be clear, at this point the problem isn’t about getting execution, it’s about having reliable C2 comms that afford the user output for all commands executed and to use the implant as a foothold or staging point to further attacks against servers in the restricted environment.

The Solution

“A named pipe is a logical connection, similar to a Transmission Control Protocol (TCP) session, between the client and server that are involved in the CIFS/SMB connection. The name of the pipe serves as the endpoint for the communication, in the same manner as a port number serves as the endpoint for TCP sessions. This is called a named pipe endpoint.” – https://msdn.microsoft.com/en-us/library/cc239733.aspx.

.NET has a class for creating and interacting with named pipes:

Where TCP port 445 is open into a server environment, we can overlay the SMB protocol and use a named pipe to share data between the workstation and server, providing a method for exchanging data (comms). The following commands make up the basis of creating a named pipe with an access rule that allows “everyone” access:

Since the days of abusing IPC$ with anonymous access (CVE-199-0519), and RID cycling your way to a plethora of goodies, Microsoft have said “no – though shall not pass” – non Microsoft direct quote. In a domain environment, any user can create a domain authenticated session to the $IPC share, which can then be piggy backed to gain access to the named pipe. Here is a simple script in PowerShell to create an authenticated session. One quick problem to overcome: While the ‘AccessRule’ applied to the pipe may look like it allows “everyone” access to the named pipe, this is not actually the case.

Interacting with a named pipe is also fairly straight forward as long as you know the data type of what is being read; as we create the server we know how to handle to pipe as shown by using a simple StreamReader:

Design

When we came up with Invoke-Pbind, the following principles were implemented.

Client/Server Model

To allow for inclusion in a C2 framework, two script blocks were created, client and server. The server starts and sets up the named pipe on a remote target (server). The client then connects to the named pipe and exchanges messages over TCP port 445 (SMB). The client runs through an existing C2 implant and by using script blocks and run spaces, it is possible to use the client non-interactively for better interaction with most C2 frameworks.

Token Passing

When sharing a common space such as a named pipe, it is imperative that messages exchanged between the client and server are not overwritten prior to being picked up by their counterpart. Control messages are used in combination with TRY and IF statements to create rules for when a client or server should read or write from the named pipe.

Security

During the generation of the script blocks, at run time, a unique key is generated and used to encrypt messages between client and server. Pbind supports AES 256 encryption. To initiate a connection to the named pipe from a client, a shared secret is also supported to stop tampering with the named pipe. If the client does not provide the correct secret, the named pipe will close.

Injection/Execution

There are two main methods included that inject the implant into target hosts. These are modified versions of Invoke-WMIExec and Invoke-SMBExec (credit to Kevin Robertson for these scripts); both scripts have been updated to support passing passwords, where previously they only accepted hashes for authentication. The implant is a self-executing script block that is passed as the payload. The script runs WMIExec by default but contains a switch parameter to invoke SMBExec:

To provide additional deployment flexibility the script also includes an exe method. This method uses CSC and Windows .Net automation DLL to compile the implant into an executable that can then be deployed and executed through any means.

NOTE: Creating a named pipe does not require administrator credentials so the executable can be run as a non-privileged user. On the other hand, WMIExec and SMBExec require administrator privileges.

The exe option continues to generate unique variables that are hardcoded into the executable, for use in cryptography and such like. The exe option can be used offline to create an executable implant and is not tied to an interactive session through a C2. To talk to the implant, the script supports a CLIENT option that is used to interact with a deployed implant, the options for which are provided when the implant is compiled:

This flexibility allows for the deployment through any means:

  • DCOM
  • RDP
  • Shared Folders
  • WinRM
  • SCCM
  • Anything……

There are a number of options that are configurable. If no options are selected, the script reverts to pre-set or randomly generated values. The following options are configurable:

  • KEY – Defaults to a randomly generated AES 256 Key – Allows for a key to be specified, commonly used in client mode.
  • SECRET – Defaults to random 5 character value – Allows for specific secret to be used.
  • PNAME – Defaults to random 8 character value – Allows for specific pipe name to be chosen.
  • TIMEOUT – Defaults to 60 second – Used to change the wait time for the client to connect to the Implant, used in slow networks.
  • EXE – Generates a stand-alone executable;
  • CLIENT – Runs the script in client mode to connect to a deployed Executable;
  • TARGET – used to specify a remote IP Address.
  • Domain/User/Password/Hash – used to provide credentials for authentication.
  • Domain2/User2/Password2 – used to map a drive to the target system, when a hash is being used as the primary authentication mechanism.
  • Dir – used in EXE mode to output the generate executable.
  • Automation – used in EXE mode, directory location of the Automation DLL.

Interaction

There are 3 main functions that have been created to interact with the implant from a client. The first and probably the most useful, especially when we introduce templates, is Pbind-Command. This simply registers a command in a variable that is read in by the client and passed to the implant (server) before being executed. A simple example is shown below:

Pbind-module c:\folder\powerup.ps1The second is Pbind-Module, which allows you to read in any other ps1 file and have it injected into memory on the implanted host. Pbind-Command can then be used to execute any of the functions in the ps1 script. This has a limitation and does not work well within a C2 setup, because all scripts have to be local to the client. In most cases the client is already running on a target workstation and would require all scripts to be uploaded to the client before being sent on to the implant.

Pbind-Squirt was a designed to help resolve the limitations of Pbind-Module. The idea for this function was to embed a number of scripts as base64 objects into the script that can then be called and auto executed into memory on the client. The only one that has been embedded is PowerUp, to assist with asset review on newly implanted hosts.

However, in practice neither Pbind-module nor Pbind-squirt were optimal and instead a new solution was constructed, called ‘Templates’. Effectively this was just a better way to interact with the Pbind-Command function. It was decided that by creating a number of small scripts which can automate tasks, it is possible to carry out similar ideas to Pbind-module and Pbind-squirt. Tasks such uploading mimikatz and extracting passwords, uploading PowerView and running queries or uploading invoke-SMBExec and attacking other machines, can all be scripted using a similar template to the one below:

The best way to see how the script runs is to download the script and have a go. The screenshot below shows a simple example of running the script locally under the context of another user, while also executing commands.

Video Tutorial

We have created a video tutorial to help illustrate the use of Invoke-Pbind.

Download

github GitHub: https://github.com/nettitude/PoshC2/blob/master/Modules/Invoke-Pbind.ps1

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

Making PoshC2 More Accessible With a $5 VPS

Users may find it difficult to host a PoshC2 server as it requires a Windows host, either directly connected to the Internet or in a position to be NAT’d through a firewall from an Internet facing C2 proxy. In this short post we’re going to show you how you can solve this problem in under 30 minutes with a $5 VPS.

For this to work you will need to create a small VPS from any provider. In this tutorial we’re going to use Digital Ocean, but feel free to use AWS, Azure, Vultr or one of the other providers out there.

First, start by creating a simple $5 per month  Digital Ocean droplet, using Ubuntu 16.04 or similar. The reason we’re using Ubuntu 16.04 is their tutorial for OpenVPN has been developed on this version, and we want to keep it simple. Once you’ve created the droplet, it should look something like this in your Droplets tab:

The next thing we need to do is get the host updated with the latest security patches, so perform an apt-get update and upgrade.

When you’re all up-to-date, we’ll install Apache2 which will be used as both the native web server and the proxy with which to forward all PoshC2 communication traffic through to your Windows host. It is important to note we only want the communications traffic to be forwarded and no other URLs.

To start this off, install apache as per the instructions below and enable the modules to allow proxying with Apache.

  • apt-get install apache2
  • a2enmod ssl
  • a2enmod rewrite
  • a2enmod proxy
  • a2enmod proxy_http
  • a2enmod headers
  • service apache2 restart

Once the default Apache2 install has completed, we find it easier to completely delete all files in the ‘sites-enabled’ and ‘sites-available’ folders of /etc/apache so that we can start from a fresh config, but this is purely an optional thing so do whatever best suits you and your setup. With one config file, we split out the virtual hosts and have both HTTP (port 80) and HTTPS (port 443) in one place.

The file we’re going to create for this postis called proxy.conf and should be located in the sites-available folder – /etc/apache2/sites-available/proxy.conf

The configuration should look something like the one below. Obviously yours may differ slightly if you decide to use multiple ports or have different virtual hosts with multiple names going through the same Apache server. However, to keep things simple, this is the default configuration without the rewrite rules applied.

Enable this site in Apache2 by either creating a symlink or by running this command:

  • a2ensite proxy.conf

This should then create a symlink in the sites-enabled directory as follows:

  • /etc/apache2/sites-enabled/proxy.conf -> /etc/apache2/sites-available/proxy.conf

Once you’re all done, restart your Apache2 service to ensure you have no errors.

  • service apache2 restart

The next thing you need to do is add your PoshC2 Apache Rewrite rules to the configuration.  This is where it can get quite complex depending on what you want the rules to do. As an example, when performing a Red Team engagement, your C2 infrastructure should be sufficiently locked down and should only allow implants from the correct IP address range of the Customer.

To add whitelisting on the C2 proxy, create a file with all the IP addresses that are known to be the client. There is a slight nuance with Apache as you have to add the list like this ( /etc/apache/whitelist):

Once you have the whitelist, you can use a function in the rewrite rules called RewriteMap to add the IP address list, to then use in the rewrite conditions. Here is a simple Rewrite Rule which will take the list above – if this is not found it will not process the rewrite rule. You have to do this for each rewrite rule you want for each URL. In this case we are applying to the /connect path as this is where the implant gets the stager, but if you customize the PoshC2 URLs then this may be different.

To complete the full Apache config, use the link below as a guide, but note you may need to change this for your PoshC2 setup as you customize the URLs for better evasion. Don’t forget that if you do change your URLs when setting up PoshC2 there is a file called apache2.conf in the root directory which created the rewrite rules for you. This does not add a whitelist but you can do this using the above config.

Now we have the Apache2 web server with our rewrite rules, we need to connect our Windows host to the this VPS using OpenVPN. I’m not going to walk through the exact steps to setup OpenVPN as there is a really good step by step guide which should take no more than around 20-30 minutes to follow and setup:

Once you’ve followed the guide to setup OpenVPN on the host in TUN mode, you can drop your client config onto your windows host. The OpenVPN server.conf configuration should look similar to this. This one is hosted over TCP 53 as we have 443 in use by the Apache Web Server.

Next, following the instruction in the Digital Ocean tutorial, create a client configuration file which matches the server settings and key files you setup and download this to your Windows host. Use the following link to install the Windows client, which should add a small icon to the task bar where you can import your configuration file to and connect.

At this point you should be nearly done. Once you get OpenVPN to successfully connect to the VPS, you can provide the Windows IP address in the Apache2 rewrite rules as the PoshC2 server and it will direct all traffic aimed for PoshC2 directly to the host. Remember that with this setup you will need to provide the external IP address or host name of the VPS as the PoshC2 server as shown in the image below – otherwise the payloads and droppers will be created with the wrong C2 server.

Having this kind of setup makes it extremely easy to deploy PoshC2 and should take no more than around 30 minutes of setup to have things fully weaponised and ready to go. Check out the latest updates for PoshC2 v3 from the blog below which induces a socks proxy (SharpSocks) to allow RDP via a HTTPS beacon.