You are on page 1of 67

Gray Hat Hacking: The Ethical Hacker's

Handbook, 6th Edition Allen Harper


Visit to download the full and correct content document:
https://ebookmass.com/product/gray-hat-hacking-the-ethical-hackers-handbook-6th-e
dition-allen-harper/
Praise for Gray Hat Hacking: The Ethical
Hacker’s Handbook, Sixth Edition

“Offensive security covers such a broad array of topics that it can be


extremely difficult to find reference material that provides even
surface-level coverage of it. Gray Hat Hacking: The Ethical Hacker’s
Handbook, Sixth Edition manages to cover a surprisingly large
subset of specialist areas within the field, all while diving deep
enough to shine a light on some of the more interesting and
challenging nuances of those areas. It’s a worthy addition to the
hacker’s bookshelf.”
—OJ Reeves
Director, Beyond Binary
“This book has been a staple of the development and careers of
many, and its sixth edition delivers on expectations with fresh
material and content to help push people to the next level. It’s a
phenomenal contribution to anyone’s skill set and written by true
experts; Stephen Sims and the other authors are people that I
respect and routinely read whatever they put out. Readers will find
this to be a practical resource worthy of any bookshelf of any
practitioner in our field.”
—Robert M. Lee
Senior SANS Instructor and CEO/Co-Founder of Dragos, Inc.
“The chapters on Hyper-V in Gray Hat Hacking: The Ethical Hacker’s
Handbook, Sixth Edition are the most complete public resources I
have seen to date. Not only do they provide a general overview of
the architecture, they also provide in-depth scripts that can be used
to understand the internals very well. I’m very impressed with all of
the resources attached to these chapters. If you are interested in
hypervisors and/or Hyper-V in any form, give this book a shot.”
—Matt Suiche
Founder, Comae
Copyright © 2022 by McGraw Hill. All rights reserved. Except as
permitted under the 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 publisher, with the exception that the
program listings may be entered, stored, and executed in a
computer system, but they may not be reproduced for publication.

ISBN: 978-1-26-426895-5
MHID: 1-26-426895-5

The material in this eBook also appears in the print version of this
title: ISBN: 978-1-26-426894-8, MHID: 1-26-426894-7.

eBook conversion by codeMantra


Version 1.0

All trademarks are trademarks of their respective owners. Rather


than put a trademark symbol after every occurrence of a
trademarked name, we use names in an editorial fashion only, and
to the benefit of the trademark owner, with no intention of
infringement of the trademark. Where such designations appear in
this book, they have been printed with initial caps.

McGraw-Hill Education eBooks are available at special quantity


discounts to use as premiums and sales promotions or for use in
corporate training programs. To contact a representative, please visit
the Contact Us page at www.mhprofessional.com.

Information has been obtained by McGraw Hill from sources believed


to be reliable. However, because of the possibility of human or
mechanical error by our sources, McGraw Hill, or others, McGraw Hill
does not guarantee the accuracy, adequacy, or completeness of any
information and is not responsible for any errors or omissions or the
results obtained from the use of such information.
TERMS OF USE

This is a copyrighted work and McGraw-Hill Education and its


licensors reserve all rights in and to the work. Use of this work is
subject to these terms. Except as permitted under the Copyright Act
of 1976 and the right to store and retrieve one copy of the work,
you may not decompile, disassemble, reverse engineer, reproduce,
modify, create derivative works based upon, transmit, distribute,
disseminate, sell, publish or sublicense the work or any part of it
without McGraw-Hill Education’s prior consent. You may use the
work for your own noncommercial and personal use; any other use
of the work is strictly prohibited. Your right to use the work may be
terminated if you fail to comply with these terms.

THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND


ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO
THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS
TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY
INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA
HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY
WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR
A PARTICULAR PURPOSE. McGraw-Hill Education and its licensors do
not warrant or guarantee that the functions contained in the work
will meet your requirements or that its operation will be
uninterrupted or error free. Neither McGraw-Hill Education nor its
licensors shall be liable to you or anyone else for any inaccuracy,
error or omission, regardless of cause, in the work or for any
damages resulting therefrom. McGraw-Hill Education has no
responsibility for the content of any information accessed through
the work. Under no circumstances shall McGraw-Hill Education
and/or its licensors be liable for any indirect, incidental, special,
punitive, consequential or similar damages that result from the use
of or inability to use the work, even if any of them has been advised
of the possibility of such damages. This limitation of liability shall
apply to any claim or cause whatsoever whether such claim or cause
arises in contract, tort or otherwise.
In Memory of Shon Harris

Each time we write a new edition, all of my memories of Shon come


to the surface. As you know from previous editions, we lost Shon on
October 8, 2014. She was a great friend, pioneer in the field, and
beloved subject matter expert of cybersecurity. She brought me into
the first Gray Hat Hacking project. We were actually working toward
creating another book at the time, but it did not pan out, so the
Gray Hat Hacking book was born. I owe much of what I have
accomplished in the field to the great start she so generously gave
me, back in 2002 when I first met her at a CISSP bootcamp. I had
no clue who Shon was when I signed up for the bootcamp, but that
chance encounter changed my life. Her passion for the field and her
work ethic were contagious and inspired me to be the best I could
be, as I tried to live up to her high standard. I will always remember
her and how much I learned from her. Please join me and the other
authors as we continue to honor her memory and her desire to
improve the world through cybersecurity. We dedicate this book to
her memory.

—Allen Harper
Lead author and friend of Shon Harris

To my brothers and sisters in Christ, keep running the race. Let your
light shine for Him, that others may be drawn to Him through you.
—Allen Harper
To my wife, thank you for your constant encouragement and faith,
and for pushing me to push myself.
—Ryan Linn
To my lovely wife Leanne and my daughter Audrey, thank you for
your ongoing support!
—Stephen Sims
To my daughter Tiernan, thank you for your support and continuous
reminders to enjoy life and learning each and every day. I look
forward to seeing the wonderful woman you will become.
—Michael Baucom
To my beautiful wife Zoe and our children Alexander and Axel, thank
you for your continuous love and support, and for always trusting in
me and encouraging all my crazy new ideas.
—Huáscar Tejeda
To my beautiful wife Vanesa and my family for their support and
their patience every time I come up with a new project.
—Daniel Fernandez
To my wife Gina and my daughter Juliet, who I am so proud of.
Thank you for putting up with most of my harebrained ideas.
—Moses Frost
ABOUT THE AUTHORS
Dr. Allen Harper, CISSP, retired in 2007 from the military as a
Marine Corps Officer after a tour in Iraq. He has more than 30 years
of IT/security experience. He holds a PhD in IT with a focus on
information assurance and security from Capella, an MS in computer
science from the Naval Postgraduate School, and a BS in computer
engineering from North Carolina State University. In 2004, Allen led
the development of the GEN III Honeywall CD-ROM, called roo, for
the Honeynet Project. Since then, he has worked as a security
consultant for many Fortune 500 and government entities. His
interests include the Internet of Things, reverse engineering,
vulnerability discovery, and all forms of ethical hacking. Allen was the
founder of N2NetSecurity, Inc., served as the EVP and chief hacker
at Tangible Security, program director at Liberty University, and now
serves as EVP of cybersecurity at T-Rex Solutions, LLC, in Greenbelt,
Maryland.
Ryan Linn, CISSP, CSSLP, OSCP, OSCE, GREM, has over 20 years in
the security industry, ranging from systems programmer to corporate
security to leading a global cybersecurity consultancy. Ryan has
contributed to a number of open source projects, including
Metasploit, the Browser Exploitation Framework (BeEF), and
Ettercap. Ryan participates in Twitter as @sussurro, and he has
presented his research at numerous security conferences, including
Black Hat, DEF CON, Thotcon, and Derbycon, and has provided
training in attack techniques and forensics worldwide.
Stephen Sims is an industry expert with over 15 years of
experience in information technology and security. Stephen currently
works out of the San Francisco Bay Area as a consultant. He has
spent many years performing security architecture, exploit
development, reverse engineering, and penetration testing for
various Fortune 500 companies, and he has discovered and
responsibly disclosed a wide range of vulnerabilities in commercial
products. Stephen has an MS in information assurance from Norwich
University and currently leads the Offensive Operations curriculum at
the SANS Institute. He is the author of the SANS Institute’s only 700-
level course, SEC760: Advanced Exploit Development for Penetration
Testers, which concentrates on complex heap overflows, patch
diffing, and client-side exploits. He holds the GIAC Security Expert
(GSE) certification as well as the CISA, Immunity NOP, and many
others. In his spare time, Stephen enjoys snowboarding and writing
music.
Michael Baucom has over 25 years of industry experience, ranging
from embedded systems development to leading the product
security and research division at Tangible Security. With more than
15 years of security experience, he has performed security
assessments of countless systems across a multitude of areas,
including medical, industrial, networking, and consumer electronics.
Michael has been a trainer at Black Hat, speaker at several
conferences, and both an author and technical editor for Gray Hat
Hacking: The Ethical Hacker’s Handbook. His current interests are in
embedded system security and development.
Huáscar Tejeda is the co-founder and CEO of F2TC Cyber Security.
He is a seasoned, thoroughly experienced cybersecurity professional,
with more than 20 years and notable achievements in IT and
telecommunications, developing carrier-grade security solutions and
business-critical components for multiple broadband providers. He is
highly skilled in security research, penetration testing, Linux kernel
hacking, software development, and embedded hardware design.
Huáscar is also a member of the SANS Latin America Advisory
Group, SANS Purple Team Summit Advisory Board, and contributing
author of the SANS Institute’s most advanced course, SEC760:
Advanced Exploit Development for Penetration Testers.
Daniel Fernandez is a security researcher with over 15 years of
industry experience. Over his career, he has discovered and
exploited vulnerabilities in a vast number of targets. During the last
years, his focus had shifted to hypervisors, where he has found and
reported bugs in products such as Microsoft Hyper-V. He has worked
at several information security companies, including Blue Frost
Security GmbH and Immunity, Inc. Recently, he co-founded TACITO
Security. When not breaking software, Daniel enjoys training his
working dogs.
Moses Frost started his career in designing and implementing
large-scale networks around the year 2000. He has worked with
computers in some form or another since the early 1990s. His past
employers include TLO, Cisco Systems, and McAfee. At Cisco
Systems, he was a lead architect for its Cyber Defense Clinics. This
free information security dojo was used in educating individuals from
the high school and university levels as well as in many enterprises.
At Cisco, he was asked to work on crucial security projects such as
industry certifications. Moses is an author and senior instructor at
the SANS Institute. His technology interests include web app
penetration testing, cloud penetration testing, and red team
operations. He currently works as a red team operator at GRIMM.
Disclaimer: The views expressed in this book are those of
the authors and not of the U.S. government or any company
mentioned herein.

