Category Archives: Incident Handling and Hacker Techniques

Malware Analysis – PlugX – Part 2

Following my previous article on PlugX, I would like to continue the analysis but now use the PlugX controller to mimic some of the steps that might be executed by an attacker. As you know the traditional steps of an attack lifecycle follow, normally, a predictable sequence of events i.e., Reconnaissance, initial compromise, establish foothold, escalate privileges, internal reconnaissance, move laterally, maintain persistence, complete mission. For sake of brevity I will skip most of the steps and will focus on the lateral movement.I will use the PlugX controller and C2 functionality to simulate an attacker that established a foothold inside an environment and obtained admin access to a workstation. Following that, the attacker moved laterally to a Windows Domain Controller. I will use the PlugX controller to accomplish this scenario and observe how an attacker would operate within a compromised environment.

As we saw previously, the PlugX controller interface allows an operator to build payloads, set campaigns and define the preferred method for the compromised hosts to check-in and communicate with the controller. In the PlugX controller, English version from Q3 2013, an operator can build the payload using two techniques. One is using the “DNS Online” technique which allows the operator to define the C2 address e.g, an URL or IP address, that will be used by the payload to speak with the C2. The other method, is the “Web Online”, which allows the operator to tell the payload from where it should fetch the C2 address. This method allows the operator to have more control over the campaign. The following diagram illustrates how the “Web Online” technique works.

Why do I say this technique would allow an attacker to have more control? Consider the case that an organization was compromised by a threat actor that use this PlugX technique. In case the C2 is discovered, the impacted organization could block the IP or URL on the existing boundary security controls as a normal reaction to the concerns of having an attacker inside the network. However, the attacker could just change the C2 string and point it to a different system. In case the organization was not able to scope the incident and understand the TTP’s (Tools, Tactics and Procedures) then the attacker would still maintain persistence in the environment. This is an example that when conducting incident response, among other things, you need to have visibility into the tools and techniques the attacker is using so you could properly scope the incident and perform effective and efficient containment and eradication steps. As an example of this technique, below is a print screen from a GitHub page that has been used by an unknown threat actor to leverage this method.

So, how to leverage this technique on the PlugX builder? The picture below shows how the operator could create a payload that uses the “Web Online” technique. The C2 address would be fetched from a specified site e.g. a Pastebin address, which on its turn would redirect the payload to the real C2 address. The string “DZKSAFAAHHHHHHOCCGFHJGMGEGFGCHOCDGPGNGDZJS” in this case is used to decode to the real C2 address which is “www.builder.com”. On the “PlugX: some uncovered points” article, Fabien Perigaud writes about how to decode this string. Palo Alto Unit42 gives another example of this technique on the “Paranoid PlugX” article. The article “Winnti Abuses GitHub for C&C Communications” from Cedric Pernet ilustrates an APT group leveraging this technique using GitHub.

For sake of simplicity, in this article, I’m going to use the DNS Online technique using “www.builder.com” as C2 address. Next, on the “First” tab I specify the campaing ID and the password used by the payload to connect to the C2.

Next, on the Install tab I specify the persistence settings, in this case I’m telling the payload to install a service and I can specify different settings including where to deploy the binaries, the service name and service description. In addition, I can specify that if the Service persistence mechanism fails due to some reason the payload should install the persistence mechanism using the Registry and I can specify which HIVE should be used.

Then, In the inject tab I specify which process will be injected with the malicious payload. In this case I choose “svchost.exe”. This will make PlugX start a new instance of “svchost.exe” and then inject the malicious code into svchost.exe process address space using process hollowing technique.

Other than that, the operator could define a schedule and determine which time of the week the payload should communicate with the C2. Also the operator could define the Screen Recording capability that will take screenshots at a specific frequency and will save them encrypted in a specific folder.

Last settings on the “option” tab allow the operator to enable the keylogger functionality and specify if the payload should hide it self and also delete itself after execution.

Finally, after all the settings defined, the operator can create/download the payload in different formats. An executable, binary form (Shellcode), or an array in C that can then be plugged in another delivery mechanism e.g, PowerShell or MsBuild. After deploying and installing the payload on a system, that system will check-in into the PlugX controller and an operator can call the “Manager” to perform the different actions. In this example I show how an attacker, after having compromised a system, uses the C2 interface to:

  • Browse the network

  • Access remote systems via UNC path

  • Upload and execute a file e.g., upload PlugX binary

  • Invoke a command shell and perform remote commands e.g., execute PlugX binary on a remote system

Previous pictures illustrate actions that the attacker could perform to move laterally and, for example, at some point in time, access a domain controller via UNC path, upload the PlugX payload to a directory of its choice and execute it. In this case the pictures show that the PlugX payload was dropped into c:\PerfLogs\Admin folder and then was executed using WMI. Below example shows the view from the attacker with two C2 sessions. One for one workstation and another for a domain controller.

Having access to a domain controller is likely one of the goals of the attacker so he can obtain all the information he needs about an organization from the Active Directory database.

To access the Active Directory database, the attacker could, for example, run the “ntdsutil.exe” command to create a copy of the “NTDS.dit” file using Volume Shadow Copy technique. Then, the attacker can access the database and download it to a system under his control using the PlugX controller interface. The picture below illustrates an attacker obtained the relevant data that was produced using the “ntdsutil.exe” command.

Finally, the attacker might delete the artifacts that were left behind on the file system as consequence of running “ntdsutil.exe”.

