Adversarial Tradecraft in Cybersecurity - Dan Borges - E-Book

Adversarial Tradecraft in Cybersecurity E-Book

Dan Borges

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Little has been written about what to do when live hackers are on your system and running amok. Even experienced hackers tend to choke up when they realize the network defender has caught them and is zoning in on their implants in real time. This book will provide tips and tricks all along the kill chain of an attack, showing where hackers can have the upper hand in a live conflict and how defenders can outsmart them in this adversarial game of computer cat and mouse.

This book contains two subsections in each chapter, specifically focusing on the offensive and defensive teams. It begins by introducing you to adversarial operations and principles of computer conflict where you will explore the core principles of deception, humanity, economy, and more about human-on-human conflicts. Additionally, you will understand everything from planning to setting up infrastructure and tooling that both sides should have in place.

Throughout this book, you will learn how to gain an advantage over opponents by disappearing from what they can detect. You will further understand how to blend in, uncover other actors’ motivations and means, and learn to tamper with them to hinder their ability to detect your presence. Finally, you will learn how to gain an advantage through advanced research and thoughtfully concluding an operation.

By the end of this book, you will have achieved a solid understanding of cyberattacks from both an attacker’s and a defender’s perspective.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 454

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Adversarial Tradecraft in Cybersecurity

Offense versus defense in real-time computer conflict

Dan Borges

BIRMINGHAM—MUMBAI

Adversarial Tradecraft in Cybersecurity

Copyright © 2021 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Producer: Dr. Shailesh Jain

Acquisition Editor – Peer Reviews: Saby Dsilva

Project Editor: Janice Gonsalves

Content Development Editor: Bhavesh Amin

Copy Editor: Safis Editing

Technical Editor: Aniket Shetty

Proofreader: Safis Editing

Indexer: Manju Arasan

Presentation Designer: Pranit Padwal

First published: June 2021

Production reference: 1070621

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80107-620-3

www.packt.com

Contributors

About the author

Dan Borges is a passionate programmer and security researcher who has worked in security positions for companies such as Uber, Mandiant, and CrowdStrike. He has served in several security roles, from penetration tester to red teamer, and from SOC analyst to incident responder. Dan has been programming various devices for more than 20 years, with 14+ years in the security industry. He has been a member of the National Collegiate Cyber Defense Competition's red team for eight years and a director of the Global Collegiate Penetration Testing Competition for five years.

I'd like to thank several people for their help putting this book together. Alex Levinson, Lucas Morris, Louis Barrett, Chris McCann, Javier Marcos, John Kennedy, and Jess Redberg, for their inspiration and help editing this text. As well as my long time CTF companion, Taylor Leach, who also designed the cover art for this book. There are many more people that I can't fit here but have a deep respect and admiration for.

About the reviewers

Jeff Foley has 20 years of industry experience focused on applied research & development and assessment of security in critical information technology and infrastructure. He is the project leader for Amass, an OWASP (Open Web Application Security Project) Foundation flagship project that performs in-depth attack surface mapping and asset discovery. Jeff is also an adjunct lecturer teaching Penetration Testing at the SUNY (State University of New York) Polytechnic Institute. Previously, he was the US Manager for Penetration Testing and Red Teaming at National Grid, a multinational electricity and gas utility company. Prior to this, Jeff served as the Director of Penetration Testing and Security Assessment at Northrop Grumman Corporation, an American global aerospace and defense technology company. In his spare time, Jeff enjoys experimenting with new blends of coffee, spending time with his wife and four children, and giving back to the information security community.

Joe DeMesy is a principal consultant and red team lead at Bishop Fox. Bishop Fox is a security consulting firm providing IT security services to the Fortune 500, global financial institutions, and high-tech start-ups. In this role, he focuses on penetration testing, source code review, mobile application assessments, and red team engagements. Joe is an active contributor to the open-source community, and co-authored Sliver, a red team adversary emulation framework.

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Theory on Adversarial Operations and Principles of Computer Conflict

Adversarial theory

CIAAAN

Game theory

Principles of computer conflict

Offense versus defense

Principle of deception

Principle of physical access

Principle of humanity

Principle of economy

Principle of planning

Principle of innovation

Principle of time

Summary

References

Preparing for Battle

Essential considerations

Communications

Long-term planning

Expertise

Operational planning

Defensive perspective

Signal collection

Data management

Analysis tooling

Defensive KPIs

Offensive perspective

Scanning and exploitation

Payload development

Auxiliary tooling

Offensive KPIs

Summary

References

Invisible is Best (Operating in Memory)

Gaining the advantage

Offensive perspective

Process injection

In-memory operations

Defensive perspective

Detecting process injection

Preparing for attacker techniques

The invisible defense

Summary

References

Blending In

Offensive perspective

Persistence options

LOLbins

DLL search order hijacking

Executable file infection

Covert command and control channels

ICMP C2

DNS C2

Domain fronting

Combining offensive techniques

Defensive perspective

C2 detection

ICMP C2 detection

DNS C2 detection

Persistence detection

Detecting DLL search order hijacking

Detecting backdoored executables

Honey tricks

Honey tokens

Honeypots

Summary

References

Active Manipulation

Offensive perspective

Clearing logs

Hybrid approach

Rootkits