About the Contributor


Jaime Geiger currently works for GRIMM Cyber as a senior
software vulnerability research engineer and for SANS as a certified
instructor. He is also an avid snowboarder, climber, sailor, and
skateboarder.

About the Technical Editor


Heather Linn is a red teamer, penetration tester, threat hunter, and
cybersecurity strategist with more than 20 years of experience in the
security industry. During her career, she has consulted as a
penetration tester and digital forensics investigator and has operated
as a senior red team engineer inside Fortune 50 environments. In
addition to being an accomplished technical editor, Heather has
written and delivered training for multiple security conferences and
organizations, including Black Hat USA and Girls Who Code, and she
has published exam guides for the CompTIA Pentest+ certification.
She holds or has held various certifications, including OSCP, CISSP,
GREM, GCFA, GNFA, and CompTIA Pentest+.
CONTENTS AT A GLANCE
Part I Preparation
Chapter 1 Gray Hat Hacking
Chapter 2 Programming Survival Skills
Chapter 3 Linux Exploit Development Tools
Chapter 4 Introduction to Ghidra
Chapter 5 IDA Pro

Part II Ethical Hacking


Chapter 6 Red and Purple Teams
Chapter 7 Command and Control (C2)
Chapter 8 Building a Threat Hunting Lab
Chapter 9 Introduction to Threat Hunting

Part III Hacking Systems


Chapter 10 Basic Linux Exploits
Chapter 11 Advanced Linux Exploits
Chapter 12 Linux Kernel Exploits
Chapter 13 Basic Windows Exploitation
Chapter 14 Windows Kernel Exploitation
Chapter 15 PowerShell Exploitation
Chapter 16 Getting Shells Without Exploits
Chapter 17 Post-Exploitation in Modern Windows Environments
Chapter 18 Next-Generation Patch Exploitation

Part IV Hacking IoT


Chapter 19 Internet of Things to Be Hacked
Chapter 20 Dissecting Embedded Devices
Chapter 21 Exploiting Embedded Devices
Chapter 22 Software-Defined Radio

Part V Hacking Hypervisors


Chapter 23 Hypervisors 101
Chapter 24 Creating a Research Framework
Chapter 25 Inside Hyper-V
Chapter 26 Hacking Hypervisors Case Study

Part VI Hacking the Cloud


Chapter 27 Hacking in Amazon Web Services
Chapter 28 Hacking in Azure
Chapter 29 Hacking Containers
Chapter 30 Hacking on Kubernetes

Index
CONTENTS
Preface
Acknowledgments
Introduction

Part I Preparation

Chapter 1 Gray Hat Hacking

Gray Hat Hacking Overview


History of Hacking
Ethics and Hacking
Definition of Gray Hat Hacking
History of Ethical Hacking
History of Vulnerability Disclosure
Bug Bounty Programs
Know the Enemy: Black Hat Hacking
Advanced Persistent Threats
Lockheed Martin Cyber Kill Chain
Courses of Action for the Cyber Kill Chain
MITRE ATT&CK Framework
Summary
For Further Reading
References

Chapter 2 Programming Survival Skills

C Programming Language
Basic C Language Constructs
Lab 2-1: Format Strings
Lab 2-2: Loops
Lab 2-3: if/else
Sample Programs
Lab 2-4: hello.c
Lab 2-5: meet.c
Compiling with gcc
Lab 2-6: Compiling meet.c
Computer Memory
Random Access Memory
Endian
Segmentation of Memory
Programs in Memory
Buffers
Strings in Memory
Pointers
Putting the Pieces of Memory Together
Lab 2-7: memory.c
Intel Processors
Registers
Assembly Language Basics
Machine vs. Assembly vs. C
AT&T vs. NASM
Addressing Modes
Assembly File Structure
Lab 2-8: Simple Assembly Program
Debugging with gdb
gdb Basics
Lab 2-9: Debugging
Lab 2-10: Disassembly with gdb
Python Survival Skills
Getting Python
Lab 2-11: Launching Python
Lab 2-12: “Hello, World!” in Python
Python Objects
Lab 2-13: Strings
Lab 2-14: Numbers
Lab 2-15: Lists
Lab 2-16: Dictionaries
Lab 2-17: Files with Python
Lab 2-18: Sockets with Python
Summary
For Further Reading
References

Chapter 3 Linux Exploit Development Tools

Binary, Dynamic Information-Gathering Tools


Lab 3-1: Hello.c
Lab 3-2: ldd
Lab 3-3: objdump
Lab 3-4: strace
Lab 3-5: ltrace
Lab 3-6: checksec
Lab 3-7: libc-database
Lab 3-8: patchelf
Lab 3-9: one_gadget
Lab 3-10: Ropper
Extending gdb with Python
Pwntools CTF Framework and Exploit Development
Library
Summary of Features
Lab 3-11: leak-bof.c
HeapME (Heap Made Easy) Heap Analysis and
Collaboration Tool
Installing HeapME
Lab 3-12: heapme_demo.c
Summary
For Further Reading
References

Chapter 4 Introduction to Ghidra

Creating Our First Project


Installation and QuickStart
Setting the Project Workspace
Functionality Overview
Lab 4-1: Improving Readability with Annotations
Lab 4-2: Binary Diffing and Patch Analysis
Summary
For Further Reading
References

Chapter 5 IDA Pro

Introduction to IDA Pro for Reverse Engineering


What Is Disassembly?
Navigating IDA Pro
IDA Pro Features and Functionality
Cross-References (Xrefs)
Function Calls
Proximity Browser
Opcodes and Addressing
Shortcuts
Comments
Debugging with IDA Pro
Summary
For Further Reading
References

Part II Ethical Hacking


Chapter 6 Red and Purple Teams

Introduction to Red Teams


Vulnerability Scanning
Validated Vulnerability Scanning
Penetration Testing
Threat Simulation and Emulation
Purple Team
Making Money with Red Teaming
Corporate Red Teaming
Consultant Red Teaming
Purple Team Basics
Purple Team Skills
Purple Team Activities
Summary
For Further Reading
References

Chapter 7 Command and Control (C2)

Command and Control Systems


Metasploit
Lab 7-1: Creating a Shell with Metasploit
PowerShell Empire
Covenant
Lab 7-2: Using Covenant C2
Payload Obfuscation
msfvenom and Obfuscation
Lab 7-3: Obfuscating Payloads with msfvenom
Creating C# Launchers
Lab 7-4: Compiling and Testing C# Launchers
Creating Go Launchers
Lab 7-5: Compiling and Testing Go Launchers
Creating Nim Launchers
Lab 7-6: Compiling and Testing Nim Launchers
Network Evasion
Encryption
Alternate Protocols
C2 Templates
EDR Evasion
Killing EDR Products
Bypassing Hooks
Summary
For Further Reading

Chapter 8 Building a Threat Hunting Lab

Threat Hunting and Labs


Options of Threat Hunting Labs
Method for the Rest of this Chapter
Basic Threat Hunting Lab: DetectionLab
Prerequisites
Lab 8-1: Install the Lab on Your Host
Lab 8-2: Install the Lab in the Cloud
Lab 8-3: Looking Around the Lab
Extending Your Lab
HELK
Lab 8-4: Install HELK
Lab 8-5: Install Winlogbeat
Lab 8-6: Kibana Basics
Lab 8-7: Mordor
Summary
For Further Reading
References

Chapter 9 Introduction to Threat Hunting

Threat Hunting Basics