So, in summary, we briefly looked at the different techniques a PlugX payload could be configured to speak with a Command and Controller. We built, deploy and install a payload. Compromised a system and obtain a perspective from PlugX operator. We move laterally to a domain controller and installed the PlugX payload and then used a command shell to obtain the Active Directory database. Of course, as you noted, the scenario was accomplished with an old version of the PlugX controller. Newer versions likely have many new features and capabilities. For example, the print screen below is from a PlugX builder from 2014 (MD5: 534d28ad55831c04f4a7a8ace6dd76c3) which can create different payloads that perform DLL Search order hijacking using Lenovo’s RGB LCD Display Utility for ThinkPad (tplcdclr.exe) or Steve Gibson’s Domain Name System Benchmarking Utility (sep_NE.exe). The article from Kaspersky “PlugX malware: A good hacker is an apologetic hacker” outlines a summary about it.

That’s it! With this article we set the table for the next article focusing on artifacts that might helps us uncover the hidden traits that were left behind by the attacker actions performed during this scenario. Stay tuned and have fun!

 

 

Tagged , , , ,

Analysis of a Master Boot Record – EternalPetya

NoPetya or EternalPetya has kept the security community pretty busy last week. A malware specimen that uses a combined arms approach and maximizes its capabilities by using different techniques to sabotage business operations. One aspect of the malware that raised my interest was the ability to overwrite the Master Boot Record (MBR) and launch a custom bootloader. This article shows my approach to extract the MBR using digital forensic techniques and then analyze the MBR using Bochs. Before we roll up our sleeves let’s do a quick review on how the MBR is used by today’s computers during the boot process.

The computers that rely on BIOS flash memory instead of the new EFI standard, when they boot, the BIOS code is executed and, among other things, the code performs a series of routines that perform hardware checks i.e., Power-On-Self-Tests (POST). Then, the BIOS attempts to find a bootable device. If the bootable device is a hard drive, the BIOS reads the sector 1, track 0, head 0 and if contains a valid MBR (valid means that the sector ends with bytes 0xAA55) it will load that sector into a fixed memory location. By convention the code will be loaded into the real-mode address 0000:7c00. Then, the instruction pointer register is transferred into that memory location and the CPU will start executing the MBR code. What happens next is dependable on the MBR implementation code i.e., different operating systems have different MBR code  Nonetheless, the code needs to fit in the 512-bytes available at disk sector. The MBR follows a standard and its structure contains executable code, the partition table (64-bytes) with the locations of the primary partitions and finally 2-bytes with 0xAA55 signature. This means only 446-bytes are available to implement a MBR. In the Microsoft world, when the MBR code is executed, its role is to find an active partition, read its first sector, which contains the VBR code, load it into memory and transfer execution into it. The VBR is a bootloader program that will find the Windows BootMgr program and executes it All this happens in 16-bits real-mode.

Now, that we have a brief overview about the boot process, how can we extract and analyze the MBR? More specifically the MBR that is used by EternalPetya? Well, we infect a victim machine on a controlled and isolated environment. We know that EternalPetya main component is a DLL and we can launch it and infect a Windows machine by running “rundll32.exe petya.dll, #1 10”. Our setup consisted of 2 Virtual Machines. One running with Windows 7 and another running REMnux. We created a snapshot of the victim machine before the infection. Then executed the malware. Following that, we waited 10 minutes for the infection to complete. The scheduled task created by the malware restarted the operating system and a ransom note appeared. Then, I shutdown the Windows 7 virtual machine and used vmware-vdiskmanager.exe utility to create a single VMDK file from the disk state before and after the infection. Next, I moved the VMDK files to a Linux machine where I used QEMU to convert the VMDK images to RAW format.

Following that I could start the analysis and look at the MBR differences. The picture below illustrates the difference between the original MBR and the EternalPetya MBR. On the right side you have the EternalPetya MBR, the first 147 bytes (0x00 through 0x92) contain executable code.  The last 66 bytes (0x1be through 0x1fd) contain the partition table and are equal to the original MBR.

So, we are interested in the code execution instructions. We can start by extracting the MBR into a binary file and convert it to assembly instructions. This can be done using radare, objdump or ndisasm. Now, this is the hard part of the analysis. Read the assembly instructions and understand what it does. We can look at the instructions and perform static analysis but we can also perform dynamic analysis by running the MBR code, combining both worlds we will have better understanding – or at least we can try.

To perform dynamic analysis of the MBR code we will use Bochs. Bochs is an open source, fully fledged x86 emulator. Originally written by Kevin Lawton in 1994 is still being actively maintained today and last April version 2.6.9 was released. Bochs brings a CLI and GUI debugger and is very useful to debug our MBR code.  In addition, Bochs can be integrated with IDA PRO and Radare.  You can download Bochs from here.  In our case, we want to use Bochs to dynamically debug our MBR code. For that we need a configuration file called Bochsrc which is used to specify different options such as the disk image and also the CHS parameters for the disk. This article from Hex-Rays contains a how-to on how to integrate Bochs with IDA PRO. At the end of the article there is the mbr_Bochs.zip file that you can download. We will use these files to use Bochs standalone or combined with IDA PRO in case you have it. The Bochsrc file that comes with the ZIP file contains options that are deprecated on the newer Bochs version. The picture below shows the Bochsrc options I used. The Bochs user guide documents this file well.

Then you can try your configuration setup and launch Bochs. If you have IDA PRO then you can use this guide starting from step 6 in order to integrate it with IDA PRO. If all is set up, the debugging session will open and stop at the first instruction from its own BIOS code at memory address F000:FFF0.  Why this address? You can read this and many other low level things in the outstanding work from Daniel B. Sedory.

Uncomment the last line from the Bochsrc configuration file, to tell Bochs to use the Enhanced Debugger. For further references, you can read the “How to DEBUG System Code using The Bochs Emulator on a Windows™ PC” article. Start Bochs again and the GUI will show up. You can load the stack view by pressing F2. Then set a breakpoint where the MBR code will be loaded by issuing the command “lb 0x7c00” and then the “c” to continue the debugging session.

Now we can look at the code, step into the instructions, inspect the registers and stack. After some back and forth with the debugger I created the following listing with my interpretation of some of the instructions.