Defensive perspective

Data integrity and verification

Detecting rootkits

Manipulating attackers

Keeping attackers distracted

Tricking attackers

Summary

References

Real-Time Conflict

Offensive perspective

Situational awareness

Understanding the system

Clear the Bash history

Abusing Docker

Gleaning operational information

Keylogging

Screenshot spy

Getting passwords

Searching files for secrets

Backdooring password utilities

Pivoting

SSH agent hijacking

SSH ControlMaster hijacking

RDP hijacking

Hijacking other administrative controls

Defensive perspective

Exploring users, processes, and connections

Root cause analysis

Killing malicious processes

Killing connections and banning IPs

Network quarantine

Rotating credentials

Restricting permissions

Chattr revisited

chroot

Using namespaces

Controlling users

Shut it down

Hacking back

Hunting attacker infrastructure

Exploiting attacker tools

Summary

References

The Research Advantage

Gaming the game

Offensive perspective

The world of memory corruption

Targeting research and prep

Target exploitation

Creative pivoting

Defensive perspective

Tool exploitation

Threat modeling

Operating system and application research

Log and analyze your own data

Attribution

Summary

References

Clearing the Field

Offensive perspective

Exfiltration

Protocol tunneling

Steganography

Anonymity networks

Ending the operation

Program security versus operational security

Taking down infrastructure

Rotating offensive tools

Retiring and replacing techniques

Defensive perspective

Responding to an intrusion

The big flip

The remediation effort

A post-mortem after the incident

Forward looking

Publish results

Summary

References

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Preface

This book provides some theories and tools to prepare readers for the fast-paced and subversive world of cyber conflict. This book is designed to give competitors in various infosec attack and defense competitions a serious advantage, through providing theory, scripts, and techniques that will put the opponent on the backfoot. These same strategies can easily be applied to a real-world cyber incident, giving incident responders new tricks to deceive and best attackers. This book draws from years of competition experience, many well-accepted industry concepts, and existing open source tools rather than reinventing the wheel each chapter. The goal of Adversarial Tradecraft in Cybersecurity is to dive deep into both deceptive attacker techniques and detections. This text starts with a chapter on theory to help prepare readers for the following chapters, followed by a chapter focused on setting up supporting infrastructure. After that, the book works through various escalating techniques that may be leveraged by either side in a cyber conflict. Chapters 3 through 8 cover tactics, techniques, and tools that both sides can leverage to get the advantage in a conflict. Chapter 8 specifically goes into how to resolve a conflict and remediate an intrusion such that the attacker doesn't maintain access. A synopsis of each chapter can be found below, covering some of the high-level topics included in the book.

Who this book is for

This book is for intermediate cybersecurity practitioners, from defensive teams to offensive teams. This book can still be utilized by beginners, but it may require the aid of some heavy googling to get the required background information on topics I cover quickly. This book is designed to give practitioners an advantage in attack and defense competitions, such as the Collegiate Cyber Defense Competition (CCDC), although many of these techniques can be used in a real conflict or breach scenario.

What this book covers

Chapter 1, Theory on Adversarial Operations and Principles of Computer Conflict: This chapter is all about theory and setting the reader up with guidance for future chapters. This chapter covers topics such as adversarial theory, CIAAAN attributes, game theory, an overview of offense versus defense in computer security, various competitions these principles can be applied in, and seven additional principles of computer conflict.

Chapter 2, Preparing for Battle: This chapter is all about preparing for a competition, operation, or engagement. This chapter covers topics such as team building, long-term planning, operational planning, infrastructure setup, data collection, data management, KPIs, and tool development.

Chapter 3, Invisible is Best (Operating in Memory): This chapter is all about process injection, hiding in memory, and detecting process injection techniques. This chapter covers topics such as the offensive shift to memory operations, process injection with CreateRemoteThread, position-independent shellcode, automating Metasploit, detecting process injection, configuring defensive tools, and detecting malicious activity behaviorally.

Chapter 4, Blending In: This chapter is about the trade-off between in-memory operations and blending into normal activity. This chapter covers topics such as LOLbins, DLL search order hijacking, executable file infection, covert command and control (C2) channels, detecting covert C2, DNS logging, detecting backdoored executables, and various honey techniques.

Chapter 5, Active Manipulation: This chapter is about actively tampering with your opponent's tools and sensors to deceive your opponents. This chapter covers topics such as deleting logs, backdooring frameworks, rootkits, detecting rootkits, and multiple methods for deceiving attackers.

Chapter 6, Real-Time Conflict: This chapter is about gaining the advantage when two operators are actively on the same machine. This chapter covers topics such as situational awareness, manipulating Bash history, keylogging, screenshots, gathering passwords, searching for secrets, triaging a system, performing root cause analysis, killing processes, blocking IP addresses, network quarantine, rotating credentials, and hacking back.

Chapter 7, The Research Advantage: This chapter is about gaining the advantage through research and automation during downtime. This chapter covers topics such as dominant strategies in CTFs, memory corruption, offensive targeting, software supply chain attacks, F3EAD, clandestine exploitation, threat modeling, application research, data logging, and attribution.

