The Linux Filesystem Hierarchy
Everything in Linux is a file, and everything lives under one unified root. Windows uses drive letters (C:\, D:\); Linux has a single unified tree starting at /.
Core Directories & Architectural Roles
Navigating Linux with speed requires understanding exactly where configuration files, logs, volatile memory pointers, and binaries reside on disk:
ls, cat, grep, and bash itself.
iptables, fdisk, useradd).
passwd, shadow, sshd_config, and cron scheduling — attackers and defenders both live here.
/home/kalki).
/ itself).
/var/log). First place to inspect during forensics.
/dev/sda, /dev/null, /dev/urandom, USB interfaces).
/etc/passwd and /etc/shadow are the first files an attacker with a foothold enumerates — passwd reveals valid usernames, while shadow holds password hashes and must strictly remain root-readable only. A misconfigured permission on /etc/shadow guarantees immediate credential theft. Conversely, /var/log is the primary ground for threat hunters during incident triage.
You have just obtained a low-privilege shell on a Linux machine during a CTF or penetration test. Which two directories do you inspect first for configuration leaks or leftover artifacts, and why?
Reveal Solution
/tmp and /home: These directories are frequently world-writable or contain leftover installation scripts, private SSH keys (
id_rsa), backup archives, or developer notes forgotten by administrators. /var/log is also worth an immediate check for running services and access patterns.
What is the precise architectural distinction between / and /root?
Reveal Solution
/root (Root User Home): The dedicated home folder belonging specifically to the root superuser account, analogous to
/home/kalki for a normal user. They share a similar name but represent entirely different filesystem roles.
Users, Groups & Permissions
Every file and directory in Linux has an owner, an assigned group, and a permission mode string. Mastering this notation is mandatory — permission misconfigurations represent the single most common privilege escalation vector in Linux security.
Reading Permission Strings
Executing ls -la outputs permission strings broken down into four distinct segments:
-rwxr-xr-- 1 kalki security 4096 Sep 11 10:02 deploy.sh │└──┬──┘└──┬──┘└──┬──┘ │ │ │ └── Other: r-- (read only = 4) │ │ └───────── Group: r-x (read + execute = 5) │ └──────────────── Owner: rwx (read + write + execute = 7) └──────────────────── File Type: - = regular file, d = directory, l = symlink
Numeric (Octal) Permissions
Permissions are computed using binary weight additions (r=4, w=2, x=1):
| Octal Value | Binary / Symbolic | Meaning | Access Granted |
|---|---|---|---|
| 4 | r-- (100) | Read | View file contents or list directory entries |
| 2 | -w- (010) | Write | Modify file contents or create/delete files in directory |
| 1 | --x (001) | Execute | Run executable binary/script or traverse directory (cd) |
| 7 | rwx (111) | Full Access | Read + Write + Execute (4 + 2 + 1) |
chmod 754 deploy.sh 7 = Owner: rwx (4 + 2 + 1) -> Full control 5 = Group: r-x (4 + 0 + 1) -> Read and execute 4 = Other: r-- (4 + 0 + 0) -> Read-only
Key Permission Management Commands
| Command | Purpose & Security Context |
|---|---|
| chmod 640 file.txt | Set file mode to owner (rw-), group (r--), others (---). Can also use symbolic: chmod u+x,g-w file |
| chown user:group file | Change ownership and primary group association of a target file or folder |
| sudo command | Execute a single command with root privileges (logged into /var/log/auth.log) |
| su - username | Switch to another user account and initialize their full interactive login shell environment |
| id | Print current user UID, primary GID, and all secondary group memberships (e.g., sudo, docker) |
| whoami | Print current effective username executing commands in the current shell session |
SUID, SGID & Sticky Bit — The Exploitation Angle
A binary with the SUID (Set User ID) bit enabled executes with the privileges of the file owner rather than the user invoking it. For example, /usr/bin/passwd is owned by root and has SUID set (-rwsr-xr-x) so that normal users can update /etc/shadow when changing their password.
-rwsr-xr-x 1 root root /usr/bin/passwd ▲ └── s = SUID bit set (replaces 'x' in the owner's execute field)
find / -perm -4000 -type f 2>/dev/null
Automated enumeration engines like LinPEAS and linux-smart-enumeration run this check, but every security engineer must know the manual syntax cold.
What numeric chmod octal value grants the file owner full read/write/execute, the group read and execute only, and others zero access?
Reveal Solution
Group: r-x = 4 + 0 + 1 = 5
Others: --- = 0 + 0 + 0 = 0
Command:
chmod 750 file
During enumeration you find a custom script with permissions -rwsr-xr-x root root backup.sh. What is suspicious about this configuration and what are your next investigative steps?
Reveal Solution
s) is set on an executable owned by root, meaning it runs with root permissions regardless of which unprivileged user executes it.Next Steps: Read the script contents. If it calls system binaries (e.g.
tar or cp) without specifying absolute paths (/bin/tar), you can manipulate your current user's $PATH variable to hijack binary execution and spawn a root shell (/bin/sh).
Explain how find / -perm -4000 -type f 2>/dev/null functions piece-by-piece.
Reveal Solution
/), traversing the entire storage tree.-perm -4000: Match files where at least the SUID bit (
4000 octal mask) is active.-type f: Restrict results exclusively to regular files (filtering out directories and device nodes).
2>/dev/null: Redirect standard error (FD 2 — suppressing permission-denied noise from unreadable directories) into the null blackhole.
Result: A clean, actionable inventory of every SUID executable on the target host.
Command Line Essentials & Pipelines
grep, awk, sed, find, ps, and ss are not optional utilities — they represent the foundation of log parsing, artifact triage, and live forensic investigation.
Core Tooling Matrix (One-Click Copy)
Search file case-insensitively (-i) for error signatures.
Recursive search (-r) with line numbers (-n) to hunt for leaked secrets.
Print the 1st whitespace-separated column of each input line.
Custom delimiter (-F:) — cleanly extract all local system usernames.
Stream editor find-and-replace text globally (g) per line.
Search the entire filesystem for specific configuration file extensions.
Forensic hunt: locate files modified within the last 24 hours.
Snapshot of every active running process across all users.
List all listening TCP/UDP sockets with owning process IDs.
Active network sockets and connections on legacy Linux distributions.
Pipe chaining — extract username column using cut delimiter.
Real-time live monitoring of authentication and sudo event logs.
Chaining Commands — The Security Engineer's Weapon
Individual tools become exponentially more effective when chained together with UNIX pipes (|). This enables rapid log parsing and intrusion detection directly in the terminal:
cat /var/log/auth.log | grep "Failed password" | awk '{print $11}' | sort | uniq -c | sort -nr
cat /var/log/auth.log): Streams authentication log records to stdout.grep "Failed password"): Filters exclusively to failed login attempt events.awk '{print $11}'): Extracts the 11th whitespace-delimited column containing the attacker's source IP address.sort | uniq -c): Sorts IP records and tallies the total occurrences per unique IP.sort -nr): Sorts numerically in descending order, producing a ranked scoreboard of IP addresses brute-forcing SSH.Write a single command to find every regular file under /home that is world-writable.
Reveal Solution
find /home -perm -o+w -type f 2>/dev/nullMechanism:
-perm -o+w checks that the "other" write bit is set. World-writable files in user directories allow attackers to plant malicious scripts or modify trusted execution paths.
You have an Apache/Nginx web server access.log and need to output the top 5 most active IP addresses by request count. Construct the command pipeline.
Reveal Solution
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -5Breakdown: Extract client IP (column 1 in standard combined log format) → sort IPs so duplicates are adjacent → count occurrences with
uniq -c → sort count descending → slice top 5 records.
What is the difference between grep "error" sys.log and grep -v "error" sys.log?
Reveal Solution
grep "error" outputs only lines containing the string "error".Inverted Match (-v):
grep -v "error" inverts matching, outputting every line that does not contain "error". Invaluable for filtering out repetitive, known-benign noise when triaging messy logs.
Processes, Services & Scheduling
Knowing what is actively executing, what initializes at boot, and what runs on schedule is critical for both offensive persistence and defensive anomaly detection.
Process & Service Control Commands
| Command | Purpose & Security Usage |
|---|---|
| ps aux | List all active processes with user owner, PID, CPU/RAM usage, and command arguments |
| top / htop | Interactive real-time process manager; spot CPU spikes from cryptominers or rogue tasks |
| kill -9 <PID> | Send SIGKILL signal to immediately terminate an unresponsive or malicious process |
| systemctl status sshd | Query status, active state, and recent runtime log snippets for a systemd daemon |
| systemctl list-units --type=service | Audit all loaded system services to discover unauthorized background daemons |
| crontab -l | Display the scheduled cron jobs registered to the currently logged-in user |
| cat /etc/crontab | Inspect system-wide scheduled tasks and their configured execution user accounts |
Cron Scheduling Syntax
* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └── Day of Week (0 - 6, where Sunday = 0 or 7)
│ │ │ └───── Month of Year (1 - 12)
│ │ └──────── Day of Month (1 - 31)
│ └─────────── Hour of Day (0 - 23 in 24h format)
└────────────── Minute of Hour (0 - 59)
Example: 0 2 * * * /opt/backup.sh -> Runs every single day at 02:00 AM sharp
/etc/cron* and each user's crontab is standard procedure. On the offensive side, if a root-owned cron job executes a script that is world-writable, any unprivileged user can modify that script to achieve root execution within minutes.
You suspect a compromised Linux server has an adversary persistence task configured. Where do you audit beyond the current user's crontab -l?
Reveal Solution
1. Check all user crontabs:
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done2. Audit system cron directories:
/etc/crontab, /etc/cron.d/, /etc/cron.daily/, /etc/cron.hourly/3. Audit systemd timers:
systemctl list-timers --all4. Inspect startup hooks:
/etc/rc.local and shell profile scripts (/etc/profile, ~/.bashrc).
A root-owned cron job runs every minute: * * * * * /opt/scripts/cleanup.sh. The permissions on cleanup.sh are -rwxrwxrwx (world-writable). How do you escalate privileges?
Reveal Solution
cleanup.sh:echo 'chmod +s /bin/bash' >> /opt/scripts/cleanup.shWhen cron executes
cleanup.sh as root on the next minute mark, /bin/bash receives the SUID bit. You then execute /bin/bash -p to drop into a root shell.
Bash Scripting for Security Engineers
You don't need to write monolithic software in Bash. You need enough scripting fluency to automate reconnaissance, batch-parse network artifacts, and chain disparate security tools together.
The Core Scripting Building Blocks
#!/bin/bash # 1. Variables (no spaces around '=') target="192.168.1.0/24" # 2. File Conditionals if [ -f "/etc/shadow" ]; then echo "[+] /etc/shadow is accessible" fi # 3. For Loop over a Sequence for ip in 10 20 30 40 50; do ping -c 1 -W 1 "192.168.1.$ip" > /dev/null && echo "Host $ip is UP" done # 4. While Loop reading line-by-line while read -r domain; do echo "Resolving: $domain" host "$domain" done < targets.txt # 5. Functions scan_host() { echo "Running Nmap on: $1" nmap -sV -p 22,80,443 "$1" } scan_host "192.168.1.1"
A Real-World Recon Script (quick_recon.sh)
A fast ping-sweep automation script written in under 5 minutes to discover live hosts across an entire subnet:
#!/bin/bash # quick_recon.sh — ping-sweep a /24 subnet and report live hosts subnet="192.168.1" echo "[*] Starting sweep on subnet: $subnet.0/24" for i in $(seq 1 254); do ip="$subnet.$i" if ping -c 1 -W 1 "$ip" &> /dev/null; then echo "[LIVE HOST] -> $ip" fi done echo "[*] Subnet sweep completed."
Write a one-line Bash loop that iterates through a list of common usernames (admin, root, guest, test) and echoes "Testing user: <username>".
Reveal Solution
for user in admin root guest test; do echo "Testing user: $user"; doneWordlist Pattern:
while read -r user; do echo "Testing user: $user"; done < users.txt
What is dangerously flawed about this cleanup script line: rm -rf $dir/*?
Reveal Solution
$dir is unquoted and unvalidated. If $dir is accidentally unset or empty, the command expands to rm -rf /*, destroying the entire root filesystem.Safe Pattern: Always double-quote variables (
"$dir") and validate they are non-empty before executing destructive operations: [ -n "$dir" ] && rm -rf "${dir:?}"/*.
Kali Linux & The Offensive Arsenal
Kali is a Debian-derived distribution maintained by Offensive Security, pre-configured with hundreds of specialized tools across every phase of an engagement.
Security Tool Categories & Standard Weapons
| Category | Pre-Installed Core Tools | Primary Use Case |
|---|---|---|
| Reconnaissance | nmap, theHarvester, recon-ng, whois | Port discovery, OS fingerprinting, OSINT domain gathering |
| Vulnerability Analysis | nikto, openvas, cve-search | Automated web server configuration and flaw scanning |
| Web Application Testing | burpsuite, sqlmap, gobuster, ffuf | HTTP proxy interception, SQL injection, directory fuzzing |
| Password Attacks | hydra, john, hashcat, wordlists | Network service brute force and offline hash cracking |
| Exploitation | metasploit-framework, searchsploit | Weaponized exploit delivery and public exploit archives |
| Sniffing & Spoofing | wireshark, tcpdump, bettercap, mitmproxy | Packet inspection, ARP poisoning, credential interception |
| Post-Exploitation | mimikatz (via wine), linpeas, evil-winrm | Credential harvesting, privilege escalation enumeration |
--help) before running scans, and never target systems without explicit, written authorization.
Fresh Kali Installation Hardening Checklist
sudo apt update && sudo apt full-upgrade -y (Kali rolling release updates frequently).Why is running Kali logged in as root for daily use considered poor practice, even though historical penetration testing tools often expected it?
Reveal Solution
Industry Standard: Modern Kali defaults to a standard non-root user (
kali) to reinforce the principle of least privilege, which you must rigorously maintain when operating in client environments.
SSH — Encrypted Remote Access & Pivoting
SSH (Secure Shell) is the industry standard for remote administration, lab connectivity, CTF challenges, and multi-hop network pivoting.
Key SSH Commands & Tunneling Flags
| Command | Operation & Practical Purpose |
|---|---|
| ssh user@host | Initiate standard interactive encrypted shell using password or default key |
| ssh -i key.pem user@host | Authenticate explicitly using a specific private key file (e.g. AWS/CTF key) |
| ssh-keygen -t ed25519 | Generate high-entropy elliptic-curve keypair (modern, secure standard) |
| ssh-copy-id user@host | Append your public key into the remote host's ~/.ssh/authorized_keys |
| scp file.txt user@host:/tmp/ | Securely transfer files between local and remote endpoints over SSH |
| ssh -L 8080:localhost:80 user@host | Local Port Forward: Tunnel remote host's port 80 to your local machine at port 8080 |
| ssh -D 1080 user@host | Dynamic SOCKS Proxy: Route arbitrary browser/tool traffic through the remote pivot host |
-L, -R, -D) allow you to pivot through a compromised machine located on a perimeter network. Once SSH access is obtained, you can route scanning and exploitation traffic directly into internal subnets that are invisible to the public internet.
You have SSH access to a jump box (jumpbox) that can reach an internal admin panel running on internal-host:8443. Your own machine cannot reach that internal host directly. Write the SSH port forwarding command.
Reveal Solution
ssh -L 9000:internal-host:8443 user@jumpboxMechanism: Visiting
https://localhost:9000 in your local browser now tunnels directly through the jump box to internal-host:8443.
Why is Ed25519 public-key SSH authentication strictly superior to password-based authentication?
Reveal Solution
Zero Credential Exposure: The private key never travels across the wire during authentication (only a cryptographic signature is transmitted). Password auth is vulnerable to network sniffing, keylogging, and credential stuffing.
Setting Up Your Home Lab
You need an isolated, virtualized playground to test exploits and capture traffic without ever touching production systems or violating legal boundaries.
5-Step Home Lab Architecture Blueprint
Virtual Network Modes Comparison
| Adapter Mode | How Traffic Routes | Lab Suitability |
|---|---|---|
| NAT | VM accesses internet via host IP; isolated from external inbound LAN traffic | Good for downloading package updates; not for VM-to-VM testing |
| Bridged | VM appears as a dedicated physical host on your actual home router subnet | Avoid for attacks — exposes exploit traffic to your real LAN |
| Host-Only | VMs can communicate with each other and the host OS, but have no outside internet route | Recommended — ideal isolated testing network |
| Internal Network | VMs communicate exclusively among themselves; completely isolated even from host OS | Maximum Security — pure malware / attack sandbox |
You accidentally set your Kali VM's network adapter to Bridged instead of Host-Only while practicing an ARP spoofing attack. What is the immediate danger?
Reveal Solution
Why is taking a hypervisor snapshot before practicing exploit chains considered a critical practice habit?
Reveal Solution
7-Day Linux Mastery Checklist
Check these off as you complete your daily drills. Your progress is automatically saved in your browser's local storage.