Bottom line, the MBR code will perform a loop that uses BIOS interrupt 0x13 function 0x42 to read data starting at sector 1 of the hard-drive. The loop copies 8880 (0x22af) bytes of data into memory location 0x8000. When the copy is done, the execution is transferred to the address 0x8000 by performing a far jump and the malicious bootloader is executed. The malicious bootloader code has been uploaded by Matthieu Suiche to Virus Total here. You can also extract it from the hard drive by extracting the sector 1 through 18 or better using the commands from the following picture. Then you can perform static and dynamic analysis.

The 16-bits bootloader code is harder to analyze than the MBR code but it is based on the Petya ransomware code from 2016. In this great article, from Hasherezade, she analyzes both Petya and EternalPetya bootloader using IDA PRO. When you use Bochs integrated with IDA PRO disassembler and debugger, the analysis is more accessible due to the powerful combination.

That’s it for today – Entering the world of real-mode execution on x86 is quite interesting. Analyzing code that relies on BIOS services such as software interrupts to perform different operations like reading from disk or writing to screen or, accessing the memory through segments is revealing. What we learned today might be a starting point to start looking at bootkits that are beneath the operating system and subvert the MBR boot sequence.

Have fun!

References:

Windows Internals, Sixth Edition, Part 2 By: Mark E. Russinovich, David A. Solomon, and Alex Ionescu

Various articles written by Daniel B. Sedory : http://starman.vertcomp.com/index.html

http://standa-note.blogspot.ch/2014/11/debugging-early-boot-stages-of-windows.html

Tagged , , ,

Threat Hunting in the Enterprise with AppCompatProcessor

Last April, at the SANS Threat Hunting and IR Summit, among other things, there was a new tool and technique released by Matias Bevilacqua. Matias’s presentation was titled “ShimCache and AmCache enterprise-wide hunting, evolving beyond grep” and he released the tool AppCompatProcessor. Matias also wrote a blog post “Evolving Analytics for Execution Trace Data” with more details.

In this article, I want to go over a quick exercise on how to use this tool and expand the existing signatures. First, let me write that, in case you have a security incident and you are doing enterprise incident response or you are performing threat hunting as part of your security operations duties, this is a fantastic tool that you should become familiar with and have on your toolkit. Why? Because it allows the security teams to digest, parse and analyze, at scale, two forensic artifacts that are very useful. The forensic artifacts are part of the Windows Application Experience and Compatibility features and are known as ShimCache and the AMCache.

To give you more context, the ShimCache can be obtained from the registry and from it we can obtain information about all executable binaries that have been executed in the system since it was rebooted. Furthermore, it tracks its size and the last modified date. In addition, the ShimCache tracks executables that have not been executed but were browsed for example through explorer.exe. This makes a valuable source of evidence for example to track executables that were on the system but weren’t executed – consider an attacker that used a directory on a system to move around his toolkit. The AMCache is stored on a file and from it we can retrieve information for every executable that run on the system such as the PATH, last modification time and created, SHA1 and PE properties. You can read more about those 2 artifacts in the article I wrote last year.

So, I won’t go over on how to acquire this data at scale – feel free to share you technique in the comments – but, AppCompatProcessor digests data that has been acquired by ShimCacheParser.py, Redline and MIR but also consumes raw ShimCache and AMCache registry hives. I will go directly to the features.At the time of this writing the tool version is 0.8 and one of the features I would like to focus today is the search module. This module allows us to search for known bad using regex expressions. The search module was coded with performance in mind, which means the regex searches are quite fast. By default, the tool includes more than 70 regex signatures for all kinds of interesting things an analyst will look for when perform threat hunting. Signatures include searching for dual usage tools like psexec , looking for binaries in places where they shouldn’t normally be, commonly named credential dumpers, etc. The great thing is that you can easily include your own signatures. Just add a regex line with your signature!

For this exercise, I want to use the search module to search for binaries that are commonly used by the PlugX backdoor family and friends. This backdoor is commonly used by different threat groups on targeted attacks. PlugX is also refered as KORPLUG, SOGU, DestroyRAT and is a modular backdoor that is designed to rely on the execution of signed and legitimated executables to load malicious code. PlugX, normally has three main components, a DLL, an encrypted binary file and a legitimated executable that is used to load the malware using a technique known as DLL search order. I won’t go discuss the details about PlugX in this article but you can read the White Paper “PlugX – Payload Extraction” done by Kevin O’Reilly from Context, the presentation about Plugx at Black Hat ASIA in 2014 given by Takahiro Haruyama and Hiroshi Suzuki, the analysis done by the Computer Incident Response Center Luxembourg and the Ahnlab threat report. With this and other reports you could start compiling information about different PlugX payloads. However, Adam Blaszczyk from Hexacorn, already did that job and wrote an article where he outlines different PlugX payloads seen in the wild.

Ok, with this information, we start creating the PlugX regex signatures. Essentially we will be looking for the signed and legitimate executables but in places where they won’t normaly be. The syntax to create a new regex signature is simple and you can add your own signatures to the existing AppCompatSearch.txt file or just create a new file called AppCompatSearch-PlugX.txt which will be consumed automatically by the tool. The figure below shows the different signatures that I produced. . At the time of this writing, this is still work in progress but is a starting point.

Next step, launch AppCompatProcessor against our data set using the newly created signatures. The following picture shows how the output of the search module looks like. In this particular case the search produced 25 hits and a nicely presented summary of the hits is displayed on a histogram. The raw dumps of the hits are saved on the file called Output.txt.  As an analyst or investigator, you would look at the results and verify which ones would be worth to further investigate and which ones are false positives. For this exercise, there was a hit that triggered on the file “c:\Temp\MsMpEng.exe”. This file is part of the Windows Defender suite but could be used by PlugX as part of DLL search order hijack technique. Basically, the attacker will craft a malicious DLL named MpSvc.dll and will place that in the same directory as the MsMpEng.exe file and execute MsMpEng.exe. The DLL would need to be crafted in a special way but that is what PlugX specializes in. This will load the attacker code.