Chapter 8, Clearing the Field: This chapter is about ending the conflict and remediating a compromise. This chapter covers topics such as exfiltration with protocol tunneling, steganography in exfiltration, various anonymity networks, program security, rotating offensive tools, fully scoping an intrusion, containing an incident, remediation activities, post-mortem analysis, and forward-looking activities.

To get the most out of this book

This book is designed to prepare cybersecurity practitioners for a real engagement or an attack and defense competition.If you want to try any of the exploits or techniques in a lab setting, I recommend setting up VirtualBox with Kali Linux and Metasploitable 3.Readers should be familiar with basic security assessment and hardening techniques, such as known vulnerability identification and patching.Readers will also encounter a wide variety of languages in this book, such as Bash, PowerShell, Python, Ruby, and Go. Readers are encouraged to play with these programs and languages on their own, and to google language-specific operators they are unsure about.

Download the example code files

You can download the example code files for this book from: https://github.com/PacktPublishing/Adversarial-Tradecraft-in-Cybersecurity.

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801076203_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input. For example, "Just make sure after you compile the older version of Nmap that you move it to its proper location in /usr/local/share/nmap/."

Italics: Indicates an important author, larger work, or emphasis on a particular point in the text. For example, "The logic for this largely comes from Jeff McJunkin's blog post where he explores ways to speed up large Nmap scans."

Bold: Indicates an important concept, important words, or principles that will be referenced more throughout the text. Bold is also used to highlight callbacks later to enforce the emphasis from a previous mention. For example, "Confidentiality is the ability to keep communications secret."

A block of code is set as follows:

//Prep vars logFile := "log.txt"; hostName, _ := os.Hostname(); user, _ := user.Current(); programName := os.Args[0];

Any command-line input or output is written as follows:

$ sudo tcpdump -i eth0 -tttt -s 0 -w outfile.pcap

The following symbols represent different command-line context:

$ for user level access on a Linux system# for root level access on a Linux system> for an Administrative Windows command prompt

Warnings or important notes appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected], and mention the book's title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

1

Theory on Adversarial Operations and Principles of Computer Conflict

In this chapter, we are going to begin our examination of adversarial computer security strategy. We will be taking a deep look at how two opposing sides can best fight over a computer network. As we examine various strategies throughout this book, we will need structures to help us analyze and process the exchanges between parties. For that, we will start by defining several attributes that can be used to help us evaluate our various computer security strategies. These are attributes that we will use in this book to show how one strategy has a tactical advantage over another. Next, we will briefly look at game theory, the study of strategy in conflict, to understand concepts of reaction correspondence and dominant strategies. These ideas will be crucial as overall themes and goals in this book. Following that, I will present a few models to help analyze our strategies and the reaction correspondence between the players of the game. These are structures we can use to show how different strategies interact with one another. We will also examine the players of our game to better understand the roles of offense and defense. We will get a brief glimpse of the various skills and tools that make these unique positions, making the game of computer security conflict quite asymmetric at the higher levels. We will examine scenarios where we can apply our strategies, specifically with attack and defense competitions or in a real conflict. Finally, we will look at several principles of computer conflict that will guide us towards advantageous strategies. While these principles of conflict, such as deception and economy, are key to all conflicts, we will look at them from the unique perspective of computer systems.

The tools and mental models we gain in this chapter will be used throughout the rest of the book to analyze the various strategies we examine. The later chapters of this book will look at in-depth computer attack techniques as well as techniques to detect and counter these attacks. To summarize what this chapter will be covering more succinctly, we will explore the following ideas:

Adversarial theoryCIAAAN attributesAn introduction to game theoryPrinciples of computer conflictOffense versus defensePrinciple of deceptionPrinciple of physical accessPrinciple of humanityPrinciple of economyPrinciple of planningPrinciple of innovationPrinciple of time

Let's begin our cybersecurity journey with an introduction to adversarial theory.

Adversarial theory

Computer security can be such a complex topic that it is often difficult to discuss in terms of dominant high-level theory. Every few years, new strategies emerge in both offense and defense, and after three decades, there is no clear winner of the dominant strategy in the space. The industry is still nascent in terms of a dominant cyber strategy, yet some strategies routinely outperform others in this evolutionary landscape. In this book, I will take a similar approach to game theory in that I will analyze some of the best possible strategies each side can use. I will break down why each strategy is optimal for a given situation, along with some strategies that can counter these techniques when used by the opposition. Examples of the strategies shifting over time can be seen on the defensive side in every new cycle of startups. For example, a very clear shift can be seen in vendor dominance moving from traditional antivirus solutions focused on specific malware samples to vendors providing endpoint detection and response frameworks for clients to implement detection operations in their own environments.

Another defensive vendor shift can be seen in the move from exploit detection to a focus on detecting post-exploitation tradecraft. It is not that these vendors wholly fail to stop compromises with their solutions, rather that they don't live up to the over-promised hype and no one strategy has dominated this sphere of conflict. These examples of shifting strategies can also be seen on the offensive side, such as migration from the use of PowerShell scripting language as the dominant post-exploitation language to C# and other compiled languages that can still leverage .NET Framework on Windows. Another example is the shift from the criminal activity of cultivating and selling access to botnets to using ransomware on an entire network for a quick, high-gain profit. This book aims to analyze why these shifts occur as each side finds new optimal strategies. Due to the technical depth of some of the strategies I will often reference more authoritative sources, as not all of the background technologies can be explained in this book. This text aims to present several concepts, theories, and techniques that will give you a strategic advantage in a computer conflict, either in a game setting or with a real attacker. I plan to explore both sides of the asymmetric conflict, as each side has a unique set of skills and tools that should be understood to form the best possible strategy.