Types of Threat Hunting
Workflow of a Threat Hunt
Normalizing Data Sources with OSSEM
Data Sources
OSSEM to the Rescue
Data-Driven Hunts Using OSSEM
MITRE ATT&CK Framework Refresher: T1003.002
Lab 9-1: Visualizing Data Sources with OSSEM
Lab 9-2: AtomicRedTeam Attacker Emulation
Exploring Hypothesis-Driven Hunts
Lab 9-3: Hypothesis that Someone Copied a
SAM File
Crawl, Walk, Run
Enter Mordor
Lab 9-4: Hypothesis that Someone Other than
an Admin Launched PowerShell
Threat Hunter Playbook
Departure from HELK for Now
Spark and Jupyter
Lab 9-5: Automated Playbooks and Sharing of
Analytics
Summary
For Further Reading
References

Part III Hacking Systems

Chapter 10 Basic Linux Exploits

Stack Operations and Function-Calling Procedures


Buffer Overflows
Lab 10-1: Overflowing meet.c
Ramifications of Buffer Overflows
Local Buffer Overflow Exploits
Lab 10-2: Components of the Exploit
Lab 10-3: Exploiting Stack Overflows from the
Command Line
Lab 10-4: Writing the Exploit with Pwntools
Lab 10-5: Exploiting Small Buffers
Exploit Development Process
Lab 10-6: Building Custom Exploits
Summary
For Further Reading

Chapter 11 Advanced Linux Exploits

Lab 11-1: Vulnerable Program and Environment


Setup
Lab 11-2: Bypassing Non-Executable Stack (NX)
with Return-Oriented Programming (ROP)
Lab 11-3: Defeating Stack Canaries
Lab 11-4: ASLR Bypass with an Information
Leak
Lab 11-5: PIE Bypass with an Information Leak
Summary
For Further Reading
References

Chapter 12 Linux Kernel Exploits

Lab 12-1: Environment Setup and Vulnerable


procfs Module
Lab 12-2: ret2usr
Lab 12-3: Defeating Stack Canaries
Lab 12-4: Bypassing Supervisor Mode Execution
Protection (SMEP) and Kernel Page-Table
Isolation (KPTI)
Lab 12-5: Bypassing Supervisor Mode Access
Prevention (SMAP)
Lab 12-6: Defeating Kernel Address Space
Layout Randomization (KASLR)
Summary
For Further Reading
References

Chapter 13 Basic Windows Exploitation

Compiling and Debugging Windows Programs


Lab 13-1: Compiling on Windows
Debugging on Windows with Immunity Debugger
Lab 13-2: Crashing the Program
Writing Windows Exploits
Exploit Development Process Review
Lab 13-3: Exploiting ProSSHD Server
Understanding Structured Exception Handling
Understanding and Bypassing Common Windows
Memory Protections
Safe Structured Exception Handling
Bypassing SafeSEH
Data Execution Prevention
Return-Oriented Programming
Gadgets
Building the ROP Chain
Summary
For Further Reading
References

Chapter 14 Windows Kernel Exploitation

The Windows Kernel


Kernel Drivers
Kernel Debugging
Lab 14-1: Setting Up Kernel Debugging
Picking a Target
Lab 14-2: Obtaining the Target Driver
Lab 14-3: Reverse Engineering the Driver
Lab 14-4: Interacting with the Driver
Token Stealing
Lab 14-5: Arbitrary Pointer Read/Write
Lab 14-6: Writing a Kernel Exploit
Summary
For Further Reading
References

Chapter 15 PowerShell Exploitation

Why PowerShell
Living off the Land
PowerShell Logging
PowerShell Portability
Loading PowerShell Scripts
Lab 15-1: The Failure Condition
Lab 15-2: Passing Commands on the Command
Line
Lab 15-3: Encoded Commands
Lab 15-4: Bootstrapping via the Web
Exploitation and Post-Exploitation with PowerSploit
Lab 15-5: Setting Up PowerSploit
Lab 15-6: Running Mimikatz Through
PowerShell
Using PowerShell Empire for C2
Lab 15-7: Setting Up Empire
Lab 15-8: Staging an Empire C2
Lab 15-9: Using Empire to Own the System
Lab 15-10: Using WinRM to Launch Empire
Summary
For Further Reading
Reference

Chapter 16 Getting Shells Without Exploits

Capturing Password Hashes


Understanding LLMNR and NBNS
Understanding Windows NTLMv1 and NTLMv2
Authentication
Using Responder
Lab 16-1: Getting Passwords with Responder
Using Winexe
Lab 16-2: Using Winexe to Access Remote
Systems
Lab 16-3: Using Winexe to Gain Elevated
Privileges
Using WMI
Lab 16-4: Querying System Information with
WMI
Lab 16-5: Executing Commands with WMI
Taking Advantage of WinRM
Lab 16-6: Executing Commands with WinRM
Lab 16-7: Using Evil-WinRM to Execute Code
Summary
For Further Reading
Reference

Chapter 17 Post-Exploitation in Modern Windows Environments

Post-Exploitation
Host Recon
Lab 17-1: Using whoami to Identify Privileges
Lab 17-2: Using Seatbelt to Find User
Information
Lab 17-3: System Recon with PowerShell
Lab 17-4: System Recon with Seatbelt
Lab 17-5: Getting Domain Information with
PowerShell
Lab 17-6: Using PowerView for AD Recon
Lab 17-7: Gathering AD Data with SharpHound
Escalation
Lab 17-8: Profiling Systems with winPEAS
Lab 17-9: Using SharpUp to Escalate Privileges
Lab 17-10: Searching for Passwords in User
Objects
Lab 17-11: Abusing Kerberos to Gather
Credentials
Lab 17-12: Abusing Kerberos to Escalate
Privileges
Active Directory Persistence
Lab 17-13: Abusing AdminSDHolder
Lab 17-14: Abusing SIDHistory
Summary
For Further Reading

Chapter 18 Next-Generation Patch Exploitation

Introduction to Binary Diffing


Application Diffing
Patch Diffing
Binary Diffing Tools
BinDiff
turbodiff
Lab 18-1: Our First Diff
Patch Management Process
Microsoft Patch Tuesday
Obtaining and Extracting Microsoft Patches
Summary
For Further Reading
References

Part IV Hacking IoT

Chapter 19 Internet of Things to Be Hacked

Internet of Things (IoT)


Types of Connected Things
Wireless Protocols
Communication Protocols
Security Concerns
Shodan IoT Search Engine
Web Interface
Shodan Command-Line Interface
Lab 19-1: Using the Shodan Command Line
Shodan API
Lab 19-2: Testing the Shodan API
Lab 19-3: Playing with MQTT
Implications of this Unauthenticated Access to
MQTT
IoT Worms: It Was a Matter of Time
Prevention
Summary
For Further Reading
References

Chapter 20 Dissecting Embedded Devices

CPU
Microprocessor
Microcontrollers
System on Chip
Common Processor Architectures
Serial Interfaces
UART
SPI
I 2C
Debug Interfaces
JTAG
SWD
Software
Bootloader
No Operating System
Real-Time Operating System
General Operating System
Summary
For Further Reading
References

Chapter 21 Exploiting Embedded Devices

Static Analysis of Vulnerabilities in Embedded Devices


Lab 21-1: Analyzing the Update Package
Lab 21-2: Performing Vulnerability Analysis
Dynamic Analysis with Hardware
The Test Environment Setup
Ettercap
Dynamic Analysis with Emulation
FirmAE
Lab 21-3: Setting Up FirmAE
Lab 21-4: Emulating Firmware
Lab 21-5: Exploiting Firmware
Summary
For Further Reading
References

Chapter 22 Software-Defined Radio


Getting Started with SDR
What to Buy
Not So Quick: Know the Rules
Learn by Example
Search
Capture
Replay
Analyze
Preview
Execute
Summary
For Further Reading

Part V Hacking Hypervisors

Chapter 23 Hypervisors 101

What Is a Hypervisor?
Popek and Goldberg Virtualization Theorems
Goldberg’s Hardware Virtualizer
Type-1 and Type-2 VMMs
x86 Virtualization
Dynamic Binary Translation
Ring Compression
Shadow Paging
Paravirtualization
Hardware Assisted Virtualization
VMX
EPT
Summary
References

Chapter 24 Creating a Research Framework


Hypervisor Attack Surface
The Unikernel
Lab 24-1: Booting and Communication
Lab 24-2: Communication Protocol
Boot Message Implementation
Handling Requests
The Client (Python)
Communication Protocol (Python)
Lab 24-3: Running the Guest (Python)
Lab 24-4: Code Injection (Python)
Fuzzing
The Fuzzer Base Class
Lab 24-5: IO-Ports Fuzzer
Lab 24-6: MSR Fuzzer
Lab 24-7: Exception Handling
Fuzzing Tips and Improvements
Summary
References

Chapter 25 Inside Hyper-V

Environment Setup
Hyper-V Architecture
Hyper-V Components
Virtual Trust Levels
Generation-1 VMs
Lab 25-1: Scanning PCI Devices in a
Generation-1 VM
Generation 2 VMs
Lab 25-2: Scanning PCI Devices in a
Generation-2 VM
Hyper-V Synthetic Interface
Synthetic MSRs
Lab 25-3: Setting Up the Hypercall Page and
Dumping Its Contents
Hypercalls
VMBus
Lab 25-4: Listing VMBus Devices
Summary
For Further Reading
References

Chapter 26 Hacking Hypervisors Case Study