Following these findings, we would want to look at the system that triggered the signature and view all the entries. The picture below shows this step where we use the dump module. The output shows all the ShimCache entries for this particular system. The entries are normally sorted in order of execution from bottom to top, and in this case, adjacent to the “c:\Temp\MsMpEng.exe” file there are several windows built-in commands that were executed and a file named “c:\Temp\m64.exe”. This is what Matias calls a strong temporal execution correlation. This is indicative that an attacker obtained access to the system, executed several windows built-in commands and and executed a file called “m64.exe” which likely is Mimikatz or a cousin. 

Following those leads, you might want to obtain those binaries from the system and perform malware analysis in order to extract indicators of compromise such as the C&C address, look at other artifacts such Windows Event Logs, UsnJournal, memory, etc.. and have additional leads. In addition, you might want to further use AppCompatProcessor to search for the “m64.exe” file and also use the tstack module, to search across all the data set for binaries that match the date of those two binaries. With these findings, among other things, you would need to scope the incident by understanding which systems the attacker accessed, find new investigation leads and pivot on the findings. AppCompatProcessor is a tool that helps doing that. This kind of finding would definitely trigger your incident response processes and procedures.

That’s it, hopefully, AppCompatProcessor will reduce the entry barrier for your security operations center or incident response teams to start performing threat hunting in your environment and produce actionable results. If you find this useful, contribute with your threat hunting signatures in AppCompatProcessor GitHub repo and Happy Hunting!

 

Tagged , , , , , ,

Offensive Tools and Techniques

In this article I go over a series of examples that illustrate different tools and techniques that are often used by both sides of the force! To exemplify it, I will follow the different attack stages and will use the intrusion kill chain as methodology. This methodology consist of seven stages. Reconnaissance, weaponization, delivery, exploitation, installation, C2 and action on objectives.

offensive-logoLet’s start with Recon! The goal here is to seek information about the target, normally a person. Targeting high profile individuals might be difficult because these individuals tend to have a personalized security group that looks after them. However, using different intelligence-gathering techniques such as searching information available in a variety of public information sources you can target other personnel. Due to the human nature, people succumb to social engineering techniques and several times they provide more information than is necessary. A starting point is to harvest metadata about the organization and personnel. Normally, companies do not know what metadata they are giving way. Metadata is a golden pot of information and information such as usernames, software versions, printers, email addresses and others can be retrieved using a tool such as FOCA Metadata Analysis Tool. You can see the presentation that was given by Chema Alonso and Jose Palazon Palatko in 2010 at Defcon 18 about FOCA 2.5.  At the end the attacker will use whatever works to gather as much information as possible about employee names, position in the hierarchy, friends and relatives, hobbies, etc.

Next step, weaponization and delivery! After getting as much information as possible and performing enough recon the attacker will choose the best method to perform the attack with his available resources. Nowadays, spear phishing techniques with attached documents are very dominant and probably a good choice as attack vector. The sophistication of how a document is weaponized and delivered might correlate with the amount of resources available to the attacker. In the example below I show how you could use Metasploit to easily create a word document with a malicious macro that when executed will connect back to the attacker system and establish a command and control channel. The payload uses HTTPS as communication channel but it uses a self-signed certificate and points to an IP address and not a domain. In organization of different sizes, many times the web filtering controls are tight and use different blocking techniques that might detect and stop this type of connection. However, the attacker can register a new domain or buy an expired domain ahead of time, create a simple and realistic web page and categorize the domain in a category such as Finance or Healthcare – these are normally allowed in web filtering products and probably the SSL wouldn’t be terminated and inspected. In addition, the attacker can buy a cheap SSL certificate and make this scenario much more realistic.  In addition, Metasploit just introduced an updated traffic obfuscation technique that will make harder for security products to detect it.

Before I continue with the different tools and techniques, is worth to mention that in this article I give several examples using the Metasploit Framework. For those of you who don’t know, Metasploit framework was originally created by the legendary H.D. Moore back in 2003. Originally coded in Perl and then ported to Ruby. In 2004, Metasploit Framework 2.0 was released and had less than 20 exploits and a similar number of payloads. Today, the free version of Metasploit framework has more than 1600 exploits and more than 400 payloads. In addition many other auxiliary modules, encoders and post exploitation modules are available. The modular framework of Metasploit makes it a fantastic tool to design, build and launch exploits.

So, the picture below illustrates how to use Metasploit to create a weaponized Word document. An alternative to this technique is to use PowerShell Empire. See this article from Matt Nelson.

offensive-macro

Then, the word document can be customized and tailored to the target. To summarize, the attacker crafts a phishing email, either with a weaponized document or malicious link. This coupled with different social engineering techniques that appeal to human nature and exploit human vulnerabilities have good probability to make the attack a success. There is other factor that might impact the success of the campaign, which is the ability of the malicious email/link to circumvent the multitude of expensive filters that are layered throughout the network boundary and reach to the endpoint. If the email reaches the endpoint, you might have a well-intentioned employee making mistakes.  If these conditions are met, the attacker will establish a foothold inside the corporate network.

The picture below depicts the steps performed by the attacker to launch the Metasploit handler that will accept the beacon from the malicious document. Then, it shows the communication received and the established session.

offensive-macrohandler