CIAAAN

To help analyze the strategies of this game, we will need some basic elements of information security to use as building blocks. For our basic properties of information security, we will use the classic attributes of confidentiality, integrity, availability, authentication, authorization, and nonrepudiation. I will briefly define them here, and I am basing these definitions on the 2008 Carnegie Mellon University memo by Linda Pesante titled Introduction to Information Security[1]. In that memo, Linda defines these six attributes as crucial to cybersecurity, and we will revisit them throughout this book. We will refer to these six elements as the CIAAAN attributes:

ConfidentialityIntegrityAvailabilityAuthenticationAuthorizationNon-repudiation

Confidentiality is the ability to keep communications secret. We will see how confidentiality plays a huge role in most data transport as well as command and control (C2) that we use throughout the book. Integrity refers to our ability to ensure information remains what we intend it to be. This means that commands, logs, files, or any information that we set remains true to its intended setting.

We will see this play a large role when we start to backdoor files and tamper with logs. Availability is a core element that means we can access the data or service in question. Compromised availability means that the device is generally unusable by a certain party. We will see this play a role when a defender quarantines a device from an attacker, or if an attacker kicks a defender out of a device temporarily. Authentication and authorization are technically two very different elements: Authentication defines how you prove your identity and authorization defines what you can access with that identity. However, for the sake of simplifying the conversation, we will generally refer to these as a single identity-based element. Finally, non-repudiation, or the ability to state historically that an event has happened, is a critical attribute. Non-repudiation is essentially creating logs or receipts for an event. Non-repudiation is an often-overlooked element, but we will learn throughout this book how crucial it is to log events, as these logs will become our eyes and ears into the digital world. Some evidence is often not captured by any log source; it can be extremely short-lived and ephemeral, such as data held in RAM. If such temporal forensic data is not captured or analyzed soon, it will be lost, thus an effort to log all critical security data we explore will prove useful in our hunts. Using these CIAAAN attributes will help us evaluate our strategies throughout the text.

Game theory

Game theory (GT) is a form of analytic discipline in which the optimal strategies of a game are studied for various players. Essentially, GT attempts to find the best response a player could make in a given situation[2]. GT often focuses on simple games in which basic strategies can be empirically determined as the best. This is because simple games in GT can be expressed as mathematical notation, only requiring three basic inputs: the players of the game, the information and actions available to them at decision points, and the consequences of those decisions. I will attempt to approximate the information available to the players and the consequences of the decisions using the CIAAAN attributes. We can use these approximations to make generalized theories about which strategies are stronger with GT. Games within GT often revolve around conflict or cooperation, in which multiple players must choose their best response among other competing players to be victorious. In GT, a non-cooperative game is a game in which players typically compete for their individual best possible outcome. I will show readers how some strategies can play to certain principles of conflict, and thus remove CIAAAN attributes from their opponents. When you remove CIAAAN attributes from your opponent in what is essentially information-based conflict, you gain the opportunity to manipulate or expel them from your environment, which is often the end goal of these conflicts. We will use these attributes to search for dominant moves or strategies that naturally best other opposing strategies[3].

Opponents may also develop strategies for their optimal play. This back and forth of shifting strategies is known as reaction correspondence[2]. We will explore several of these evolutions and show how optimal strategies may become suboptimal after a certain reaction correspondence occurs. A simple way to think about reaction correspondences is as the defense shifts to attempt to counter the offense, the offense must shift again to regain the upper hand. When each opponent or adversary chooses the best possible response for their opponent's best response, a state is reached known as the Nash equilibrium, or optimal play for both sides in a non-cooperative game[4]. We will use other techniques in this chapter, such as kill chains and attack trees, to help model these reaction correspondences.

Modern computer security is likely too complicated to have a perfect Nash equilibrium, due to the number of variables at play. There are extremely complex technology stacks at work and such complexity adds vulnerabilities and uncertainty into the equation. When large teams of people and complex technologies work together, many vulnerabilities are often introduced because of human error or configuration errors, sometimes known as system complexities. Cybersecurity is a deeply complex form of a non-cooperative, asymmetric game in which certain strategies can outperform other strategies. At its base, it is different parties trying to exert their will on a computer network, taking advantage of whatever vulnerabilities they may find and manipulating controls at their disposal. I am not sure I have seen a single dominant strategy in the reality of modern computer security. Usually, each side is so rife with errors that the games played are far from optimal. Like the game of American football, even at the professional level, there are mistakes, and a perfect game is rarely ever played. There are also some strategies that are highly effective against other strategies, such as using machine learning on user behavior or honey tokens to detect Lightweight Directory Access Protocol (LDAP) enumeration. A good example of using an effective dominant strategy is using Microsoft ATA to detect Bloodhound enumerating Active Directory[5][6][7]. I have seen high-security environments where layered controls have created a legitimately imposing defense, and in my experience, even these environments still have vulnerabilities and abuse issues.