Bug Analysis
USB Basics
Lab 26-1: Patch Analysis Using GitHub API
Developing a Trigger
Setting Up the Target
Lab 26-2: Scanning the PCI Bus
The EHCI Controller
Triggering the Bug
Lab 26-3: Running the Trigger
Exploitation
Relative Write Primitive
Relative Read Primitive
Lab 26-4: Debugging the Relative Read Primitive
Arbitrary Read
Full Address-Space Leak Primitive
Module Base Leak
RET2LIB
Lab 26-5: Finding Function Pointers with GDB
Lab 26-6: Displaying IRQState with GDB
Lab 26-7: Launching the Exploit
Summary
For Further Reading
References
Part VI Hacking the Cloud

Chapter 27 Hacking in Amazon Web Services

Amazon Web Services


Services, Locations, and Infrastructure
How Authorization Works in AWS
Abusing AWS Best Practices
Lab 27-1: Environment Setup
Abusing Authentication Controls
Types of Keys and Key Material
Lab 27-2: Finding AWS Keys
Attacker Tools
Lab 27-3: Enumerating Permissions
Lab 27-4: Leveraging Access to Perform
Unauthorized Actions
Lab 27-5: Persistence Through System Internals
Summary
For Further Reading
References

Chapter 28 Hacking in Azure

Microsoft Azure
Differences Between Azure and AWS
Lab 28-1: Setup of Our Labs
Lab 28-2: Additional User Steps
Lab 28-3: Validating Access
Microsoft Azure AD Overview
Azure Permissions
Constructing an Attack on Azure-Hosted Systems
Lab 28-4: Azure AD User Lookups
Lab 28-5: Azure AD Password Spraying
Lab 28-6: Getting onto Azure
Control Plane and Managed Identities
Lab 28-7: System Assigned Identities
Lab 28-8: Getting a Backdoor on a Node
Summary
For Further Reading
References

Chapter 29 Hacking Containers

Linux Containers
Container Internals
Cgroups
Lab 29-1: Setup of our Environment
Lab 29-2: Looking at Cgroups
Namespaces
Storage
Lab 29-3: Container Storage
Applications
What Is Docker?
Lab 29-4: Looking for Docker Daemons
Container Security
Lab 29-5: Interacting with the Docker API
Lab 29-6: Executing Commands Remotely
Lab 29-7: Pivots
Breaking Out of Containers
Capabilities
Lab 29-8: Privileged Pods
Lab 29-9: Abusing Cgroups
Summary
For Further Reading
References

Chapter 30 Hacking on Kubernetes


Kubernetes Architecture
Fingerprinting Kubernetes API Servers
Lab 30-1: Cluster Setup
Finding Kubernetes API Servers
Lab 30-2: Fingerprinting Kubernetes Servers
Hacking Kubernetes from Within
Lab 30-3: Kubestriker
Lab 30-4: Attacking from Within
Lab 30-5: Attacking the API Server
Summary
For Further Reading
References

Index
PREFACE
This book has been developed by and for security professionals who
are dedicated to working in an ethical and responsible manner to
improve the overall security posture of individuals, corporations, and
nations.
ACKNOWLEDGMENTS
Each of the authors would like to thank the staff at McGraw Hill.
In particular, we would like to thank Wendy Rinaldi and Emily
Walters. We could not have done this book without you. Your
expertise, tireless dedication, and attention to detail helped make
this book a success. Thanks for keeping us on track and for your
patience with us as we progressed.
We would also like to thank Heather Linn, our technical editor. She
went above and beyond as a technical editor and improved the book
in many ways. She tirelessly ran all the code in the book and often
had to work with the authors to fix that code. Throughout the
process, she kept a sense of humor and encouraged us to do our
best. As an accomplished author in her own right, she completed our
team.
Allen Harper would like to thank his wonderful wife Corann and
beautiful daughters Haley and Madison for their support and
understanding as he chased yet another dream. With each edition, it
is neat to see our family grow and now spread apart, as we live in
different states. Haley and Madison, you are the joy of my life. I am
so proud of you both and am so excited for your future. Corann, I
love you more than ever, and look forward to spending the rest of
our lives together! To my colleagues at T-Rex, thanks for bringing
the best out of me and challenging me to achieve even more.
Ryan Linn would like to thank Heather for her support,
encouragement, and advice as well as his family and friends for their
support and for putting up with the long hours and infrequent
communication while the book was coming together.
Thanks to Jeff, Brian, Luke, Derek, Adrian, Shawn, Rob, Jon,
Andrew, Tom, Todd, Kelly, Debbie, and all the others who continue
to push him to grow technically, professionally, and in all aspects of
life.
Stephen Sims would like to thank his wife Leanne and daughter
Audrey for their ongoing support with the time needed to research,
write, work, teach, and travel.
He would also like to thank his parents George and Mary and his
sister Lisa for their support from afar. Finally, a special thanks to all
of the brilliant security researchers who contribute so much to the
community with publications, lectures, and tools.
Finally, a special thank you to Jaime Geiger for writing the chapter
on Windows Kernel exploitation!
Michael Baucom would like to thank his wife Bridget and his
daughter Tiernan for their sacrifices and support in allowing him to
pursue his professional goals.
He’d also like to thank his parents for their love and support and for
instilling in him the work ethic that has carried him to this point.
Additionally, he’d like to thank the Marine Corps for giving him the
courage and confidence to understand that all things are possible.
Finally, he’d like to thank his brother in Christ, long-time friend, and
colleague Allen Harper. Nothing can be accomplished without a great
team.
Huáscar Tejeda would like to thank his wife Zoe and their children
Alexander and Axel for their continuous support and encouragement.
He would also like to thank his mother Raysa for having taught him
by example the importance of being passionate about inexhaustible
study and hard work, as well as for exposing him to music, painting,
and mathematics at an early age. Additionally, he’d like to thank his
grandmother Milagros for her great love and for always believing in
him since he was a child. Also, a special thanks to his older brother
Geovanny for inviting him to the university to take computer science
classes after learning of Huáscar’s strong computer programming
skills at the age of 13. And, finally, thanks go to his brother Aneudy
for always caring and being there for him.
Daniel Fernandez would like to thank his wife Vanesa for her love
and support.
He’d also like to thank former colleagues and longtime friends
Sebastian Fernandez, Gottfrid Svartholm, and Bruno Deferrari. He
considers himself lucky to have met them and learn from them all
these years. Finally, a special thanks to Rocky, a good friend who
many years ago gave him the opportunity that resulted in his best
professional experience.
Moses Frost would like to thank his wife Gina and daughter Juliet
for their continued love, support, and sacrifices throughout the
years.
He’d also like to thank his parents who allowed him to pursue his
passions. It was not easy to break free and take chances. Finally, but
not least, he’d like to thank some former colleagues, mentors, and
friends—Fernando Martinez, Joey Muniz, Ed Skoudis, Jonathan Cran,
and so many others who have helped him be a better person.
We, the authors, would also like to collectively thank Hex-Rays for
the generous use of their tool IDA Pro.
Finally, a special thank you to Jaime Geiger for writing the chapter
on Windows Kernel exploitation!
INTRODUCTION
There is no instance of a nation benefitting from prolonged warfare.
—Sun Tzu
To be prepared for war is one of the most effective means of
preserving peace.
—George Washington
If it were a fact, it wouldn’t be called intelligence.
—Donald Rumsfeld
Like the previous editions, the purpose of this book is to provide
individuals the information once held only by governments and a few
black hat hackers. In each edition, we strive to update the reader on
the latest security techniques. Increasingly, individuals stand in the
breach of cyberwar, not only against black hat hackers, but
sometimes against governments. If you find yourself in this position,
either alone or as a defender of your organization, we want you to
be equipped with as much knowledge of the attacker as possible. To
that end, we present to you the mindset of the gray hat hacker, an
ethical hacker who uses offensive techniques for defensive purposes.
Ethical hacker is an honorable role—one that respects the laws and
the rights of others. The ethical hacker subscribes to the notion that
the adversary may be beaten to the punch by testing oneself first.
The authors of this book want to provide you, the reader, with
something we believe the industry and society in general need: a
holistic review of ethical hacking that is responsible and truly ethical
in its intentions and material. This is why we keep releasing new
editions of this book with a clear definition of what ethical hacking is
and is not—something our society is very confused about.
We have updated the material from the fifth edition and have
attempted to deliver the most comprehensive and up-to-date
assembly of techniques, procedures, and material with real hands-on
labs that can be replicated by the reader.
Eighteen new chapters are presented, and the other chapters have
been updated.
In the first section, we cover the topics required to prepare you for
the rest of the book. Keep in mind that all the skills you need are
more than can be covered in any book, but we attempt to lay out
some topics to make the rest of the book more attainable and
accessible by newer members of the field. We cover the following
topics:

• The role of a gray hat hacker


• The MITRE ATT&CK framework
• Programming basic skills in C, Assembly, and Python
• Linux exploit tools
• Ghidra reverse engineering tool
• IDA Pro reverse engineering tool

In the second section, we explore the topic of ethical hacking. We


give you an overview of the skills being employed by professionals
as they attack and defend networks. We cover the following topics:

• Red and purple teaming


• Command and control (C2) techniques
• Building a threat hunting lab on your host and in the cloud
• Threat hunting basics