Next step exploitation! With a foothold in the environment and an established communication channel the attacker will act quickly, stealthy and will probably try to find avenues to exploit other systems and achieve higher privileges.  Ruben Boonen who maintains fuzzysecurity.com and goes by the handler @FuzzySec has wrote a very comprehensive article where he describes the different techniques that could be used to escalate privileges on a Windows environment. Another great resource is the paper “Windows Services – All roads lead to SYSTEM” from Kostas Lintovois that exemplifies several ways in which misconfigured services could be compromised.  These techniques are very useful for attackers because in many organizations normal users don’t have admin rights. Admin rights are likely a goal that all attackers aim in an enterprise environment because it facilitates their job.

Many of the techniques written by Ruben and others have been materialized in the post-exploitation framework known as PowerSploit in a module called PowerUp.ps1 which has been originally written by Will Schroeder – a brilliant security researcher that in recent years released powerful tools -. PowerSploit contains a great library of modules and scripts that help in all phases of an attack life-cycle.  The PowerUp module facilitates the discovery of conditions that would allow an attacker to execute a technique that will lead him to get a privileged account. All this done using PowerShell and can be executed from within Meterpreter using the PowerShell extension that was written by OJ Reeves and incorporated into Metasploit  This means, that attacker can run PowerUp from within Metasploit. You can read more about PowerUp on Will Schroeder blog and also get PowerUp cheat sheet from here.

The picture below illustrates this scenario, where the attacker after getting a foothold in the environment – via phishing email – verifies that the account he is operating with doesn’t have enough privileges to run additional modules such as the powerful Mimikatz. Mimikatz is a post-exploitation tool written in C and developed by Benjamin Delphy. You can read more about many of its features on Sean Metcalf Unofficial Guide to Mimikatz and Command reference here and here. However, Meterpreter contains a PowerShell module that would allow the attacker to execute PowerShell commands. In this case the attacker can load the PowerShell module, execute the necessary commands to download the PowerUp from GitHub, a site owned by the attacker or other place and then perform the Invoke-AllChecks. At the time of this writing, the PowerUp module contains 14 checks.

offensive-powerup

In this case, as you could see in the image, the conditions necessary to perform DLL hijacking are found by PowerUp module. Essentially, the system contains a directory that any authenticated user can write to and this directory is part of the %PATH% environment variable. With this the attacker can leverage the DLL search order and obtain system privileges.  In this case PowerUp suggests to use “wlbsctrl.dll”. For this to work the Windows service “IKE and AuthIP IPsec Keying Modules” needs to be running but in enterprises where workstations have VPN clients installed this is quite common. This vulnerability was discovered in 2012 by the High-Tech Bridge Security Research Lab. It leverages the Windows service “IKE and AuthIP IPsec Keying Modules”, which during startup tries to load the “wlbsctrl.dll” DLL that doesn’t exist on default Windows installations. A great explanation about how this technique works and why the vulnerability exists was written by Parvez Anwar here.  Another resource about this topic is “DLL Hijacking Like a Boss!” presentation Jake Williams and an old article from the Corelan team here.

So, now that there is an avenue to explore, the next step is for the attacker to create a DLL that matches the architecture of the target system and has the name “wlbsctrl.dll”. This can be easily done with msfvenom. This utility is very popular to create one liners commands that will generate and encode a desired payload. Msfvenom was added to Metasploit in 2011 and combines the older Msfpayload and Msfencode commands in one utility. This is showing in the figure below.

offensive-dll

Another way to leverage this technique is to use Write-HijackDll function available in the PowerUp.ps1 module. This function will create and drop the “wlbsctrl.dll” DLL into the writable path and when the service starts the DLL will load and will add a user to local administrators with a predefined password.

An important remark in regards to the usage of PowerShell is that on some environments the security might be tight and PowerShell execution might be blocked. However, in this cases the attacker could use other techniques and use other tools such as PowerOPS: PowerShell for Offensive Operations tool written by Portuculis Lab and inspired in the PowerShell Runspace Post Exploitation Toolkit written by Cn33liz.

After that, the attacker uploads the DLL to the desired folder, the attacker can force a reboot or wait for the system to be rebooted. When the system starts, the IKEEXT service will be started and the malicious DLL will be loaded, spawning a command and control channel back to the system owned by the attacker and with SYSTEM privileges. The picture below illustrates the upload of the malicious DLL to the folder that has weak permissions and is part of the %PATH% variable. Then it follows the command and control channel that is established due to the IKEEXT service being started. Due to the high privileges the attacker can then move on and start using the powerful Mimikatz module. To start he can obtain clear text credentials by using Kerberos command.

offensive-dllhijack

Now, the attacker is operating under a high privileged account! With that, the attacker can move on and find a way to establish a persistence mechanism and in parallel move laterally within the environment.

Next step, installation and C2! There are a multitude of clever techniques and tools used by attackers to accomplish a persistence mechanism but in this case I would give an example of using WMI combined with PowerShell using a payload crafted by Metasploit.

WMI has gained popularity among attacker in recent years. A good resource is the presentation that Matt Graeber gave on BlackHat 15 : Abusing Windows Management Instrumentation (WMI) to Build a Persistent, Asynchronous, and Fileless Backdoor. In addition, William Ballenthin, Matt Graeber and Claudiu Teodorescu have written a great paper about the usage of WMI for both offense and defense. Furthermore, you can read the paper WMI for Detection and Response from NCCIC/ICS-CERT.

So, to achieve persistence the attacker could use Windows Management Instrumentation (WMI). The WMI will be used as a vehicle to trigger a payload to run at a particular event. This event could be a specific schedule, an event that occurred at the OS level, such as login or one of the many events supported by WMI. The payload would leverage PowerShell to perform a technique known as Reflective DLL injection which will call back to the attacker system and inject the Metasploit Meterpreter – to read more about Reflective DLL injection read this article from Dan Staples and its references -. The communication occurs over HTTPS back to the domain owned by the attacker. In sum, the attacker will only use windows built-in functionality combined with Metasploit. This arrangement of different tools and techniques lead to more powerful attacks that are harder to detect. In addition this technique leverages in memory payload that doesn’t touch disk due to the fact that uses a PE loader in memory to load the DLL and not the traditional LoadLibraryA() method. The persistence mechanism is inside the WMI repository which is likely to be outside of the radar of many defenders.