We will also see how both sides are realistically limited on resources and options, so they must choose a small subset of their total plans to carry out. No team is as good as their best plan; rather, they are as weak as their most lax control or weakest link. Often this is acceptable for certain operations because there can be a lot of room for error on both sides, although you must be careful about operators getting complacent. To counter this error, team members should review each other's work and have both operational standards and programming standards that they are held to. You should also analyze which strategies routinely outperform other strategies and adapt your defensive strategies to perform as well as possible.

High-performing teams will study emerging techniques and use their research time to see how they can step up their individual gameplay by shifting with the features of the landscape or evolving strategies. We will cover many competing strategies in this book and see how they perform when stacked up against opposing strategies, highlighting various tradeoffs along the way.

Principles of computer conflict

Fundamentally, I view computer security conflict as a human-on-human conflict, albeit with the aid of technical tools. Automated defenses or static security applications ultimately suffer from being breached by intelligent hackers, and thus the strategy of defense in depth has developed. Defense in depth involves layering security controls so that in the eventuality that a single control is breached, the offensive efforts can still be prevented, detected, and responded to by further layers of controls[8]. This means defensive controls are placed throughout the network to detect attacks wherever they may be in their life cycle. This defensive strategy was developed after years of continually relying on a hardened external perimeter, which continually led to undetected breaches. Now, as the offense develops their strategy to pivot through this infrastructure, the defense will similarly develop a strategy to detect the abuse of and enforce the controls throughout their network. These models of opposing offensive and defensive strategies are popularly known as kill chains. Cyber kill chains are a Lockheed Martin evolution of classic military kill chains, showing the steps an attacker needs to carry out to achieve their goals and the best places to respond from a defensive standpoint[9]. While many parts of this kill chain can be automated, ultimately it is up to humans to pivot, respond to, and control any event that may arise. Kill chains are effectively a model to help visualize attack paths and formulate defensive strategies. We will also use an analog form of kill chains throughout the book known as attack trees. Attack trees are simply conceptual flow diagrams for how a target may be attacked. Attack trees will be useful for exploring decision options in a reaction correspondence and for seeing what either side may choose to do as a result[10]. Using kill chains for high-level strategic planning and attack trees for working out technical decision-making will give us models for analyzing our strategies moving forward[11]. Figure 1.1 shows an example of attack trees mapped to a kill chain from the original paper in which this combination was proposed[11], A Combined Attack-Tree and Kill-Chain Approach to Designing Attack-Detection Strategies for Malicious Insiders in Cloud Computing. In this example, they are showing an attacker installing a network tap to exfiltrate data:

Figure 1.1: Attack trees mapped to kill chains from A Combined Attack-Tree and Kill-Chain Approach to Designing Attack-Detection Strategies for Malicious Insiders in Cloud Computing

While many principles of conflict will remain the same, ultimately this conflict takes place in a new, digital domain, which means that different laws and axioms apply to it, and often knowing these mechanisms better will give either side an advantage. This digital landscape is still evolving every day but is also built on a rich history of technology.

While it was once difficult to find cheap, dynamically scalable hosting and IP addresses on the internet, now multiple vendors offer these services and many more in what is known as the cloud. The cloud is just various virtually hosted and dynamically scaled Linux technologies. This shifting and evolving digital landscape has many rules and laws of its own, many of which will be considered crucial background knowledge for this text. It is expected that readers have a basic understanding of operating systems, executable files, TCP/IP, DNS infrastructure, and even some reverse engineering. One of the beautiful aspects of computer security is that it is a great confluence of so many different disciplines, from human psychology to criminology and forensics, to a deep technical understanding of computer systems. A solid grasp of the underlying concepts is important for computer conflict strategy at the higher levels. You need to know what can go wrong with the system to be able to verify everything is running properly.

Many of the strategies I cover in this book will be considered advanced in the sense that there are basic operational techniques that will be assumed, such as generally knowing how to perform network reconnaissance[12] or a basic understanding of command and control infrastructure[13]. When I cover an assumed technique, I will try my best to link to a resource that conveys what I am assuming. I will also show many examples of the Python, Ruby, and Go programming languages, yet I will not explain the basics of these languages. It is assumed the reader is generally familiar with these languages, which you can find in the References section at the end of the chapter for Python[14] and Go[15].

I won't be using advanced programming techniques in any of the languages, but readers are encouraged to look up basic operators to help understand the programs better. I will also reference many attacker techniques but will often not have the space to describe every technique in great detail. To help further define attacker techniques, I will refer to the MITRE ATT&CK matrix when referencing attacks[16]. This text will also reference as many open-source examples of techniques as possible. In those situations, I will often refer to their GitHub projects, and credit should go to all of those who have worked on those projects. All this is to say, if I mention a technology you are unfamiliar with and do not describe it in enough detail, please Google it on your own as it will help with the overall understanding of the theory or technique I am describing. One reason we study the offense so deeply in computer security is that knowing the attacker's available technical options helps the defender optimally strategize.

Offense versus defense