In the third section, we shift gears and talk about hacking systems.
Here, you will discover the skills needed to exploit Windows and
Linux systems. This is a broad area of focus, where we cover these
topics:

• Basic Linux exploits


• Advanced Linux exploits
• Linux kernel exploits
• Basic Windows exploits
• Windows kernel exploits
• PowerShell exploits
• Getting shells without exploits
• Post-exploitation in modern Windows environments
• Next-generation patch exploitation

In the fourth section, we cover hacking of the Internet of Things


(IoT) and hardware devices. We start with an overview of this area
of cybersecurity and then launch into more advanced topics,
including the following:

• Overview of the Internet of Things


• Dissecting embedded devices
• Exploiting embedded devices
• Hacking software-defined radios (SDRs)

In the fifth section, we cover hacking hypervisors, which provide the


software-defined networks, storage, and processing of virtual
machines that undergird the majority of business systems these
days. In this section, we explore the following topics:

• Overview of hypervisors
• Creating a research framework for testing hypervisors
• Looking inside Hyper-V
• Hacking hypervisors case study

In the sixth section, we cover hacking the cloud. Moving beyond


standard hypervisors, which often run in private data centers, we
describe the public cloud, the technologies involved, and the security
implications of such. We cover these topics:

• Hacking in Amazon Web Services


• Hacking in Azure
• Hacking containers
• Hacking on Kubernetes

We hope you enjoy the new and updated chapters. If you are new
to the field or are ready to take the next step to advance and
deepen your understanding of ethical hacking, this is the book for
you. In any event, use your powers for good!

NOTE To ensure your system is properly configured to perform the


labs, we have provided the files you will need. The lab materials and
errata may be downloaded from the GitHub repository at
https://github.com/GrayHatHacking/GHHv6.
PART I

Preparation
Chapter 1 Gray Hat Hacking
Chapter 2 Programming Survival Skills
Chapter 3 Linux Exploit Development Tools
Chapter 4 Introduction to Ghidra
Chapter 5 IDA Pro
CHAPTER 1

Gray Hat Hacking


In this chapter, we cover the following topics:
• Gray hat hacking
• Vulnerability disclosure
• Advanced persistent threats (APTs)
• Cyber Kill Chain
• MITRE ATT&CK framework

What is a gray hat hacker? Why should you care? In this chapter, we
attempt to define what a gray hat hacker is and why they are so
vital to the cybersecurity field. In short, they stand in the gap
between white hat hackers and black hat hackers and serve as
ethical hackers, never breaking the law, but instead making the
world a better place through applying their skills for good. Now, this
concept is controversial, and good people may disagree on this
topic. So, in this chapter, we try to set the record straight and give a
call to action—that you join us as gray hat hackers and practice
ethical hacking in a responsible manner. We also lay the foundation
of other critical topics discussed throughout the book.

Gray Hat Hacking Overview


