40,81 €
Master the art of identifying vulnerabilities within the Windows OS and develop the desired solutions for it using Kali Linux.
Key Features
Book Description
Windows has always been the go-to platform for users around the globe to perform administration and ad hoc tasks, in settings that range from small offices to global enterprises, and this massive footprint makes securing Windows a unique challenge. This book will enable you to distinguish yourself to your clients.
In this book, you'll learn advanced techniques to attack Windows environments from the indispensable toolkit that is Kali Linux. We'll work through core network hacking concepts and advanced Windows exploitation techniques, such as stack and heap overflows, precision heap spraying, and kernel exploitation, using coding principles that allow you to leverage powerful Python scripts and shellcode.
We'll wrap up with post-exploitation strategies that enable you to go deeper and keep your access. Finally, we'll introduce kernel hacking fundamentals and fuzzing testing, so you can discover vulnerabilities and write custom exploits.
By the end of this book, you'll be well-versed in identifying vulnerabilities within the Windows OS and developing the desired solutions for them.
What you will learn
Who this book is for
This book is for penetration testers, ethical hackers, and individuals breaking into the pentesting role after demonstrating an advanced skill in boot camps. Prior experience with Windows exploitation, Kali Linux, and some Windows debugging tools is necessary
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 510
Veröffentlichungsjahr: 2018
Copyright © 2018 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.
Commissioning Editor: Vijin BorichaAcquisition Editor: Shrilekha InaniContent Development Editor: Sharon RajTechnical Editor:Komal KarneCopy Editor: Safis EditingProject Coordinator:Virginia DiasProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Tom ScariaProduction Coordinator: Shraddha Falebhai
First published: July 2018
Production reference: 1270718
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78829-566-6
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Phil Bramwell acquired the Certified Ethical Hacker and Certified Expert Penetration Tester certifications at the age of 21. His professional experience includes Common Criteria design reviews and testing, network security consulting, penetration testing, and PCI-DSS compliance auditing for banks, universities, and governments. He later acquired the CISSP and Metasploit Pro Certified Specialist credentials. Today, he is a cybersecurity and cryptocurrency consultant and works as a cybersecurity analyst specializing in malware detection and analysis.
Abhijit Mohanta works as a malware researcher for Juniper Threat Labs. He worked as a malware researcher for Cyphort, MacAfee, and Symantec. He has expertise in reverse engineering. He has experience working with antivirus and sandbox technologies. He is author of the book Preventing Ransomware, Understand everything about digital extortion and its prevention. He has written a number of blogs on malware research. He has filed a couple of patents related to malware detection.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Hands-On Penetration Testing on Windows
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Disclaimer
Bypassing Network Access Control
Technical requirements
Bypassing MAC filtering – considerations for the physical assessor
Configuring a Kali wireless access point to bypass MAC filtering
Design weaknesses – exploiting weak authentication mechanisms
Capturing captive portal authentication conversations in the clear
Layer-2 attacks against the network
Bypassing validation checks
Confirming the Organizationally Unique Identifier
Passive Operating system Fingerprinter
Spoofing the HTTP User-Agent
Breaking out of jail – masquerading the stack
Following the rules spoils the fun – suppressing normal TCP replies
Fabricating the handshake with Scapy and Python
Summary
Questions
Further reading
Sniffing and Spoofing
Technical requirements
Advanced Wireshark – going beyond simple captures
Passive wireless analysis
Targeting WLANs with the Aircrack-ng suite
WLAN analysis with Wireshark
Active network analysis with Wireshark
Advanced Ettercap – the man-in-the-middle Swiss Army Knife
Bridged sniffing and the malicious access point
Ettercap filters – fine-tuning your analysis
Killing connections with Ettercap filters
Getting better – spoofing with BetterCAP
ICMP redirection with BetterCAP
Summary
Questions
Further reading
Windows Passwords on the Network
Technical requirements
Understanding Windows passwords
A crash course on hash algorithms
Password hashing methods in Windows
If it ends with 1404EE, then it's easy for me – understanding LM hash flaws
Authenticating over the network–a different game altogether
Capturing Windows passwords on the network
A real-world pen test scenario – the chatty printer
Configuring our SMB listener
Authentication capture
Hash capture with LLMNR/NetBIOS NS spoofing
Let it rip – cracking Windows hashes
The two philosophies of password cracking
John the Ripper cracking with a wordlist
John the Ripper cracking with masking
Reviewing your progress with the show flag
Summary
Questions
Further reading
Advanced Network Attacks
Technical requirements
Binary injection with BetterCAP proxy modules
The Ruby file injection proxy module – replace_file.rb
Creating the payload and connect-back listener with Metasploit
HTTP downgrading attacks with sslstrip
Removing the need for a certificate – HTTP downgrading
Understanding HSTS bypassing with DNS spoofing
HTTP downgrade attacks with BetterCAP ARP/DNS spoofing
The evil upgrade – attacking software update mechanisms
Exploring ISR Evilgrade
Configuring the payload and upgrade module
Spoofing ARP/DNS and injecting the payload
IPv6 for hackers
IPv6 addressing basics
Local IPv6 reconnaissance and the Neighbor Discovery Protocol
IPv6 man-in-the-middle – attacking your neighbors
Living in an IPv4 world – creating a local 4-to-6 proxy for your tools
Summary
Questions
Further reading
Cryptography and the Penetration Tester
Technical requirements
Flipping the bit – integrity attacks against CBC algorithms
Block ciphers and modes of operation
Introducing block chaining
Setting up your bit-flipping lab
Manipulating the IV to generate predictable results
Flipping to root – privilege escalation via CBC bit-flipping
Sneaking your data in – hash length extension attacks
Setting up your hash attack lab
Understanding SHA-1's running state and compression function
Data injection with the hash length extension attack
Busting the padding oracle with PadBuster
Interrogating the padding oracle
Decrypting a CBC block with PadBuster
Behind the scenes of the oracle padding attack
Summary
Questions
Further reading
Advanced Exploitation with Metasploit
Technical requirements
How to get it right the first time – generating payloads
Installing Wine32 and Shellter
Payload generation goes solo – working with msfvenom
Creating nested payloads
Helter Skelter evading antivirus with Shellter
Modules – the bread and butter of Metasploit
Building a simple Metasploit auxiliary module
Efficiency and attack organization with Armitage
Getting familiar with your Armitage environment
Enumeration with Armitage
Exploitation made ridiculously simple with Armitage
A word about Armitage and the pen tester mentality
Social engineering attacks with Metasploit payloads
Creating a Trojan with Shellter
Preparing a malicious USB drive for Trojan delivery
Summary
Questions
Further reading
Stack and Heap Memory Management
Technical requirements
An introduction to debugging
Understanding the stack
Understanding registers
Assembly language basics
Disassemblers, debuggers, and decompilers – oh my!
Getting cozy with the Linux command-line debugger – GDB
Stack smack – introducing buffer overflows
Examining the stack and registers during execution
Lilliputian concerns – understanding endianness 
Introducing shellcoding
Hunting bytes that break shellcode
Generating shellcode with msfvenom
Grab your mittens, we're going a NOP sledding
Summary
Questions
Further Reading
Windows Kernel Security
Technical requirements
Kernel fundamentals – understanding how kernel attacks work
Kernel attack vectors
The kernel's role as time cop
It's just a program
Pointing out the problem – pointer issues
Dereferencing pointers in C and assembly
Understanding NULL pointer dereferencing
The Win32k kernel-mode driver
Passing an error code as a pointer to xxxSendMessage()
Metasploit – exploring a Windows kernel exploit module
Practical kernel attacks with Kali
An introduction to privilege escalation
Escalating to SYSTEM on Windows 7 with Metasploit
Summary
Questions
Further reading
Weaponizing Python
Technical requirements
Incorporating Python into your work
Why Python?
Getting cozy with Python in your Kali environment
Introducing Vim with Python syntax awareness
Python network analysis
Python modules for networking
Building a Python client
Building a Python server
Building a Python reverse shell script
Antimalware evasion in Python
Creating Windows executables of your Python scripts
Preparing your raw payload
Writing your payload retrieval and delivery in Python
Python and Scapy – a classy pair
Revisiting ARP poisoning with Python and Scapy
Summary
Questions
Further reading
Windows Shellcoding
Technical requirements
Taking out the guesswork – heap spraying
Memory allocation – stack versus heap
Shellcode whac-a-mole – heap spraying fundamentals
Shellcode generation for the Java vulnerability
Creating the malicious website to exploit Java
Debugging Internet Explorer with WinDbg
Examining memory after spraying the heap
Fine-tuning your attack and getting a shell
Understanding Metasploit shellcode delivery
Encoder theory and techniques – what encoding is and isn't
Windows binary disassembly within Kali
Injection with Backdoor Factory
Code injection fundamentals – fine-tuning with BDF
Trojan engineering with BDF and IDA
Summary
Questions
Further reading
Bypassing Protections with ROP
Technical requirements
DEP and ASLR – the intentional and the unavoidable
Understanding DEP
Understanding ASLR
Testing DEP protection with WinDbg
Demonstrating ASLR on Kali Linux with C
Introducing return-oriented programming
Borrowing chunks and returning to libc – turning the code against itself
The basic unit of ROP – gadgets
Getting cozy with our tools – MSFrop and ROPgadget
Metasploit Framework's ROP tool – MSFrop
Your sophisticated ROP lab – ROPgadget
Creating our vulnerable C program without disabling protections
No PIE for you – compiling your vulnerable executable without ASLR hardening
Generating a ROP chain
Getting hands-on with the return-to-PLT attack
Extracting gadget information for building your payload
Finding the .bss address
Finding  a pop pop ret structure
Finding addresses for system@plt and strcpy@plt functions
Finding target characters in memory with ROPgadget and Python
Go, go, gadget ROP chain – bringing it together for the exploit
Finding the offset to return with gdb
Writing the Python exploit
Summary
Questions
Further reading
Fuzzing Techniques
Technical requirements
Network fuzzing – mutation fuzzing with Taof proxying
Configuring the Taof proxy to target the remote service
Fuzzing by proxy – generating legitimate traffic
Hands-on fuzzing with Kali and Python
Picking up where Taof left off with Python – fuzzing the vulnerable FTP server
The other side – fuzzing a vulnerable FTP client
Writing a bare-bones FTP fuzzer service in Python
Crashing the target with the Python fuzzer
Fuzzy registers – the low-level perspective
Calculating the EIP offset with the Metasploit toolset
Shellcode algebra – turning the fuzzing data into an exploit
Summary
Questions
Further reading
Going Beyond the Foothold
Technical requirements
Gathering goodies – enumeration with post modules
ARP enumeration with meterpreter
Forensic analysis with meterpreter – stealing deleted files
Privileges enumeration with meterpreter
Internet Explorer enumeration – discovering internal web resources
Network pivoting with Metasploit
Just a quick review of subnetting
Launching Metasploit into the hidden network with autoroute
Escalating your pivot – passing attacks down the line
Extracting credentials with hashdump
Quit stalling and pass the hash – exploiting password equivalents in Windows
Summary
Questions
Further reading
Taking PowerShell to the Next Level
Technical requirements
Power to the shell – PowerShell fundamentals
What is PowerShell?
PowerShell's own cmdlets and PowerShell scripting language
Working with the registry
Pipelines and loops in PowerShell
It gets better – PowerShell's ISE
Post-exploitation with PowerShell
ICMP enumeration from a pivot point with PowerShell
PowerShell as a TCP-connect port scanner
Delivering a Trojan to your target via PowerShell
Offensive PowerShell – introducing the Empire framework
Installing and introducing PowerShell Empire
Configuring listeners
Configuring stagers
Your inside guy – working with agents
Configuring a module for agent tasking
Summary
Questions
Further reading
Escalating Privileges
Technical requirements
Climb the ladder with Armitage
Named pipes and security contexts
Impersonating the security context of a pipe client
Superfluous pipes and pipe creation race conditions
Moving past the foothold with Armitage
Armitage pivoting
When the easy way fails—local exploits
Kernel pool overflow and the danger of data types
Let's get lazy – Schlamperei privilege escalation on Windows 7
Escalation with WMIC and PS Empire
Quietly spawning processes with WMIC
Create a PowerShell Empire agent with remote WMIC
Escalating your agent to SYSTEM via access token theft
Dancing in the shadows – looting domain controllers with vssadmin
Extracting the NTDS database and SYSTEM hive from a shadow copy
Exfiltration across the network with cifs
Password hash extraction with libesedb and ntdsxtract
Summary
Questions
Further reading
Maintaining Access
Technical requirements
Persistence with Metasploit and PowerShell Empire
Creating a payload for Metasploit persister
Configuring the Metasploit persistence module and firing away
Verifying your persistent Meterpreter backdoor
Not to be outdone – persistence in PS Empire
Elevating the security context of our Empire agent
Creating a WMI subscription for stealthy persistence of your agent
Verifying agent persistence
Hack tunnels – netcat backdoors on the fly
Uploading and configuring persistent netcat with meterpreter
Remotely tweaking Windows Firewall to allow inbound netcat connections
Verifying persistence is established
Maintaining access with PowerSploit
Installing the persistence module in PowerShell
Configuring and executing meterpreter persistence
Lying in wait – verifying persistence
What did the persistence script do?
Summary
Questions
Further reading
Tips and Tricks
Getting familiar with VMware Workstation
VMware versus Oracle for desktop virtualization
Building your attack lab
Finding Windows machines for your lab
Downloading Edge tester VMs for developers
Downloading an evaluation copy of Windows Server
Installing Windows from an OEM disc or downloaded ISO file
Network configuration tricks
Network address translation and VMnet subnets
Using the Virtual Network Editor
Further reading
Assessment
Chapter 1: Bypassing Network Access Control
Chapter 2: Sniffing and Spoofing
Chapter 3: Windows Passwords on the Network
Chapter 4: Advanced Network Attacks
Chapter 5: Cryptography and the Penetration Tester
Chapter 6: Advanced Exploitation with Metasploit
Chapter 7: Stack and Heap Memory Management
Chapter 8: Windows Kernel Security
Chapter 9: Weaponizing Python
Chapter 10: Windows Shellcoding
Chapter 11: Bypassing Protections with ROP
Chapter 12: Fuzzing Techniques
Chapter 13: Going Beyond the Foothold
Chapter 14: Taking PowerShell to the Next Level
Chapter 15: Escalating Privileges
Chapter 16: Maintaining Access
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book takes a hands-on approach to teaching and understanding penetration testing concepts at an intermediate to advanced level. It's designed to lay the foundation for advanced roles in the field with an engaging and easy-to-follow style. There are a lot of books on the subject of penetration testing, but what makes this book special is the emphasis on the underlying logic and mechanisms of the concept at hand. Recognizing that there aren't enough pages to give each subject what it deserves, this book takes a springboard approach to the topics by providing enough key information and theory to inform further research outside of these pages. The reader can thus spend less time searching and more time learning.
This book is for penetration testers who want to break out of old routines, security professionals who want to break into penetration testing, security managers who want to understand penetration testing, and young security students and professionals who excel in ethical-hacking boot camps.
Chapter 1, Bypassing Network Access Control, focuses on getting a foothold in the network. Network Access Control systems, or NACs, rely on certain detection technology – this chapter will review them and how they work at a low level.
Chapter 2, Sniffing and Spoofing, will discuss advanced Wireshark techniques to give the reader practical experience in low-level traffic analysis. The reader will then learn applied network-spoofing attacks, focusing on layer-2 poisoning attacks and DNS spoofing.
Chapter 3, Windows Passwords on the Network, demonstrates advanced Windows password attacks. The chapter reviews how Windows passwords are carried over the network and then provides practical demonstrations of capturing, understanding, and cracking Windows passwords to gain access.
Chapter 4, Advanced Network Attacks, ties together the network-hacking portion with coverage of advanced concepts. We cover software-update hijacking, SSL stripping, and routers. A discussion of IPv6 is included along with practical demonstrations of using Kali to attack IPv6 implementations.
Chapter 5, Cryptography and the Penetration Tester, discusses cryptographic system implementations and practical attacks against them. Attacking message integrity via bit-flipping is demonstrated against the AES implementation of cipher block chaining. We also look at length-extension attacks and run through a demonstration of how they work. Another demonstration of an attack against confidentiality will be given with a padding-oracle attack using Kali.
Chapter 6, Advanced Exploitation with Metasploit, will take the reader to the next level with the standard attack framework in every pen tester's toolkit: Metasploit. The finer points of exploits in Metasploit are discussed, including working with the payload generator, metamodules, and building custom modules. Attacks will be demonstrated while organizing them with Metasploit's task automation features.
Chapter 7, Stack and Heap – Memory Management, guides the reader through understanding memory management for practical application to pen testing. An introduction to stack overflow attacks is demonstrated step by step. The reader will use a debugger to develop exploitation opportunity from finding software bugs.
Chapter 8, Windows Kernel Security, guides the reader through understanding and attacking the other side of the Windows virtual address space: the kernel. The reader will understand the fundamentals of kernel exploitation, including context switching and the use of the scheduler to inform race condition attacks, and vulnerabilities that the hacker seeks to exploit, including pointer issues, such as NULL pointer dereferencing and corrupted pointers.
Chapter 9, Weaponizing Python, is a crash course in Python to bring the reader to a level of understanding that will facilitate pen testing tasks with Python modules. Some of the techniques covered that can be transformed into pen testing tools include network analysis with Python and Scapy.
Chapter 10, Windows Shellcoding, will step through stack-protection mechanisms of the Windows OS and demonstrate practical bypass methods. We demonstrate heap spraying with step-by-step explanations, as well as exploit creation.
Chapter 11, Bypassing Protections with ROP, will guide the reader through understanding Windows memory protection mechanisms and bypassing them with Return-Oriented Programming (ROP). The mechanisms discussed are Data Execution Prevention (DEP) and Address Space Layout Randomization (ASLR). The reader will understand the core assembly mechanisms that allow ROP to work, building on knowledge of memory management from other chapters.
Chapter 12, Fuzzing Techniques, guides the reader through practical fuzzing techniques. The reader will understand the core principle and will be able to understand what's happening at a low memory-management level. The reader will have hands-on experience with trial and error fuzzing applications. From there, we will move on to more advanced fuzzing techniques, such as protocol fuzzing.
Chapter 13, Going Beyond the Foothold, explores the post-exploitation modules of Metasploit. The Windows post modules are introduced and practically demonstrated so the reader will know how to capture keystrokes from a compromised Windows host, scan the network for new targets, and learn and exploit trust relationships to complete the pivot. We then cover enumeration on the compromised Windows host to inform post-exploitation efforts.
Chapter 14, Taking PowerShell to the Next Level, guides the reader through PowerShell fundamentals with hands-on examples, and then moves on to offensive PowerShell techniques. Post-exploitation with the PowerShell Empire framework on Kali is explained and demonstrated in practical hands-on examples.
Chapter 15, Escalating Privileges, steps through Metasploit and PS Empire techniques while analyzing the core mechanisms, including duplication of tokens and named pipe impersonation. The reader will review local exploit options, a method for attacking Active Directory credentials on a domain controller, and a technique that leverages the Windows Management Instrumentation Command line (WMIC).
Chapter 16, Maintaining Access, guides the reader through a series of hands-on demonstrations of access maintenance via backdoors using tools such as Netcat. Metasploit, PS Empire, and PowerSploit persistence abilities are also discussed and demonstrated.
Chapter 17, Tips and Tricks, provides a brief discussion of virtualization on Windows to assist the reader in setting up a hacking lab with some hints on advanced virtual network configuration.
This book makes a few assumptions about the reader. You should have a solid understanding of networking essentials; layered interconnection concepts, such as the OSI model; and you should be self-sufficient with OS basics and troubleshooting. We won't cover getting your OS installed, and though basic installation instructions are provided for some tools, you need to be self-sufficient in troubleshooting any dependency problems you may run into in your unique environment.
This book tries to be as useful as possible even without a lab. It's a hands-on book first and foremost, but with the provided examples and coverage of concepts, you should be able to benefit from the information without your computer.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Penetration-Testing-on-Windows. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/HandsOnPenetrationTestingonWindows_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book 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 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 authors.packtpub.com.
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.
The information within this book is intended to be used only in an ethical manner. Do not use any information from the book if you do not have written permission from the owner of the equipment. If you perform illegal actions, you are likely to be arrested and prosecuted to the full extent of the law. Packt Publishing does not take any responsibility if you misuse any of the information contained within the book. The information herein must only be used while testing environments with proper written authorizations from appropriate persons responsible.
The network is the first thing we think about when we imagine computers getting hacked. It's the pen tester's playground. It's both the first step and the final frontier of compromising a computer. It's also what makes the compromise of a single computer effectively the compromise of an entire building full of computers. It's fitting, then, that we begin our journey with a discussion about compromising the network and using its own power and weaknesses to inform the pen test.
The first step is getting on the network in the first place, and there are human, architectural, and protocol factors that make the mere presence of an attacker on the network potentially devastating. For this reason, defenders often deploy network access control(NAC) systems. The intent of these systems is to detect and/or prevent an intrusion on the network by identifying and authenticating devices on the network. In this chapter, we will review some of the methods employed by NACs and demonstrate practical methods of bypassing these controls.
The following topics will be covered in this chapter:
Bypassing NACs with physical access to clone an authorized device
Captive portal methods and their weaknesses
Policy checks for new devices
Masquerading the stack of an authorized device
Kali Linux installed on a laptop
A USB wireless network interface card that supports promiscuous mode in Kali—I recommend Alfa cards
An attacker needs to be aware of methods for remote compromise: attacking the VPN, wireless infiltration from a distance using high-gain antennas, and so forth. However, the pen tester can never forget the big picture. This is a field where it's very easy to get caught up in the highly specific technical details and miss the human element of security design.
There's a design flaw concept that pen testers like to call the candy bar model. This simply refers to a network that is tough and crunchy on the outside, but gooey on the inside. In other words, it's a model that emphasizes the threats of the outside world when designing the security architecture, while assuming that someone who is physically inside company facilities has been vetted and is therefore trusted. The mindset here dates back many years; in the earliest days of what became the internet, the physical access points to the network were inside highly secure facilities. Packets coming in over the network were safely assumed to be from a secure environment and sent by an authorized individual. In today's world, a packet hitting the border of a company's network could be from an authorized individual on a business trip, or it could be from a clever teenager in Thailand eager to try out some newly learned tricks.
The candy bar model will come up in later chapters when we discuss other network attacks. Once you crack that outer shell, you'll often find that the path forward seems paved especially for you—and a successful compromise will inform your client of the devastating consequences of this mistaken assumption.
How you social engineer your target is a subject for another book altogether, but for the purposes of this discussion, let's assume that you have physical access to network drops. Not all physical access is the same, though: if you convinced your target to hire you as a full-time employee, then you'll have constant physical access. They'll even hand you a computer. However, what's more likely is that you've exploited a small gap in their physical security stance, and your presence can be undetected or tolerated for only a short period of time. You've snuck in through the smoker's door after striking up some conversation with an unwitting employee; you've been given permission to walk around for an hour with a convincing-looking contractor uniform and clipboard; or (my personal favorite) you've earned trust and affection by bringing in a big box of doughnuts for the people expecting an auditor's visit based on a well-scripted phone call. We'll demonstrate how to set up a Kali box to function as a rogue wireless access point while impersonating the MAC address of a VoIP phone.
You've found an unoccupied cubicle with an empty desk and a generic IP Phone. The phone is plugged in and working, so you know the network drop is active. We'll drop our small laptop running Kali here and continue the attack from outside.
First, we've unplugged the IP Phone so that our bad guy can take the port. We're going to clone the MAC address of the IP Phone on our Kali box's Ethernet port. From the perspective of a simple MAC address whitelisting methodology of NAC, this will look like the phone merely rebooted.
I use ifconfig to bring up the interface configuration. In my example, my Ethernet port interface is called eth0 and my wireless interface is called wlan0. I'll note this for later, as I will need to configure the system to run an access point with DHCP and DNS on wlan0, while running NAT through to my eth0 interface. I can use ifconfig eth0 hw ether to change the physical address of the eth0 interface. I've sneaked a peek at the label on the back of the IP Phone – the MAC address is AC:A0:16:23:D8:1A.
So, I bring the interface down for the change, bring it back up, then run ifconfig one more time to confirm the status of the interface with the new physical address:
Two handy tools in the Kali repository are dnsmasq and hostapd:
dnsmasq
is a lightweight network infrastructure utility. Completely free and written in C, this is a nifty tool for setting up a quick and dirty network on the fly, complete with DHCP and DNS forwarding. In our example, we're using it as a DHCP and DNS service for the wireless clients who connect to our access point (which would be you and your colleagues, of course).
hostapd
(host access point daemon) is, as the name implies, access point software for turning your ordinary wireless network interface into an access point and even an authentication server. You can confirm that whatever Wi-Fi card you're using supports AP mode with this command:
# iw list |grep "Supported interface modes" -A 8
If you see AP in the results, you're good to go. We use apt-get install hostapd dnsmasq to grab the tools.
First, let's configure dnsmasq. Open up /etc/dnsmasq.conf using the nano command:
You can see that the configuration file has everything you need to know commented out; I strongly recommend you sit down with the readme file to understand the full capability of this tool, especially so you can fine-tune your use for whatever you're doing in the field. Since this is a hands-on demonstration, I'm keeping it pretty simple:
I set my interface to
wlan0
, where the USB wireless card that will play the role of access point is located.
I set the DHCP range where new clients will be assigned IP addresses when they request an assignment. The format is
[bottom address],[top address],[lease time]
. The address range here is what would be assigned to new clients, so make sure you don't overlap with the gateway address. You're the gateway!
DHCP options specification. This isn't arbitrary—these numbers are specified in RFC 2132 and subsequent RFCs, so there's a lot of power here. For our purposes here, I'm setting the gateway with option
3
and DNS with option
6
. In this case, they're the same address as we would expect on a tiny LAN like this one. Note the address:
10.11.12.1
. That's the gateway that by definition, will be your
wlan0
interface. You'll define that address when you bring up the wireless interface just prior to firing up the access point.
I defined the upstream DNS server; I set it to Google
8.8.8.8
, but you can use something different.
I did some logging, just in case we need it.
Hit Ctrl + X and confirm the file name to save it. Now, we'll move on to the hostapd configuration. Open up /etc/hostapd/hostapd.conf using the nano command:
Again, this is a tool with a lot of power, so check out the readme file so you can fully appreciate everything it can do. You can create a rather sophisticated access point with this software, but we'll just keep it simple for this example:
I set the interface to
wlan0
, of course.
I defined the wireless driver; this is
nl80211
, the interface between
cfg80211
and user space, and it allows for management of the device.
ssid
is our service set identifier – our network's name. I'm using
NotABadGuy
because I want to convince the world that I'm really a good guy, but of course, you'll fine-tune this to your needs. There's a bit of social engineering potential here to minimize suspicion on the part of those casually scanning the environment.
hw_mode
is the 802.11 modulation standard;
b
,
g
, and
n
are common.
I've defined the channel here, but you can configure it to pick the channel automatically based on surveying.
macaddr_acl
is a Boolean flag to tell
hostapd
if we're using a MAC-based access control list. You'll have to decide if this is something you need for your purposes. In my example, I've configured encryption, and I like to use randomly generated MACs on my devices anyway, so I'd rather not deal with whitelisting MACs.
max_num_sta
is one way to keep the population of wireless clients restricted— this is the maximum number of clients that are allowed to join. I set mine as
1
here since I only expect myself to be joining, but you could omit this.
ignore_broadcast_ssid
simply allows you to hide the network. What it really does is cause your AP to ignore probe request frames that don't specify the SSID, so it will hide your network from active scans, but you should never consider a functional access point to be hidden. I want to see it in my example, so I set it to
0
.
The remaining options allow me to configure WPA2 encryption.
Believe it or not, those are the basics for our quick and dirty access point to the physical network. Now, I'll bring up the wlan0 interface and specify the gateway address I defined earlier. Then I bring up dnsmasq and tell it to use my configuration file. We enable IP forwarding to tell Kali to act like a router with sysctl. We allow our traffic through and enable NAT functionality with iptables. Finally, we fire up hostapd with our configuration file.
When a wireless client connects to this network, they will have access to the corporate network via eth0; to a MAC filter, traffic coming from that port will appear to be coming from a Cisco IP Phone:
With network access control, authentication is the name of the game. In our first attack scenario, we saw that the network verifies that a device is permitted by MAC address whitelisting. The principle is simple—a list of allowed devices is checked when a device joins the network. Many people, even outside of the field, are familiar with MAC filtering from the common implementation of this technique in SOHO wireless routers. However, you may be surprised at how often the VoIP phone masquerade will work in highly secured environments.
It's Network Security 101: MAC addresses are very easily faked, and networks will take your word for it when you claim to be a particular value. I've had clients detail, at length, the various features of their state-of-the-art NAC, only to look puzzled when I show them I had network access to their server environment by pretending to be a conference room phone. It's important to test for this bypass; not many clients are aware of simple threats.
We're now going to look at another attack that can fly surprisingly low under the radar: exploiting authentication communications in the initial restricted network. We'll be using Wireshark for quick and easy packet analysis in this section; more advanced Wireshark discussion will take place in Chapter 2, Sniffing and Spoofing.
Speaking of security mechanisms that even non-security folks will have some familiarity with, captive portals are a common network access control strategy. They're the walls you encounter when trying to get online in a hotel or an airplane; everything you try to access takes you to a specially configured login screen. You will receive credentials from an administrator, or you will submit a payment – either way, after you've authenticated, the captive portal will grant access via some means (a common one is SNMP management post-authentication).
I know what the hacker in you is saying: When the unauthenticated client tries to send an HTTP request, they get a 301 redirect to the captive portal authentication page, so it's really nothing more than a locally hosted web page. Therefore, it may be susceptible to ordinary web attacks. Well done, I couldn't have said it better. But don't fire up sslstrip just yet; would it surprise you to learn that unencrypted authentication is actually fairly common? We're going to take a look at an example: the captive portal to grant internet access to guests in my house. This isn't your run-of-the-mill captive portal functionality built in to an off-the-shelf home router; this is a pfSense firewall running on a dedicated server.
This is used in some enterprises, so trust me, you will run into something like this in your adventures as a pen tester.
What we see here is the captive portal presented to a user immediately upon joining the network. I wanted to have a little fun with it, so I wrote up the HTML myself (the bad cat pun is courtesy of my wife). However, the functionality is exactly the same as you'll see in companies that utilize this NAC method.
Let's get in the Kali driver's seat. We've already established a connection to this network, and we're immediately placed into the restricted zone. Fire up a Terminal and start Wireshark.
Not a lot is going on here, even with our card in promiscuous mode. This looks like we're dealing with a switched network, so traffic between our victim and the gateway is not broadcasted for us to see. But, take a closer look at the highlighted packet: it's coming from the gateway at 10.108.108.1 and going to 255.255.255.255, which is the broadcast address of the zero network (namely, the network we're on). We can see that it's a DHCP ACK packet – an acknowledgment of a DHCP request. So, our victim with an unknown IP address is joining the network, and will soon authenticate to the portal. Though the victim isn't the destination, we'll find the IP address assignment in the DHCP ACK packet:
Wireshark is kind enough to convert that hex into a human-friendly IP address: 10.108.108.36. We're on a switched LAN, so our victim's HTTP authentication is going directly to the gateway, right? Yes, it is, but the keyword here is LAN.
The lowest layer of the internet protocol suite is the link layer, which is the realm of adjacent hosts on a LAN segment. Link layer communication protocols don't leave the network via routers, so it's important to be aware of them and their weaknesses when you are attacking LANs. When you join a LAN, even a restricted one outside of the protected network, you're sharing that space with anything else on that segment: the captive portal host itself, other clients waiting to be authenticated, and in some cases, even with authenticated clients.
When our victim joined the LAN, it was assigned an IP address by DHCP. But, any device with a message for that IP address has to know the link layer hardware address associated with the destination IP. This layer-2 – layer-3 mapping is accomplished with Address Resolution Protocol (ARP). An ARP message informs the requester where (for instance, at which link layer address) a particular IP address is assigned. The clients on the network maintain a local table of ARP mappings. For example, on Windows, you can check the local ARP table with the arp -a command. The fun begins when we learn that these tables are updated by ARP messages without any kind of verification. If you're an ARP table and I tell you that the gateway IP address is mapped to 00:01:02:aa:ab:ac, you're going to just believe it and update accordingly. This opens up the possibility for poisoning the ARP table – feeding it bad information.
What we're going to do is feed the network bad ARP information, so that the gateway believes that the Kali attacker's MAC address is assigned the victim's IP address; meanwhile, we're also telling the network that the Kali attacker's MAC address is assigned the gateway IP address. The victim will send data meant for the gateway to me, and the gateway will send data meant for the victim to me. Of course, that would mean nothing is actually getting from the gateway to the victim and vice versa, so we'll need to enable packet forwarding so that the Kali machine will hand off the message to the actual destination. By the time the packet gets to where it was meant to go, we've processed it and sniffed it.
First, we enable packet forwarding with the following command:
# echo 1 > /proc/sys/net/ipv4/ip_forward
An alternative command is as follows:
# sysctl -w net.ipv4.ip_forward=1
arpspoof is a lovely tool for really fast and easy ARP poisoning attacks. Overall, I prefer Ettercap; however, I will be covering Ettercap later on, and it's always nice to be aware of the quick and dirty ways of doing things for when you're in a pinch. Ettercap is ideal for more sophisticated reconnaissance and attack, but with arpspoof, you can literally have an ARP man-in-the-middle attack running in a matter of seconds.
The -i flag is the interface; the -t flag is the target; and the -r flag tells arpspoof to poison both sides to make it bidirectional. (The older version didn't have the -r flag, so we had to set up two separate attacks.)
Here, we can see arpspoof in action, telling the network that the gateway and the victim are actually my Kali box. Meanwhile, the packets will be forwarded as received to the other side of the intercept. When it works properly (namely, your machine doesn't create a bottleneck), neither side will know the difference unless they are sniffing the network. When we check back with Wireshark, we can see what an ARP poisoning attack looks like.
We can see communication between the victim and the gateway, so now it's a matter of filtering for what you need. In our demonstration here, we're looking for an authentication to a web portal – likely a POST message. When I find it, I follow the conversation in Wireshark by right-clicking a packet and selecting Follow, and there are the victim's credentials in plain text:
We've seen how network access control systems can employ simple MAC address filtering and captive portal authentication to control network access. Now, suppose that you're coming away from the ARP poisoning attack just described, excited that you scored yourself some legitimate credentials. You try to log in with your Kali box and you're slapped down by a validation check that you hadn't foreseen. You have the correct username and password – how does the NAC know it isn't the legitimate user?
NAC vendors quickly figured out that it was a simple matter for anyone to spoof a MAC address, so some systems perform additional verification to match the hardware address to other characteristics of the system. Imagine the difference between authenticating someone by fingerprint alone and authenticating someone by fingerprint, clothing style, vocal patterns, and so on. The latter prevents simple spoof attacks. In this context, the NAC is checking that the MAC address matches other characteristics: manufacturer, operating system, and user agent are common checks. It turns out that the captive portal knows this Phil user you've just spoofed, and it was expecting an Apple iPad (common in the enterprise as an approved device). Let's review these three checks in detail.
There are two main parts to a MAC address: the first three octets are the Organizationally Unique Identifier (OUI), and the last three octets are Network Interface Controller-specific (NIC-specific). The OUI is important here because it uniquely identifies a manufacturer. The manufacturer will purchase an OUI from the IEEE Registration Authority and then hardcode it into their devices in-factory. This is not a secret – it's public information, encoded into all the devices a particular manufacturer makes. A simple Google search for Apple OUI helps us narrow it down, though you can also pull up the IEEE Registration Authority website directly. We quickly find out that 00:21:e9 belongs to Apple, so we can try to spoof a random NIC address with that (for example, 00:21:e9:d2:11:ac).
But again, vendors are already well aware of the fact that MAC addresses are not reliable for filtering, so they're likely going to look for more indicators.
Anyone who has dissected a packet off a network should be familiar with the concept of operating system fingerprinting. Essentially, operating systems have little nuances in how they construct packets to send over the network. These nuances are useful as signatures, giving us a good idea of the operating system that sent the packet. We're preparing to spoof the stack of a chosen OS as previously explained, so let's cover a tool in Kali that will come in handy for a variety of recon situations: Passive Operating system Fingerprinter (p0f).
Its power is in its simplicity: it watches for packets, matches signatures according to a signature database of known systems, and gives you the results. Of course, your network card has to be able to see the packets that are to be analyzed. We saw with our example that the restricted network is switched, so we can't see other traffic in a purely passive manner; we had to trick the network into routing traffic through our Kali machine. So, we'll do that again, except on a larger scale as we want to fingerprint a handful of clients on the network. Let's ARP spoof with Ettercap, a tool that should easily be in your handiest tools Top 10. Once Ettercap is running and doing its job, we'll fire up p0f and see what we find.
We're going to bring up Ettercap with the graphical interface featuring a very scary-looking network-sniffing spider:
# ettercap -G
Let's start sniffing, and then we'll configure our man-in-the-middle attack. Click Sniff in the menu at the top and choose Unified Sniffing. Unified sniffing means we're just sniffing from one network card; we aren't forwarding anything to another interface right now.
Now we tell Ettercap to find out who's on the network. Click Hosts | Scan for hosts. When the scan is complete, you can click Hosts again to bring up the host list. This tells us what Ettercap knows about who's on the network.
Now, we're doing something rather naughty; I've selected the gateway as Target 1 (by selecting it and then clicking Add to Target 1) and a handful of clients as Target 2. This means Ettercap is going to poison the network with ARP announcements for all of those hosts, and we'll soon be managing the traffic for all of those hosts.
Select Mitm | ARP poisoning. I like to select Sniff remote connections, though you don't have to for this particular scenario.
That's it. Click OK and now Ettercap will work its magic. Click View | Connections to see all the details on connections that Ettercap has seen so far.
Those of you who are familiar with Ettercap may know that the Profiles option in the View menu will allow us to fingerprint the OS of the targets, but, in keeping with presenting the tried-and-true, quick-and-dirty tool for our work, let's fire up p0f. The -o flag allows us to output to a file – trust me, you'll want to do this, especially for a spoofing attack of this magnitude:
# p0f -o poflog
p0f likes to show you some live data as it's collecting the juicy gossip. Here we can see that 192.168.108.22 is already fingerprinted as a Windows NT host by looking at a single SYN packet:
Ctrl + C closes p0f. Now, let's open up our (greppable) log file with nano:
Beautiful, isn't it? The interesting stuff is the raw signature at the end of each packet detail line, which is made up of colon-delimited fields in the following order:
Internet protocol version (for instance, 4 means IPv4).
Initial
time-to-live
(
TTL
). It would be weird if you saw anything other than 64, 128, or 255, but some OSes use different values; for example, you may see AIX hosts using 60, and legacy Windows (95 and 98) using 32.
IPv4 options length, which will usually be 0.
Maximum Segment Size
(
MSS
), which is not to be confused with MTU. It's the maximum size in bytes of a single TCP segment that the device can handle. The difference from MTU is that the TCP or IP header is not included in the MSS.
TCP receive window size, usually specified as a multiple of the MTU or MSS. p0f is nice enough to let us know; in this case, the value is the MSS
multiplied by
44.
Window scaling factor, if specified.
A comma-delimited ordering of the TCP options (if any are defined).
A field that the
readme
calls
quirks
: weird stuff in the TCP or IP headers that can help us narrow down the stack creating it. Check out the
readme
file to see what kind of options are displayed here; an example is
df
for the
don't fragment
flag set.
Why are we concerned with these options anyway? That's what the fingerprint database is for, isn't it? Of course, but part of the wild and wacky fun of this tool is the ability to customize your own signatures. You might see some funky stuff out there and it may be up to you playing with a quirky toy in your lab to make it easier to identify in the wild. However, of particular concern to the pen tester is the ability to craft packets that have these signatures to fool these NAC validation mechanisms. We'll be doing that in the next section, but for now, you have the information needed to research the stack you want to spoof.
Some budding hackers may be surprised to learn that browser user agent data is a consideration in network access control systems, but it is commonly employed as an additional validation of a client. Thankfully for us, spoofing the HTTP User-Agent field is easy. Back in my day, we used custom UA strings with cURL, but now you kids have fancy browsers that allow you to override the default.
Let's try to emulate an iPad. Sure, you can experiment with an actual iPad to capture the user agent data, but UA strings are kind of like MAC addresses in that they're easy to spoof, and detailed information is readily available online. So, I'll just search the web for iPad user agent data and go with the more common ones. As the software and hardware change over time, the UA string can change, as well. Keep that in mind if you think all iPads (or any device) are created equal.
In Kali, we open up Firefox ESR and navigate to about:config in the address bar. Firefox will politely warn you that this area isn't for noobs; go ahead and accept the warning. Now, search for useragent and you'll see the configuration preferences that reference the user agent:
Note that there isn't an override preference name with a string data type (so we can provide a useragent string). So, we have to create it. Right-click to create a new preference name and call it general.useragent.override.
The data type is a string, of course, and the value is the user agent data. Keep in mind, there isn't a handy builder that will take specific values and put together a nicely formatted UA string; you have to punch it in character by character, so check the data you're putting there for accuracy. You could pretend to be a refrigerator if you wanted to, but I'm not sure that helps us here:
I've just dumped in the User-Agent data for an iPad running iOS 9.3.2, opened a new tab, and verified what the web thinks I am:
The Website Goodies page is now convinced that my Kali box is actually a friendly iPad.