The game of computer security is fundamentally asymmetric because different technologies, skills, and strategies are optimal for the opposing sides. While we will see that various tools, skills, and strategies exist at the base of both sides, ultimately each side leverages specialized technology that should be specifically accounted for. In the military sphere, the arena is often described as computer network operations (CNO) with two distinct sides, computer network attack (CNA) and computer network defense (CND). We will be referring to these sides throughout the book as offense and defense, and we will define their roles and tools on the network much better throughout the book. While we can draw parallels between their strategies, they are often fundamentally different in how they go about achieving their goals. As a very quick example, the defense will set up multiple forms of monitoring and auditing, using technologies such as OSQuery, Logstash, ELK, or Splunk. The offense will often invest in completely different infrastructure stacks for scanning and pivoting their control, using technologies such as Nmap, OpenVAS, Metasploit, or proxychains as basic examples. It's important to remember that while many of the operating systems and technologies involved can be similar, each unique side will employ very different strategies and techniques to accomplish its objectives. This is also not a zero-sum game in that objectives can be accomplished to a varying degree of success on each side, and each side can be successful or unsuccessful in a certain sense regarding the conflict. For example, the offense can get some of the data they were searching for before the defense expels them, while the defense can also be successful in defending their primary goal, such as uptime or protecting specific data. Just because data is stolen (loss of confidentiality) does not mean the original owner loses access to it (loss of availability); confidentiality and availability are two different CIAAAN attributes.

This means that if a defender cares most about uptime or business continuity, they could be breached, have their data stolen, expel the attacker, and still consider it a partial win from a defensive perspective. Throughout this book, we will examine how different strategies target different CIAAAN attributes to achieve their end goals, from both of the unique perspectives of offense and defense.

The defensive team is defined by the role of protecting the data, network, and computing available to the organization. It is most often referred to as the blue team, the incident response team, the detection team, or even just the security team. Their main method of determining nefarious activity on their network is often through setting up elaborate systems of centralized monitoring and logging tools throughout their computing environment. Typically, they have some level of management interface to their environment or fleet, such as SCCM on Windows, Puppet, or Chef in general. This level of host management will allow them to install and orchestrate more tools to set up their monitoring. Next, they may install or utilize tools to help them generate richer logs, more security-relevant logs, such as OSQuery, AuditD, Suricata, Zeek, or any number of EDR solutions. Next, they would install log aggregation tools to help bring all of this data back to a central location. These are often tools such as filebeat, loggly, fluentd, or sumo logic, tools that collect logs from around the network for centralized correlation and analysis. Finally, the blue team is ready to detect nefarious actions on their network, or at least understand when things may be going wrong. In an incident response situation where external consultants need to come in, it will often be a more aggressive and shorter timeline than that already described. External incident responders will come in with ready-made scripts to deploy their tools and simply begin collecting forensic logs from all the hosts they can. In-house defenders have more time to set up richer monitoring, and we will see that this will give them an advantage in the conflict. One advantage that external consultants often have is they may have unique intelligence or tools from responding to many similar incidents. As is often the case, these battle-hardened consultants may be better equipped with both tools and expertise than the in-house team, and it makes a huge difference. Regardless of the source of the defense, their mission is often the same: protect operations and expel any potential threat or offense.

Offense, on the other hand, is defined as the aggressor in this situation, the group attacking the computer systems. They can be a red team, a team competing in a competition, or even a real adversary, really any group or person attacking a computer network. However, this book is not for your typical red team or pentest team. What will unite the offense throughout this book is their use of guile and deception to gain the advantage. The tools used in these types of attack and defense competitions are not always the typical penetration testing tools. Just as not all vulnerability scans are pentests, and not all pentests are red teams, not all red teams are well equipped or have the right set of skills for this out of the gate.

We will be using a number of tools to obfuscate, persist, and even mess with the blue team, not something your average red team does. Even some adversary emulation tools are not up to par, as they will have some type of tell or work in a restricted manner. One of the conference talks that best embodies the spirit of this book or the red teams I imagine in this book is Raphael Mudge's Dirty Red Team Tricks[17]. A lot of the techniques he covers in that talk are from the National CCDC Red Team, so we will see a lot more content like that throughout this book. It is also important to keep in mind that this is not necessarily purple teaming. Purple teaming is when a red team and a blue team work together in tandem to improve a blue team's ability to detect various techniques. In purple teaming exercises, both teams are essentially working together to generate more high-fidelity alerting. In a purple team, the red team's goal is to paint a target by emulating a threat and help the blue team hit that mark by detecting the emulation. Here, we will discuss ways for the offense to gain the upper hand or for the defense to recognize and counter their opponent's plan of action. The strategies we will discuss in this book are to give one side or the other the advantage in a conflict. It is an important distinction to keep in mind as you read. This will also allow us to explore dirty, underhanded, or deceptive tricks that would likely be off-limits in a purple team exercise. I do think purple teams can learn a lot from reading this text and studying the strategies we discuss on both sides, but it is important to note that this is fundamentally not purple teaming.

There are many different strategies in the field of cybersecurity, both on offense and defense. Each of these strategies often comes with a tradeoff, even if that tradeoff is the complexity of the technique. While advanced strategies can excel in a particular scenario, for example using process injection when there are no EDR or memory scanning technologies at play, they sometimes come with drawbacks against a further reaction correspondence. Process injection is a great example of a technique that excels at disappearing from traditional forensic log sources, but when you are looking specifically for process injection techniques with capable tools it tends to stand out from other programs. We will take a deeper look at the reaction correspondence around process injection more in Chapter 3, Invisible is Best (Operating in Memory).