Let’s see how the attacker can build this. To craft the payload the attacker could use msfvenom utility that is part of Metasploit framework. The following picture illustrates the use of msfvenom to create the Reflective DLL injection payload using PowerShell format.

offensive-pshcmd

Next step would be to weaponize this payload into a Managed Object Format (MOF) script.

offensive-wmimof

Next the attacker will use the Managed Object Format (MOF) compiler, Mofcomp.exe on the target machine. This utility will parse a file containing MOF statements and adds the classes and class instances defined in the file to the WMI repository. A good article about MOF is “Playing with MOF files on Windows, for fun & profit” from Jérémy Brun-Nouvion. After that, a series of wmic.exe commands can be executed to view the contents of the different classes.

offensive-wmicommands

These commands are executed within the Meterpreter session that was established with the DLL hijacking technique. Then the attacker can cover his tracks and delete the malicious MOF script and move on. When the WMI event is triggered, the payload is invoked and a meterpreter session is established back to the system owned by the attacker. With this, the attacker has a persistence mechanism and is operating in the target environment with a privileged account.

Next, action on objectives! Lateral movement has been traditionally done using a variety of commands and tools such as net.exe, psexec.exe and wmic.exe. Nowadays, you can add PowerShell to the mix.. More specifically using the PowerView tool which was developed by William Schroeder and is part of PowerSploit tools and scripts. PowerView is an advanced active directory enumeration tool written in PowerShell that allows an attacker to gather extensive amount of information about a Windows enterprise environment. You can read more about the reason behind Powerview hereThis great write-up demonstrates several use cases for PowerView. Once again, we can load PowerView from within our Meterpreter sessions. In this case, the session has SYSTEM privileges and was obtained leveraging the WMI persistence but PowerView can run with a normal account.  The picture below exemplifies this step.

offensive-powerview

The list of functions available within PowerView is here and the cheat sheet here. The attacker starts enumerating different aspects of the Active Directory and the different systems just by leveraging PowerShell commands. To perform this he can leverage different techniques and modules within PowerView.  For a great summary you can see – once again – William Schroeder presentation given at Troopers 16 entitled “I have the power view”.

So, to start, the attacker can leverage the Kerberoasting technique. This technique pioneered by Tim Medin – I recommend you watch his presentation “Attacking Kerberos – Kicking the Guard God of Hades” – is brilliant and exploits the way Kerberos functions inside a Microsoft environment. This technique has been reorganized and adopted by PowerView and to run it is as simple as to list all user accounts in the active directory environment that have a SPN, request a Kerberos ticket and extract the crypto material. Then crack it offline to obtain clear text password. You can read more about it in this two articles written by William here and here. The below picture illustrates the Kerberoasting technique.

offensive-kerberoast

After obtaining the hash you could use John the Ripper to crack the password using as hash format the krb5tgs.

Another attack vector is to find accounts in the Active Directory that don’t require Kerberos preauthentication i.e., the PreAuthNotRequire attribute is enabled. This technique was pioneered by Geoff Janjua from Exumbra Operations and you can read the work he did in the article “Kerberos Party Tricks: Weaponizing Kerberos Protocol Flaws“. Essentially the technique consists on listing all accounts that have this attribute and request a Kerberos ticket for those accounts. This ticket contains crypto material that can be extracted and cracked offline. Once again this technique was adopted by PowerView and you can read more about it here.

Finally, if these techniques don’t work, then the attacker likely will move from system to system until he finds a system where he can obtain administrative privileges and move on until he finds a domain admin. This can be daunting task in large environments but once again William Schroeder coded the necessary steps into a series of PowerView modules that are coined with the Hunter word such as Invoke-UserHunter, Invoke-StealthUserHunter and many others that will facilitate the search for high value targets. You can view his presentation “I hunt sysadmins” to understand more what these modules do behind the scenes.  Justin Warner, one of the founders of PowerShell Empire, wrote a great article explaining how these modules works and went further by explaining a technique he named as derivative local admin. This technique was then automated by Andy Robbins which started in a proof-of-concept tool called PowerPath which leverages algorithms that are used to find the shortest path between two points. Andy then worked with Rohan Vazarkar and Will Schroeder  and their work culminated in the release of a tool called BloodHound. The tool was released as open source tool at DEF CON 24. Bottom line, using the different techniques and tools implemented by these brilliant folks the threat actor is likely to succeed obtaining a high privileged account.

Then, is matter of pivoting inside the enterprise environment using the obtained privileged accounts. For that the attacker can leverage the netsh.exe port forwarding feature or the Meterpreter port proxy command to pivot between internal systems. This technique is commonly used by attackers that want to use an internal system as pivot, allowing direct access to machines otherwise inaccessible from the attacking system. The command in the picture below illustrates this, where after configuring the port forwarding on the compromised system, the attacker can use wmic.exe to launch PowerShell on a remote system that will connect back to the attacker system and establish a meterpreter session.

offensive-wmimove

From this moment, its a cycle. Enumerate weakness, exploit them, compromise the system, move further, repeat. This cycle goes on and on until the attacker meets his objectives. A great resource about the techniques that were shown and many others are listed in this article written by Raphael Mudge, the author of Cobalt Strike.

That’s it. With this we covered different tools and techniques that are used in the different attack stages and used nowadays by security professionals but as well by cyber criminals and APT groups. After this, I would ask, how would you detect, prevent and respond to each one of the steps outlined in this attack scenario?

Feel free to share your ideas in the comments below. Thanks for reading!

Tagged , , , , , , , , ,