The phrase “gray hat hacker” has been quite controversial. To some,
it means a hacker who occasionally breaks the law or does
something unethical to reach a desired end. We, as gray hat
hackers, reject that notion. In a moment we will give our definition.
We have read more than one book that has further confused the
Another random document with
no related content on Scribd:
It was at the outset of this campaign that Jomini handed in to
Marshal Ney, his chief, a paper showing what Napoleon must
necessarily do if he would beat the Prussians and cut them off from
their approaching allies. He alone had divined the strategic secrets
of the Emperor.
In this campaign we plainly see the growth of risk commensurate
within the magnitude of plan, but we also recognize the greater
perfection of general intuitions, the larger plan and method. Details
had to be overlooked, but the whole army was held in the Emperor’s
hand like a battalion in that of a good field officer. In forty-eight hours
his two hundred thousand men could be concentrated at any one
point. And the very essence of the art of war is to know when you
may divide, to impose on the enemy, subsist, pursue, deceive, and
to know how to divide so that you may concentrate before battle can
occur.
JENA CAMPAIGN
Again Napoleon had carried out his principle of moving on one
line in one mass on the enemy, and a few great soldiers began to
see that there was a theory in this. Jomini first grasped its full
meaning and showed that only battle crowns the work. Without it a
general is merely uncovering his own communications. Victory is
essential to the success of such a plan. Napoleon pushed restlessly
in on the enemy. “While others are in council, the French army is on
the march,” quoth he.
In the Austerlitz and Jena campaigns, Napoleon’s manœuvre
was so admirably conceived that he kept open two lines of retreat,
which he could adapt to the enemy’s evolutions,—at Austerlitz via
Vienna and Bohemia, at Jena still more secure lines on the Rhine
and on the Main or Danube. This is a distinct mark of the perfection
of the plans.
The succeeding Friedland campaign has several items of
interest. At his first contact with the Russians, Napoleon, instead of
sticking to his uniform plan of one mass on one line, tried to surround
his enemy before he knew where the tactical decision of the
campaign would come. Result, a thrust in the air by one corps,
another did not reach the appointed place, a third met unexpected
and superior forces, and the enemy broke through the net. Napoleon
seemed to be experimenting. The captain of 1796, Ulm, Jena, is for
the moment unrecognizable.
The Russians attacked Napoleon in his winter-quarters, and the
bloody and indecisive battle of Eylau resulted, where for the first time
Napoleon met that astonishing doggedness of the Russian soldier,
on which Frederick had shattered his battalions at Kunersdorf. Later
came the victory of Friedland. Napoleon’s order for this day is a
model for study. Every important instruction for the battle is
embraced in the order; details are left to his lieutenants. Only the
time of launching the first attack is reserved to the chief. But the
strategy of the Friedland campaign was not so crisp. The true
manœuvre was to turn the Russian left, their strategic flank, and
throw them back on the sea. Napoleon turned their right to cut them
off from Königsberg. It was mere good luck that Friedland ended the
campaign. Even after defeat the enemy could have escaped.
In the Spanish campaign of the winter of 1807–8, Napoleon
reverted to his 1796 manœuvre of breaking the enemy’s centre. But
Napoleon had undertaken what could not be accomplished,—the
subjugation of Spain. His own strategy and the tactics of his
marshals were both brilliant and successful; he could have
compelled a peace, had such been the object. But to subdue a
people fanatically fighting for their homes, in a mountainous country,
is practically impossible by any means short of extermination. It was
in the political, not the military, task that Napoleon failed.
While Napoleon was struggling in Spain, Austria deemed the
occasion good again to assert herself. This gave Napoleon an
opportunity of leaving to his lieutenants a game he already saw he
could not win, but in which he had achieved some brilliant openings,
and hurry to fields on which he felt a positive superiority. His army
and allies were already on the scene.
Berthier was in charge, and to him Napoleon had given full and
explicit instructions. But Berthier, though a good chief of staff, had no
power to grasp a strategic situation. By not obeying orders, he had,
by the time Napoleon arrived, muddled the problem, and instead of
concentrating behind the Lech, had got Davout’s corps pushed out to
Ratisbon, where it was liable to be cut off. Napoleon was in perilous
case. But by a beautiful and rapid series of manœuvres, in which he
cut the enemy in two, he wrought victory out of threatening defeat.
He was justly proud of this. “The greatest military manœuvres that I
have ever made, and on which I most flatter myself, took place at
Eckmühl, and were immensely superior to those of Marengo or other
actions which preceded or followed them.” It is the rapidity and
suddenness of these manœuvres which distinguished them from
1805. There was a regular plan. Here a constant series of surprises
and changes.
In making his plans, Napoleon never began by “What can the
enemy do?” but he first sought to place his army in the best position,
and then asked, “What now can the enemy do?” This gave him the
initiative. But his plan was always elastic enough to bend to what the
enemy might do. He never made plans colored by the enemy’s
possibilities. He chose his own plan intelligently, according to the
geography, topography, and existing conditions, and made it elastic
enough to be equal to the enemy’s. “The mind of a general should
be like the glass of a telescope in sharpness and clearness, and
never conjure up pictures.” The elasticity of Napoleon’s Eckmühl
plan is well shown by his ability to turn threatening disaster into
brilliant success.
During all these days, Napoleon was tremendously active. He
was personally at the important points. He hardly ate or slept. His
body was governed entirely by his will. The soldier of 1796 was
again afoot. But he was well and hearty. The lapse he now made is
all the more singular. The Archduke Charles had been beaten at
Eckmühl and was retiring into Ratisbon to cross the Danube;
Napoleon neglected to pursue. They say he was persuaded by his
marshals that the troops were too tired. For the first time in his life he
succumbed to an obstacle. “Genius consists in carrying out a plan
despite obstacles, and in finding few or no obstacles,” he once said.
Failure to pursue may come from the difficulty of leaving one’s
magazines, as in Frederick’s era, or because the captain is
exhausted, as well as the troops. But if the captain wants to pursue,
the troops can always do so. If the enemy can fly, the victor can
follow. Some part of the army is always in condition to march.
Jomini says that if Napoleon had here pursued like the Prussians
after Waterloo, it would have greatly modified the campaign. As it
was, the Archduke made good his escape. Napoleon had broken in
between the two wings of the Austrian army, but he had not crippled
the one before turning against the other. So that when he reached
Vienna on the heels of the left, he found ready to meet him the right
wing, which he ought to have crushed beyond so quick recovery at
Ratisbon. This failure to pursue is the first symptom of a habit which
from now on is more observably of not utilizing every advantage.
Then followed the crossing of the Danube at Lobau and the
battles around Aspern and Essling, which terminated with defeat and
great loss. The Archduke was on hand, received in overwhelming
numbers that part of the French army which crossed; the bridges
were broken behind the French; and a disastrous retreat to Lobau
followed.
Napoleon’s difficulties were growing apace with the size of his
armies, and he was now opposed by abler men. But it also seems as
if occasional fits of apathy or impatience of exertion were growing on
him. His splendid energy at Eckmühl did not continue. Details
received less personal attention. He was more rarely at the front. He
began to rely on the eyes of others more than, with his ancient vigor,
he would have done—despite his dictum that “a general who sees
through the eyes of others will never be in condition to command an
army as it should be commanded.” Until battle actually opened, he
lacked his old enthusiasm. After the first gun he was himself again.
But his method of conducting war was no longer so crisp as of yore.
He was more daring than careful; he relied on his luck, and strove to
cover errors of omission by stupendous blows. He was suffering
from not having about him a well-educated, properly selected staff,
each member drilled in his specific duties. Till now Napoleon had
been his own staff; but with lessening activity, he had no one on
whose eyes and judgment he could rely. “The general staff is so
organized that one cannot see ahead at all by its means,” said he in
the next campaign. Still it must constantly be borne in mind that one
hundred and fifty thousand men cannot be commanded as readily as
forty thousand. And Napoleon’s breadth of view, his power of
grasping the tout ensemble, were still present in greater measure;
and when he chose he could summon up all his old spirit.
Succeeding this defeat were the skilful preparations for a new
crossing and battle, the putting over from Lobau of one hundred and
fifty thousand men and four hundred guns in one night, and the
victory of Wagram. Truly a marvellous performance! The strength of
mind and constancy displayed by Napoleon on Lobau recalls the
elastic courage of Alexander when, cut off from his communications,
he turned upon the Persians at Issus. But after Wagram the
Austrians retired in good order and Napoleon did not pursue. It was
no doubt a difficult task, but with the inspiration of his earlier days he
would certainly have pushed the Archduke home,—or lost the game.
He forgot the principles which had made him what he was, in not
following up the retreat. To other and even great generals this
criticism could not apply, but Napoleon has created a measure by
which himself must be tried and which fits but a limited group. In
1805 he said, “One has but a certain time for war. I shall be good for
it but six years more; then even I shall have to stop.” Was
Napoleon’s best term drawing to a close? Or was it that the
Archduke Charles was not a Würmser or a Mack?
In Napoleon’s battles, tactical details are made to yield to
strategic needs. Frederick generally chose his point of attack from a
strictly tactical standpoint. Napoleon did not appear to consider that
there were such things as tactical difficulties. He always moved on
the enemy as seemed to him strategically desirable, and with his
great masses he could readily do so. The result of Napoleon’s
battles was so wonderful, just because he always struck from such a
strategic direction as to leave a beaten enemy no kind of loophole.
But Napoleon would have been more than human if his extraordinary
successes had not finally damaged his character. It is but the story of
Alexander with a variation. In the beginning he was, after securing
strategic value, strenuous to preserve his tactical values. By and by
he began to pay less heed to these; stupendous successes bred
disbelief in failure; carelessness resulted, then indecision. Those
historians who maintain that Napoleon succumbed solely to the
gigantic opposition his status in Europe had evoked, can show good
reasons for their belief, for Napoleon’s task was indeed immense.
But was he overtaxed more than Hannibal, Cæsar, or Frederick?
In the Russian campaign (1812) Napoleon’s original idea was to
turn the Russian right, but finding the Russian position further north
than he expected, he resorted to breaking the Russian centre. It here
first became a question whether the rule of one mass on one line,
distinctly sound with smaller armies, will hold good with the
enormous armies of 1812 or of modern days; whether the mere
manœuvre may not become so difficult of execution as to open the
way to the destruction of the entire plan by a single accident.
Certainly its logistics grow to a serious problem with a force beyond
two hundred thousand men, and it seems probable that when armies
much exceed this figure, the question of feeding, transportation, and
command, even with railroads and telegraph, make concentric
operations more available. And the fact that even Napoleon could
not, in the absence of a thoroughly educated staff and perfectly
drilled army, obtain good results from the handling of such enormous
forces, gives prominence to the value of the Prussian idea of placing
greater reliance on an army drawn from the personal service of the
people and made perfect in all its details from the ranks up, than on
the genius of a single general.
The entire plan of the Russian campaign was consistent and
good. The Bonaparte of 1796 would probably have carried it through,
despite its unprecedented difficulties. But its execution was seriously
marred by the absence of Napoleon at the front, and the want of his
ancient decisiveness. To be sure he had nearly half a million men to
command and feed; but he was no longer the slim, nervously active,
omnipresent man. He was corpulent, liked his ease, and shunned
bad weather. This want appears in his long stay in Wilna, his failure
to put his own individuality into the details of the advance; his now
relying on his lieutenants, whom he had never trained, and some of
whom were unable, to rely on themselves. Napoleon began to draw
his conclusions, not from personal observation, but from assumed
premises. He had from the beginning the habit of underrating the
enemy’s forces. It now grew to be a rule with him to take one-third off
from what the enemy really had and double his own forces, in order
to encourage his subordinates. This exaggerated reckoning could
not but lead to evil. There is none of Frederick’s straightforward
dependence on his own brain and his army’s courage. The king’s
frankness stands out in high relief against Napoleon’s simulation.
But we must constantly bear in mind that Napoleon led an army
of unprecedented size, made up of different nationalities, in a
limitless territory, and that his difficulties were enormous. It should be
noted that Alexander’s largest army in the field numbered one
hundred and thirty-five thousand men; Hannibal’s less than sixty
thousand; Cæsar’s about eighty thousand; Gustavus’ never reached
eighty thousand men; Frederick had to parcel out his forces so that
of his one hundred and fifty thousand men he rarely could personally
dispose of more than fifty thousand in one body. Napoleon carried
three hundred and sixty thousand men into Russia. This is not a final
measure of the task, but it stakes out its size.
Some of Napoleon’s Russian manœuvres are fully up to the old
ones. The manner of the attempt to turn the Russian left at
Smolensk and seize their communications so as to fight them at a
disadvantage, is a magnificent exhibition of genius. But at the last
moment he failed. The spirit of his plan was to seize the
communications of his opponent and force him to fight; the letter was
to seize Smolensk. When he reached Smolensk, the Russians had
retired to the east of the city. Napoleon apparently overlooked the
spirit of his plan, and though he could easily have done so, he did
not cut the Russians off by a tactical turning movement. He was not
personally where he needed to be,—on the right,—but remained at
his headquarters. It may be claimed that the commander of so huge
an army must necessarily remain at central headquarters. It is rather
true that his administrative aide should be there, and he at the point
of greatest importance. At Smolensk, theoretically and practically,
this was the right, and operations at this point were intrusted to by no
means the best of his subordinates. Napoleon’s intellect was still as
clear as ever. It was his physique and his power of decision which
were weakening. Even allowing the utmost to all the difficulties of the
situation, if tried by the rule of 1796 or 1805, this seems to be
indisputable.
When Napoleon did not bring on a battle at Smolensk, the
Russian campaign had become a certain failure. For it was there
settled that he could not reach Moscow with a force sufficient to hold
himself. He had crossed the Niemen with three hundred and sixty-
three thousand men. At Moscow he could have no more than one
hundred thousand. Arrived at Smolensk he was called on to face
retreat, which was failure; or an advance to Moscow, which was but
worse failure deferred,—almost sure annihilation. This seems clear
enough from the military standpoint. But Napoleon advanced to
Moscow relying largely on the hope that the Russians would sue for
a peace. For this dubious hope of the statesman, Napoleon
committed an undoubted blunder as a captain. It is hard to divorce
the statesman from the soldier. All great captains have relied on
state-craft, and properly so. But such was the purely military
syllogism.
Much has been written about Napoleon’s failure to put the guard
in at Borodino. Under parallel conditions at an earlier day, he would
certainly have done so. That he did not is but one link more in the
growing chain of indecisiveness. But had he done so, and won a
more complete victory, would it have made any eventual difference?
Smolensk was his last point of military safety. Even had he been
able to winter in Russia, it is not plain how spring would have
bettered his case, in view of the logistic difficulties and of the temper
of the Russian emperor and people. Time in this campaign was of
the essence.
Once or twice on the terrible retreat, Napoleon’s old fire and
decision came to the fore, but during the bulk of it he was apparently
careless of what was happening. He habitually left to his generals all
but the crude direction of the outlying corps. The contrast between
Napoleon in this disaster and Napoleon after raising the siege of
Acre, or after the defeat at Aspern and Essling, is marked. He did not
oppose his old countenance to misfortune.
After this campaign, in which the grand army of half a million
men was practically annihilated, Napoleon showed extraordinary
energy in raising new troops, and actually put into the field, the
succeeding spring, no less than three hundred and fifty thousand
men. They were not the old army, but they were so many men.
Napoleon understood this: “We must act with caution, not to bring
bad troops into danger, and be so foolish as to think that a man is a
soldier.” He had thirteen hundred guns. “Poor soldiers need much
artillery.” The lack of good officers was the painful feature. The few
old ones who were left were ruined by bad discipline. The new ones
were utterly inexperienced.
In the campaign of 1813, Napoleon showed all his old power of
conception. The intellectual force of this man never seemed
overtaxed. But the lack of resolution became still more marked. He
began by winning two battles,—Lützen and Bautzen,—in which he
freely exposed himself and worked with all his old energy, to lend his
young troops confidence. He was then weak enough to enter into an
armistice with the allies. This was a singularly un-Napoleonic thing to
do. He had turned the enemy’s right and was strategically well
placed. It was just the time to push home. If the reasons he alleged
—want of cavalry and fear of the dubious position of Austria—were
really the prevailing ones, Napoleon was no longer himself, for his
wonderful successes hitherto had come from bold disregard of just
such things.
Napoleon here shows us how often fortune is of a man’s own
making. So long as he would not allow circumstances to dictate to
him, fortune was constant. When he began to heed adverse facts,
we see first indecisive victories, then half successes, and by and by
we shall see failure and destruction.
The operations about and succeeding Dresden show a
vacillation which contrasts with the intellectual vigor. For the first time
Napoleon conducted a defensive campaign. He studied his chances
of an offensive, and cast them aside for reasons which would not
have weighed a moment with him in 1805. And yet the defensive
against his concentrically advancing enemies was no doubt the best
policy. It shows Napoleon’s judgment to have been better than ever.
After this brilliant victory Napoleon ordered a pursuit—which he
ought to have made effective—across the Erzgebirge, but without
issuing definite instructions. Sickness forbade the personal
supervision he had expected to give; troops intended to sustain the
advanced corps were diverted from this duty by a sudden change of
purpose. Here was, as Jomini says, “without contradiction, one of
Napoleon’s gravest faults.” But Napoleon had got used to seeing
things turn in his favor, until he deemed constant personal effort
unnecessary. Decreasing strength had limited his activity; great
exertion was irksome. The immediate result of this ill-ordered
operation was the destruction of a corps; the secondary result, the
re-encouragement of the allies, whose morale had been badly
shaken by three defeats, and whose main army he should have
followed into Bohemia and broken up. The grand result was loss of
time, which to Napoleon was a dead loss, a new advance of the
allies, and the battle of Leipsic. During all this time, while Napoleon’s
execution was weak compared to his old habit, his utterances and
orders showed the clearest, broadest conception of what was
essential. But he was no longer the man who used to gallop forty to
sixty miles a day to use his eyes. Even at Leipsic he exhibited at
times his old power; when defeat was certain he lapsed into the
same indifference he had shown on the Russian retreat.
Nothing now, in a military sense, could save Napoleon, except to
concentrate all his forces into one body and manœuvre against the
allies with his old vigor. But the Emperor Napoleon could not bear to
give up Italy, Belgium, Spain, as General Bonaparte had given up
Mantua to beat the enemy at Castiglione; and he committed the
grievous mistake of not concentrating all his forces for the defence of
France. The campaign around Paris is a marvel of audacious
activity, though indeed it did not bring up any of the larger intellectual
problems of Marengo, Ulm, or Jena. If Napoleon had done half as
good work with the larger army he might have had, there is scarce a
doubt but that he would have gone far towards peace with honor. As
it was, he was crushed by numbers. But no words can too highly
phrase his military conduct, within its limits, in this brief campaign.
There is but one mistake,—the underrating of his enemy, the
misinterpretation of manifest facts.
The Waterloo campaign (1815), as already said, bears marked
resemblance to that of 1796. The details of Waterloo are so well
known that only the reasons will be noted which appear to make
Napoleon’s first so great a success and his last so great a failure.
At the beginning of June, Napoleon had available for Belgium,
where he proposed to strike the allied forces, one hundred and ten
thousand foot, and thirteen thousand five hundred horse. In Belgium
were Wellington, covering Brussels with ninety-five thousand men,
and Blucher lying from Charleroi to Namur with one hundred and
twenty-four thousand. Napoleon was superior to either; inferior to
both together. He chose against these allied armies the same
offensive manœuvre he had employed against Beaulieu and Colli,—
a strategic breaking of their centre, so as to separate them and
attack each one separately. The controlling reasons were the same.
The allies were of different nationalities, and each had a different
base, as well as varying interests. If cut in two they no doubt would
retire eccentrically, of which Napoleon could take immediate
advantage. The key to the whole problem was the exhibition by him
of foresight, boldness, and rapid action. The plan could not be better.
He concentrated on Charleroi. From here led two pikes, one to
Brussels, which was Wellington’s line of advance and retreat, one to
Liège, which was Blucher’s. Wellington and Blucher were connected
by the Namur-Nivelles road, which cut the other pikes at Quatre-Bras
and near Ligny. In order to push in between the allies to any effect,
Napoleon must seize on both these points.
WATERLOO CAMPAIGN
The French army broke up June 15th at 3 A.M. Napoleon was
full of eagerness and early in the saddle. The French advanced with
slight opposition to Quatre-Bras, and forced the Prussians back to
Fleurus. Napoleon remained in the saddle all day, then retired to
Charleroi overcome with a fatigue which seemed to paralyze his
mental faculties. He could no longer conquer sleep as of old. His
bodily condition was bad, and even the necessity of present success
was unable to evoke persistent effort. There is a singular difference
between Napoleon at this time and grim old Frederick in 1759
suffering from gout. The king never gave up for an instant his
restless work. Disease and pain could not subdue his obstinate
diligence. The emperor’s ailments overcame his zeal. Here began
those little lapses of unused time whose addition, in four days,
sufficed to bring Napoleon to the end of his career. The plan of
campaign was as brilliantly thought out and begun as that of 1796,
and with equal vigor would have equally succeeded. Wellington and
Blucher had foreseen the manœuvre, and agreed to concentrate for
mutual support at Quatre-Bras and Ligny. But Wellington, instead of
holding Quatre-Bras, gave Nivelles as the rallying-point. Not even
Würmser or Mack could have made an error more in Napoleon’s
favor, for this separated him from Blucher instead of gaining him his
support. Napoleon had the chance to strike Blucher singly.
Wellington had not yet assembled. Napoleon should have reached
Quatre-Bras and Ligny on the 15th, as he could easily have done, or
at a very early hour on the 16th. But no orders even were issued till
nearly 9 A.M. of the 16th. In his old days, Napoleon would have been
at the outposts at daylight, have gauged the situation with his own
eyes and his incomparable power of judgment, and would have
attacked at an early hour. But he did not reach the ground till noon
nor finish his reconnoissance till 2 P.M. Ney had been sent to
Quatre-Bras.
Despite delays, however, part of Napoleon’s plan did succeed.
Wellington was prevented from joining Blucher, and Blucher was
beaten and fell back in disorder. Now Napoleon’s object was so to
manœuvre as to keep the allies apart. This could be done only by
immediate pursuit. He must push on after Blucher relentlessly, so as
to throw him off in an easterly direction, where he could observe him
with a small force, while he should dispose of Wellington singly. And
the more Wellington should manage to push back Ney, the graver
danger he would run.
Nothing was done about the pursuit of Blucher on the night of
16th to 17th. Next morning Napoleon leisurely visited the battle-field
of Ligny and conversed with his officers about indifferent things.
None of the old-time drive was manifest. It was again noon before he
ordered Grouchy in pursuit of the Prussians, while he himself would
turn against the English. Grouchy got off about 2 P.M. No one knew
at that time whether Blucher had retired on Namur or Wavre. In
earlier days Napoleon would have ascertained this fact with his own
eyes, for it was the one fact to make no mistake about. Whether to
ascertain this was the duty of the staff or the general is immaterial.
That Napoleon did not do so may not have been his fault; but it was
his misfortune. Great captains have won success by personal activity
and by relying only on themselves in critical matters. In estimating a
great soldier, one must number all his errors of omission and
commission. No general may shelter himself behind the lapse of a
subordinate. He must stand or fall by what he himself does or fails to
do.
But the fate of the campaign was already sealed. Blucher had
had the night of the 16th to 17th, and the morning of the 17th, and he
had used the respite well. He boldly threw up his own base on Liège
and marched on Wavre to rejoin Wellington. Napoleon had assumed
that Blucher would retire along his line of communications. He
desired him to do this, and erroneously calculated on his having
done so. The object of breaking the allied centre, the sundering of
the allies so as to beat them in detail, had been forfeited by the
sixteen or eighteen hours of unnecessary delays after the battle of
Ligny.
The battle of Waterloo itself has been so fully and ably discussed
from this rostrum, and Grouchy’s part of the failure so clearly
explained, that I will go no further. It seems clear that the battle was
lost on the day preceding it. If Blucher did not join Wellington by one
means he would by another, when Napoleon gave him so many
hours leeway. Nothing but the old activity in following up his initial
success could possibly have enabled Napoleon to fight Wellington
and Blucher separately,—and if they joined they were sure to beat
him. Had he kept right on, he would have beaten Wellington, and
Blucher would have retired. His difficulties here were not great. He
was successful in his early steps, and failed in later ones. The
explanation of the whole matter lies in the fact that Napoleon’s
physical powers and moral initiative had waned. His intellect was
unimpaired, but his character had lost its native quality.
No man should be subject to criticism for inability to do his best
work when suffering from disease. It is not intended to criticise in this
sense. La critique est facile; l’art est difficile. The motto of these
lectures is that coexistent intellect, character, and opportunity go to
make the great captain. We see Napoleon for twelve years possibly
the greatest soldier who ever lived. We then see his successes
lessen. It was not from declining intellect. It was partly lesser
opportunity,—that is, greater difficulties,—partly loss of activity and
decisiveness,—or, in other words, character,—proceeding from
weakening physique or decrease of moral strength. There may be
room for doubt whether failing health alone, or failing health
combined with waning character, caused the indecisiveness. It
descends into a question of nomenclature. Of the bald fact there can
be no doubt. Napoleon at Waterloo was not as great as Napoleon at
Austerlitz.
The secret of Napoleon’s power lay in his clear eye for facts, his
positive mind. Carlyle says: “The man had a certain, instinctive,
ineradicable feeling for reality, and did base himself upon fact so
long as he had any basis.” Napoleon said of himself that he was
most of a slave of all men, obliged to obey a heartless master, the
calculation of circumstances and the nature of things. Coupled with
this were a reliance on facts, rare capacity for divination, and an
immense power of imagination. But finally the latter overran the other
qualities. His successes convinced him that he could do anything; he
forgot what his success had been grounded on, and he began to
neglect facts. “It is not possible” is not French, said he. This is the
best of maxims construed one way,—the worst, if misconstrued.
Napoleon believed himself able to accomplish all things, until his
accuracy of judgment was lost in his refusal to look facts in the face.
He ceased to be slave of the nature of things. He deserted belief in
facts for belief in his destiny. Finally facts became for him not what
they were, but what he wished them to be. He refused credit to what
did not suit his theory of how things ought to turn.
Napoleon had what rarely coexists,—an equally clear head on
the map and in the field. On the map he was able in both theory and
practice. His theories are text-books; his letters are treatises. No
higher praise can be spoken than to say that every one of
Napoleon’s fourteen campaigns was, in a military sense, properly
planned.
Napoleon showed the value of masses in strategy as well as
tactics. In former times the worth of troops was of greater value than
numbers. To-day worth of itself is less essential than it was.
Napoleon founded his calculations on the equality of thousands. It is
he who collated all that was done by the other great captains,
clothed it in a dress fit for our own days, and taught the modern
world how to make war in perfect form.
Strategy will always remain the same art. Its uses are to-day
varied by railroads, telegraphs, arms of precision. What was not
allowable in the Napoleonic era can be undertaken now with safety.
But all this has only modified, it has not changed strategy. The
tendency of modern armies is toward better organization. Ramrod
discipline is giving way to dependence on the individuality of officers
and men, and to instruction in doing what at the moment is the most
expedient thing. But every great soldier will be great hereafter from
the same causes which have made all captains what they were; in
conducting war he will be governed by the same intellectual and
moral strength which they exhibited, and will do, as they always did,
what befits the time, unfettered by rules and maxims, but with a
broad comprehension of their true value.
Napoleon is so close to this generation that he sometimes
appears to us gigantic beyond all others. He certainly moulded into
shape the method in use to-day, which the Prussians have carried
forward to its highest development by scrupulous preparation in
every department, personal service, and the teaching of individuals
to act with intelligent independence. That Napoleon was always
intellectually the equal, and, in the first part of his career in the moral
forces, the equal of any of the captains, cannot be denied. But we
must remember that because Napoleon wrought in our own times we
can the better appreciate what he did, while our more meagre
knowledge of the others makes it impossible to see as clearly the
manner in which, to accomplish their great deeds, they must have
patterned their means to the work to be done. “The most important
qualities of an army leader,” says Jomini, “will always be a great
character or constitutional courage, which leads to great
determinations; sang froid or bodily courage which conquers danger;
learning appears in third line, but it will be a strong help.”
Napoleon exhibited these qualities in full measure up to 1808,
and comes close to being, at his best, the greatest of the captains.
He failed to exhibit the moral power in as great measure thereafter. It
was not years, for Cæsar and Frederick were older when they
showed these same qualities in the highest degree. That Napoleon
lost activity and decisiveness, and thereby forfeited success, is no
reproach. No man can keep his faculties beyond a certain period. He
lacked that equipoise which enables a man to stand success. He did
not last as the others lasted; and proved that only so long as a man
retains the highest grade of character can he remain a great captain.
At the same time it is but fair to repeat that the conditions under
which Napoleon worked gradually became more difficult; that the
allies learned from him as the Romans did from Hannibal, and made
fewer mistakes as the years went on; that he was not always able to
retain about him the most efficient of his marshals; that he
commanded vastly larger armies than the other captains. His task
was larger accordingly.
Napoleon’s strategy shows a magnificence in conception, a
boldness in execution, and a completeness and homogeneity not
shown by any other leader. The other captains can only stand beside
him because they builded so that he might add; they invented so that
he might improve. But while Napoleon reached a height beyond the
others, they did not show the decrease of genius which he showed.
Too little time is left to draw a satisfactory comparison between
Napoleon and his peers in arms. In Frederick we recognize a man of
higher standard than Napoleon reached. Not merely because
Frederick was, of all the captains, the only one who, with vastly
smaller forces, attacked troops equal to his own and defeated them
right and left,—in other words, because he was typical tactician, the
typical fighter,—but because he was steadfast in victory and defeat
alike; because he was so truly a king to his people as well as a
soldier; because he so truly merged his own self in the good of
Prussia. Napoleon flared like a comet. Frederick burned like a planet
or a fixed star,—less brilliant, less startling, but ever constant.
Frederick at the close of his life was the same great man. Napoleon
had burned out his lamp. Frederick never waned. Years or infirmity
never changed his force or determination, or limited his energies.
Moreover, Frederick, like Hannibal, was greater in disaster than in
success. Napoleon succumbed to disaster. Frederick and Hannibal
alone held themselves against overwhelming civilized armies. They
were stronger, more able, more determined, more to be feared the
more misfortune crowded upon them. We instinctively couple
Napoleon’s genius with his greatest success; we couple Hannibal’s
or Frederick’s with their direst disasters. Alexander and Gustavus
never looked real disaster in the face, as Frederick before Leuthen,
or Hannibal after the Metaurus. Nor indeed did Cæsar. But Cæsar
opposed wonderful countenance to threatening calamity.
Looking at Napoleon and Gustavus, it is perhaps impossible to
compare them. Gustavus was immeasurably above all the others in
purity of character, and their equal in force and intellect. To him we
owe the revival of intellectual war, lost for seventeen centuries; and
on what he did Frederick and Napoleon builded. Napoleon is nearer
akin to Cæsar. Perhaps, take them all in all, as soldiers, statesmen,
law-givers, Cæsar and Napoleon are the two greatest men. But they
sink below the rest in their motives and aspirations. Neither ever lost
sight of self; while Alexander’s ambition was not only to conquer the
East, but to extend Greek civilization; the motive of Hannibal and
Frederick was patriotic, and that of Gustavus love of country and
religion. Three of the captains were kings from the start. Their
ambition was naturally impersonal. Of the other three, Hannibal
alone worked from purely unselfish motives.
Nor can we compare Napoleon with Hannibal. In his successes
Napoleon is equally brilliant, more titanic; in his failures he falls so far
below the level of this great pattern of patient, never-yielding
resistance to adversity as to be lost. To Alexander fighting semi-
civilized armies, Napoleon can only be likened in his Egyptian
campaigns, and in this he in no sense rises to the height of the
Macedonian. Napoleon’s genius was most apparent on the familiar
fields of Europe.
In intellectual grasp, all six great captains stand side by side. In
enthusiastic activity and in all the qualities which compel good
fortune, Alexander stands clearly at the head. No one but Frederick
has perhaps so brilliant a string of tactical jewels as Hannibal, while
in a persistent unswerving struggle of many years to coerce success
against the constantly blackening frowns of Fortune, Hannibal stands
alone and incomparable. Cæsar was a giant in conception and
execution alike, and stands apart in having taught himself in middle
life how to wage war, and then waging in it a fashion equalled only
by the other five. Gustavus will always rank, not only as the man who
rescued intellectual war from oblivion, but as the most splendid
character, in nobility of purpose and intelligence of method, which
the annals of the world have to show. Frederick is not only the Battle
Captain who never blenched at numbers, but truly the Last of the
Kings,—king and priest, in the history of mankind. Napoleon carries
us to the highest plane of genius and power and success, and then
declines. We begin by feeling that here is indeed the greatest of the
captains, and we end by recognizing that he has not acted out the
part. No doubt, taking him in his many-sidedness, Cæsar is the
greatest character in history. It may not unfairly be claimed that
Napoleon follows next, especially in that he preserved for Europe
many germs of the liberty which was born of the blood of the
Revolution. Cæsar was the most useful man of antiquity; Napoleon
comes near to being the most useful man of modern times. But
neither Cæsar nor Napoleon appeal to us as do splendid, open-
hearted Alexander; patient, intrepid, ever-constant Hannibal; the
Christian hero, Gustavus; and daring, obstinate, royal Frederick.

You might also like