To take another example on the defensive side, there is a prevailing notion of endpoint security, or moving the bulk of the detection logging activity to the host. This could help detect endpoint compromise and recon from the endpoint, as well as detect memory injection and overall privilege escalation techniques. This reaction correspondence could then make using the technique of process injection less desirable because the attacker would lose some confidentiality and the defender can gain non-repudiation in the new scenario. We will cover this reaction correspondence specifically later in the book. This also goes against an older defensive strategy that was very popular a few years ago: network-based defense.

Endpoint-focused defensive controls can help you in a large decentralized network, such as the modern working-from-home environment, whereas a network-based strategy was designed to help you uncover and detect the new endpoint compromise possibilities you may not know about or endpoints that are not managed in your environment. These tradeoffs in defensive strategies are evident, both possessing unique opportunities and blind spots. We will cover both strategies throughout the book, showing where each excels and lacks in a particular scenario. A network-based defense can help normalize traffic and provide additional controls like deep packet inspection, whereas endpoint-based defense can provide on-the-fly memory analysis. Each one offers different benefits and comes with different performance tradeoffs. Throughout this text, we will explore how different strategies exemplify various principles or can remove the core elements of security from the opponent, giving certain defender strategies a clear benefit versus popular attacker strategies.

Similarly, from the offensive perspective, two exceedingly popular strategies exist for lateral movement: low and slow when moving around the network, or aggressively compromising and dominating the network. While being highly aggressive can work in a short-lived engagement cycle, such as an attack and defense competition or a ransomware operation, it is generally not a good long-term strategy as it will alert the defender to your presence. We will examine some scenarios where an aggressive offensive strategy can be successful, but generally, we will see the defender dominate these scenarios in the long run as they will have physical access, and thus completely control all availability and integrity in the infected hosts. The average pentest team tends to fit the same profile as a highly aggressive threat actor as they simply don't have the time to budget for stealthy threat emulation and defense evasion. We will also examine a few short-lived scenarios where the attacker can dominate for a short period of time or buy themselves access for a little longer, such as in attack and defense competitions. In some of those short-lived scenarios, the attackers may even induce havoc on the network to cause disruption, but make no mistake, these are planned routines, and they are not flailing around or trying random attacks. After those examples, a lot of this book will focus on various low and slow offensive strategies, showing attackers how to hide and deceive their opponent into thinking they are not compromised. These threat profiles better fit internal red teams and real threat actors as they can budget the time and expenses to go through the reaction correspondence with the defensive team. We will explore several advanced low and slow strategies that focus on deceiving and hiding from the opponent. By subverting the defender's controls, the offense will be able to operate for longer and with more freedom, knowing they are not being detected with routine hunting operations. Similarly, the defenders should learn how to recognize these signs of deception and sow their own seeds of disruption. From a defensive perspective, it is far better to hypothesize attacks, model these scenarios, and play-test response plans to identify your own blind spots before the attackers arrive.

A lot of my experience here is drawn from over eight years of attack and defense competitions. I have played in up to four of these competitions in a single year, along with numerous other capture the flag (CTF) competitions and red team operations for my day job. These real-time attack and defense competitions have been a major part of my last decade and are quite different from a traditional cyber CTF. Attack and defense competitions can be thought of as a real cyber wargame, where one group defends a computer network and another group attacks that network. Each competition normally has a different implementation of these core rules, but the game is generally a group of people on each side trying to defend or attack certain data on a given computer network. These events can be extremely competitive, where sides can sometimes game the game, but often there is a complex series of rules and escalating strategies, played out in real time. The tools are often vastly different from traditional red teaming or CTF tools, with these tools focusing on command and control, persistence tricks, and even trolling. This experience is vital because it offers a time-boxed conflict where sides can explore various offensive or defensive strategies in a zero-consequences environment. They can then iterate on these experiences and develop their strategies in quicker loops than real engagements. This means sides can be creative and try different strategies to explore those given tradeoffs in a real conflict scenario. Furthermore, my experience here is drawn from real-life incident response investigations, where attackers have been deceived into making mistakes or revealing their identities, resulting in them being expelled from the environment and brought to justice in some cases. These real conflict scenarios generally require a longer time to incorporate the lessons learned, such as several months to a year to see feedback, in contrast to short-lived, weekly competitions. While I generally have extensive red team and purple team experience as well, I think that is less directly applicable as any advantage achieved there is usually limited for the benefit of the customer. While many of the common skills and tools for identifying and exploiting vulnerabilities are the same, these are just a means to our end goals on the offense in an attack and defense competition. Our true goal on the offense is to persist undetected in the environment while accessing our target resources for as long as possible, for which we often use tools that are not used in a traditional pentest. While these tools can be part of threat emulation frameworks, operators need to be intimately familiar with the techniques on their own. I mean to say that penetration testing is often fundamentally different from these attack and defense competitions because the motivations and outcomes are not always the same as in direct competition. I suppose it depends how competitive the red teaming can get, but I would generally bucket red teaming and purple teaming into different categories as I typically do not see them going to such extreme measures as we will explore in this book. That said, real cyber conflict experience is invaluable in this arena.