The ABC’s of a Cyber Intrusion

IntrusionNowadays, in corporations of any size and maturity level, I believe the success of many of the initial compromise and follow up actions is based on three variables. First, a well-crafted phishing email, either with a weaponized document or malicious link. Second the ability of the malicious email/link to circumvent the multitude of expensive filters that are layered throughout the network boundary and reach to the endpoint. Third, a well-intentioned employee making mistakes.  If these three conditions are met then the threat actor is likely to establish a foothold inside the corporate network.  Of course the conditions for the second and third variable to be met are likely outside of the attacker control and depends on many factors that can impact the success of the exercise. For example, two questions that might be relevant to determine how hard would be for a threat actor to get in, are: How well optimized, tuned and monitored is the deployed security technology? How well behaved and trained are the corporate users about the different types of threats?

Nevertheless, a threat actor that has strong technical capabilities can shift tactics and compromise websites that are related to your business and instead focus on a watering hole attack. This might remove the third variable from the equation.

Once the threat actor(s) got in, he will likely perform internal recon to find assets and data of interest. To collect this information he needs a toolbox. More often than the defenders would like the attackers are using Windows native tools to perform their actions. However, many times to be able to access more resources within the environment they deploy their own tools which sometimes are legitimate sysadmin tools – like SysInternals Suite. Normally, these tools are moved into the environment using the same channel that has been used to establish foothold. The toolbox might consist in exploit(s), credential theft tool(s), utilities to (de)compress and encrypt data and other utilities or scripts.

After having their toolbox deployed – normally referred as staging phase – is common that they start enumerating and mapping the environment. The initial collection might consist of information about the users, their roles, the enforced password policies, the workstations and server names. To do this the threat actor only needs to query the Domain. By Domain I mean the Active Directory which is likely present in any corporate network environment. In a very simple manner the Active Directory is a directory that can be easily queried just like someone would query any other directory such as the yellow pages. Just by executing the net.exe command on a command prompt the attacker can dump all the users, service accounts and which users and service accounts belong to which groups. This information is of great value and become very useful when the attacker is moving laterally. In addition, this information can be complemented by gathering which users are logged on a particular system using the query.exe command. Furthermore, the attacker can leverage powerful Windows Management Instrumentation Command Line (wmi.exe) and PowerShell techniques to increase his capabilities to collect even more information about the Domain. This can all be done with a non-privileged account.

Then, provided with all this rich information the threat actor can start expanding his territory and move laterally. How would he do that? Well, in fact you could be thinking about using the latest 0-day or a novel exploit technique but in today’s corporate networks sometimes the attacker doesn’t need this. Why? Well, many times the weakness of corporate networks is processes and people. For example, the persons that have the keys to the domain such as sysadmins are likely to be a target. The sysadmins are persons with a day job, a pile of tasks to perform and many times part of an understaffed team. Moreover, their goal is likely not security but availability of the services, minimum disruption to the business and at the end of the day a job well done that satisfy the business needs.

Consider the scenario that exists in most corporate networks when someone raises a ticket into helpdesk. Or some endpoint maintenance or action needs to be performed by a sysadmin. Many times the administration of the workstations is done by sysadmins that connect to the endpoint and authenticate using domain credentials that have privileged accounts. This will make their credentials exposed because when the user logs on interactively, Windows will cache the user password in memory. Perhaps, here we have a problem with the processes and not with technology. A privileged domain account should never login into a workstation. Other scenario that is problematic is the management of service accounts. Many times privileged service accounts are used for all type of services. This means the credentials of the service accounts are exposed and can be retrieved by an attacker with local access to the system. Therefore, service accounts should be managed prudently and more important a common mistake is to allow service accounts to login interactively. The scope of service accounts should be limited and, perhaps, here we have another process issue, service accounts should never be used to logon interactively. Another common challenge is that internal network segregation is often not the same as the perimeter leaving services and servers exposed to direct access from the workstations. These are some of the common challenges that are difficult problems to solve and where many times convenience wins and technology alone is not likely to overcome.

What is the impact of this? If a threat actor manages to get a foothold inside an environment that relies on practices such as the ones described previously, then he can access a variety of credentials. The captured credentials will depend on the technique and hardening settings of the endpoint used and are either in a form of a hash, ticket or clear text. This can be accomplished using tools such as Windows Credential Editor, Mimikatz, Gsecdump or AceHash. Won’t antivirus detect these tools? Likely, when they are used off the shelf but not when they are customized. Furthermore, more often than we would like, the internal network segregation is simple and not designed to prevent attacks. This means the attacker can enumerate services at will and leverage the gathered credentials to logon into servers. This step is a game changer!

If the attacker has credentials that can be used to login into your Servers and Domain Controllers then is likely game over. For example he could create a persistence and unnoticed backdoor just by setting a registry key that will use the cmd.exe as a Debugger for tools like sethc.exe (Sticky Keys) and osk.exe (On-screen keyboard). Or even worse he could easily steal the Active Directory database (ntds.dit). Even though the database is not accessible via user mode API’s the threat actor can leverage different techniques such as Volume Shadow copy, Powershell offensive framework like PowerSploit or use a forensic tool that is able to read low level NTFS. With a copy of the Active Directory database the threat actor can perform an offline attack using tools like Impacket secredumps to extract all the credentials. If the threat actors have the keys to the kingdom they will likely be undetected for quite some time and might start using the same egress points as your remote access users. How many VPN users do you have that are in the exception list of not having 2nd factor?

From an IT point of view this will mean your network would be in the worst state possible and your most plausible solution, among other things, is to rebuild the workstations, servers and potentially go over the painful task of having to rebuild the entire Active Directory forest. Now, this will be expensive however, it’s not impossible and the organization will survive. But, if the attacker also gets access to the servers that hold the organization critical information, valuable data, and intellectual property that would make the business leaders tremble. The financial direct or indirect losses of a security incident can be significant. The reputational damage can be difficult to assess and the disruption of critical systems on heavy regulated industry can have significant consequences.