I am most familiar with CCDC, or the Collegiate Cyber Defense Competition, where I have been on the national level red team for eight years, competed in over a dozen CCDC events, and led the red team in the Virtual Region for three years now. In CCDC, college students play as dedicated network defenders, and our team of volunteers plays the offense in an attack and defense competition[18]. The network environment is often unknown to both teams, and both teams start at the same time. This gives an advantage to the attackers as they can scan the infrastructure and pivot to exploiting vulnerabilities quicker than the defensive teams can access, understand, and secure each individual machine on their newly inherited network. Still, the defending team often evicts the attackers by the end of the competition and gains the upper hand over the next 48 hours. The national-level red team for CCDC consists of some of the best offensive security engineers from around the United States, each bringing signature techniques and tools that have been honed over years of playing in this event. On the national red team, I write and support a few tools, including a global Windows malware dropper we used for a number of years. This Windows-based implant has gone through several evolutions, from using script-based languages such as PowerShell to using custom loaders, individually encrypted modules, and loading further implants into memory. We have also drastically expanded on our covert command and control channels that we use in our backdoor infrastructure. This CCDC competition was part of the inspiration behind the tool Armitage, which became the popular post-exploitation framework Cobalt Strike, written by Raphael Mudge on the CCDC red team in 2010[19]. We will look at this evolution of tools and show how some strategies routinely outperform others even when under the direct scrutiny of the blue team. In this book, we will discuss a number of strategies both sides can use in such a conflict, many of which I have seen used firsthand.

I am also familiar with playing both sides of the spectrum from playing in Pros V Joes (PvJ), a popular attack and defense competition run at various American BSides security conferences[20]. I've played in PvJ for over five years, three years as a Joe competitor on a team and two years leading a team as a Pro. PvJ is unique in that each team has a similar network to defend but can also attack the other team. The scoring in the game is based on your own team's uptime, so it is far more important to play defense than offense. There are typically four teams and about eight services each team needs to support throughout the competition. Each team has roughly the same network, ten players, and two days of game time, with points going to your team for uptime, solving business injects, and with points getting taken away when you have an active compromise scored by another team. On the team, the actual roles of defense and offense in terms of what players in these positions will be doing are unique and independent to their roles. For this reason and a few others, I like to have my team focus on defense first, and offense when we have the opportunity for spare cycles.

Generally, I will split my team 80/20 with the bulk of my team working defense in terms of expertise and preparation time (which we will spend a lot of time discussing in the next chapter). There are a few reasons for this. Mostly, it is harder to work back a compromise than to attack and still find vulnerabilities later in the game. That means if we focus on defense upfront, we can shift more people to offense later if we think we are reasonably secure. The team in PvJ wants to be reasonably assured we are operating from a position of security, otherwise our own attacks and offensive operations can be easily thwarted if we lack confidentiality in our actions and infrastructure. Playing in PvJ or any attack and defense competition for that matter can be very stressful, as you are simultaneously trying to secure your environment while responding to live attackers on your systems. This oversaturation of tasks and lack of resources to do it all is one of the core tenets of these attack and defense competitions, and a major reason we will focus on strategies that put your opponent (the offense) on the back foot even when they compromise a server. Any time you can buy between when a server gets compromised and the attacker pivots to their goals is critical time you can use to detect and respond to the attacker before they can make a major impact.

Finally, aside from running many red team operations throughout my career, I have been involved in numerous incident response engagements with real threat actors. I tend to view real incident response conflicts as more closely related to real offense versus defense than traditional red team exercises (the gloves are normally still on when running legitimate red team operations). Real incident response is often a no-holds-barred type of competition in which the stakes are very real: getting data or assets stolen as the blue team and getting expelled or facing legal repercussions for the red team. Real incident response operations often involve highly competitive tricks to get an advantage over the attackers and bring them to justice, which we will explore throughout this text. Such gloves-off techniques may involve using honey pots to catch the attackers, reverse engineering the attacker's tools to find errors or vulnerabilities in them, and even hacking back the attacker's infrastructure to gain more intelligence on their operations. These gloves-off operations will be the majority of what we explore with this book. This means getting the advantage over your opponent, sometimes in an unfair way, and leveraging this advantage to win the game. For example, the defense or blue team would likely not backdoor their own code base for a red team exercise, but they might if someone was routinely stealing their code and they wanted to covertly discover where the code was being compiled or run. Such techniques do not really fit in an exercise where the end goal is to harden the environment or increase the organization's overall security insights. However, these techniques can shine in a real conflict and sadly are often overlooked in the industry as available options. Many red teams don't focus on the malware or the same tricks of the trade that real attackers focus on. This text will focus on the more devious tricks that both offense and defense can use but often don't unless in a real conflict.

Next, I am going to touch on several principles or themes that I will be referencing throughout this book. The Oxford English Dictionary defines a principle as "a fundamental truth or proposition that serves as the foundation for a system of belief or behavior or for a chain of reasoning." I am going to put forth several principles or themes that will be leveraged throughout this book in our various strategies. These principles exist on both sides of the game, and they can lend the advantage when leveraged effectively and limit your opponent's available options at any given time. None of these are required to carry out operations; however, if you use them in your operations you are likely to gain an advantage by adhering to them in some way. While these themes are