Multi-stage, multi-faceted attacks are here to stay. The tools and technique will evolve and become more sophisticated than ever. The threat actors behind the attacks will try to become stealthy and remain under the radar.  However, on the other side of the fence we have the defenders. Which I believe can have a big impact on detecting and preventing the threat actors mission. If the detection only occurs after the fact then they can respond and stop the bleeding and limit the damage. But before they do this the organizations should get the basics right. It can take time and is never too late. A good starting point is to choose a framework such as the SANS TOP 20 Critical Controls. Use it as a reference for building, designing, deploying and adopt security controls and measure the security posture of your organization. Then move on from there to build more advanced capabilities!

Tagged , , ,

Digital Forensics – DLL Search Order

Following our series of posts on Digital Forensics we will continue our journey about analyzing our compromised system. In the last two articles we covered Windows Prefetch and Shimcache. Among other things, we wrote that Windows Prefetch and ShimCache artifacts are useful to find evidence about executed files and executables that were on the system but weren’t execute. While doing our investigation and looking at these artifacts, the Event Logs and the SuperTimeline, we found evidence that REGEDIT.EXE was executed. In addition, from the Prefetch artifacts we saw this execution invoked a DLL called CLB.DLL from the wrong path. On Windows operating systems CLB.DLL is located under %SYSTEMROOT%\System32.  In this case CLB.DLL was invoked from %SYSTEMROOT%.

However, when we looked inside the %SYSTEMROOT% folder and we could not find any traces of the CLB.DLL file. This raised the following questions:

  • How did this file got loaded from the wrong PATH?
  • Did file got deleted by the attacker?

Let’s answer the first question.

Inside PE files there is a structure called Import Address Table (IAT) that contains the addresses of the library routines that are imported from DLL’s. When an application is launched the operating system will check this table to understand which routines are needed and from which DLL’s. For example, when I execute REGEDIT.EXE the binary has a set of dependencies needed in order to execute.  To see this dependencies, you can look at the IAT. On Windows you could use dumpbin.exe /IMPORTS or on REMNUX you could use pedump as illustrated below.

dllsearchorder-regiat

But from where will this DLL’s be loaded from? The operating system will locate the required DLL’s by searching a specific set of directories in a particular order. This is known as the DLL Search Order and is explained here. This mechanism can and has been abused frequently by attackers to plant a malicious DLL inside a directory that is part of the DLL Search Order mechanism. This will trick the Windows operating system to load the malicious DLL instead of the real one.  The DLL Search Order by default on Windows XP and above is the following:

  • The directory from which the application loaded.
  • The current directory.
  • The system directory.
  • The 16-bit system directory.
  • The Windows directory.
  • The directories that are listed in the PATH environment variable.

Not all DLL’s will be found using the DLL Search Order. There is a mechanism known as KnownDLLs Registry Key which contains a list of important DLL’s that will be invoked without consulting the DLL Search Order. This key is stored in the registry location HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\KnownDLLs.

Throughout the years Microsoft patched some of the problems with DLL Search Order mechanism and also introduced some improvements. One is the Safe DLL Search Order Registry which changes the order and moves the search of “The Current Directory” to the bottom making harder for the attacker without admin rights to plant a DLL in a place that will be searched first. This feature is controlled by the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SafeDllSearchMode.

Bottom-line, this technique is known as DLL pre-loading, side-loading or hijacking and is an attack vector used to takeover a DLL and escalate privileges or achieve persistence by taking advantage of the way DLL’s are searched. This technique can be pulled off by launching an executable that is not in %SYSTEMROOT%\System32 – like our REGEDIT.EXE – or by leveraging weak Directory Access Control Lists (DACLS) and dropping a malicious DLL in the appropriate folder. In addition, for this technique to work the malicious DLL should contain the same exported functions and functionality has the hijacked DLL or work as proxy in order to ensure the executed program will run properly.  The picture below shows the routines that are exported by the malicious DLL. As you could see these are the same functions like the ones required by REGEDIT.EXE from the CLB.DLL.

dllsearchorder-iat

To further understand the details, you might want to read a write-up on leveraging this technique to escalate privileges described by Parvez Anwar here and to achieve persistence described by Nick Harbour here. Microsoft also gives guidance to developers on how to make applications more resistant to this attacks here.

Considering the REGEDIT.EXE example we can see from where the DLL’s are loaded on a pristine system using Microsoft Windows debugger like CDB.EXE.  Here we can see that CLB.DLL is loaded from %SYSTEMROOT%\System32.

dllsearchorder-regedit

We have now a understanding about how that DLL file might have been loaded. DLL sideloading is a clever technique that load malicious code and is often used and abused to either escalate privileges or to achieve persistence. We found evidences of it using the Prefetch artifacts but without Prefetch e.g., a Windows Server, this won’t be so easy to find and we might need to rely on other sources of evidence like we saw on previous articles. Based on the evidence we observed we consider that the attacker used DLL sideloading technique to hijack CLB.DLL and execute malicious code when invoking REGEDIT.EXE. However, we could not find this DLL file on our system. We will need to look deeper and use different tools and techniques that help us find evidence about it and answer the question we raised in the begging. This will be the topic of the upcoming article!

 

References:
Luttgens, J., Pepe, M., Mandia, K. (2014) Incident Response & Computer Forensics, 3rd Edition
Carvey, H. (2014) Windows Forensic Analysis Toolkit, 4th Edition
Russinovich, M. E., Solomon, D. A., & Ionescu, A. (2012). Windows internals: Part 1
Russinovich, M. E., Solomon, D. A., & Ionescu, A. (2012). Windows internals: Part 2

Tagged , , ,