Copied to clipboard
9
Sections, filesystem hierarchy to virtualized home lab
20+
Security-critical commands you must know cold
16
Worked practice problems with step-by-step solutions
1
Week structured roadmap to working fluency
SEC // 01

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:

/ Root: The absolute top of the entire filesystem tree. Every single directory, disk mount, and device branches from here.
/bin, /usr/bin User Binaries: Essential command binaries for standard users — ls, cat, grep, and bash itself.
/sbin, /usr/sbin System Binaries: Administration and maintenance executables — usually requires root authority (iptables, fdisk, useradd).
/etc System Configuration: Host-wide config files. Contains passwd, shadow, sshd_config, and cron scheduling — attackers and defenders both live here.
/home User Home Spaces: Personal storage directories per non-root user account (e.g. /home/kalki).
/root Root Home: The personal home directory belonging to the root superuser (distinct from / itself).
/var Variable Data: Dynamic spool files, mailboxes, and incident response event logs (/var/log). First place to inspect during forensics.
/tmp Temporary Scratchpad: World-writable directory cleared on system reboot. Common staging ground for droppers and payload compilation.
/proc Virtual Process Filesystem: Live memory window into active process state and kernel internals. Does not exist on physical disk storage.
/dev Device Nodes: Hardware handles and pseudo-devices (/dev/sda, /dev/null, /dev/urandom, USB interfaces).
/opt Optional Add-ons: Third-party software packages and custom offensive tool compilations (e.g., BloodHound, BurpSuite).
Why this matters for security /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.
Practice Drill 01.1 · Foothold Enumeration

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
/etc: Inspect for configuration files that might leak plaintext credentials, exposed database connection strings, or misconfigured cron job schedules you can abuse.
/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.
Practice Drill 01.2 · Root Disambiguation

What is the precise architectural distinction between / and /root?

Reveal Solution
/ (Root Directory): The root of the entire unified filesystem — every single folder, mount, and device exists underneath this entry point.
/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.
SEC // 02

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:

Terminal // Anatomy of a Linux Permission String
-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
Owner (User)
rwx (7)
Group
r-x (5)
Others (World)
r-- (4)

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)
Bash // Octal Calculation Breakdown
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.

Terminal // SUID Bit Representation
-rwsr-xr-x  1 root root  /usr/bin/passwd
   ▲
   └── s = SUID bit set (replaces 'x' in the owner's execute field)
Security Critical PrivEsc Discovering a custom or vulnerable root-owned binary with the SUID bit set is one of the most reliable Linux privilege escalation vectors. The universal audit one-liner to hunt for all SUID binaries across the filesystem is:

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.
Practice Drill 02.1 · Octal Calculation

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
Owner: rwx = 4 + 2 + 1 = 7
Group: r-x = 4 + 0 + 1 = 5
Others: --- = 0 + 0 + 0 = 0
Command: chmod 750 file
Practice Drill 02.2 · SUID Script Vulnerability

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
Vulnerability: The SUID bit (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).
Practice Drill 02.3 · Find Anatomy

Explain how find / -perm -4000 -type f 2>/dev/null functions piece-by-piece.

Reveal Solution
find /: Initiate the search starting from root (/), 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.
SEC // 03

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)

grep -i "error" access.log

Search file case-insensitively (-i) for error signatures.

grep -rn "password" /etc/

Recursive search (-r) with line numbers (-n) to hunt for leaked secrets.

awk '{print $1}' file.log

Print the 1st whitespace-separated column of each input line.

awk -F: '{print $1}' /etc/passwd

Custom delimiter (-F:) — cleanly extract all local system usernames.

sed 's/foo/bar/g' file.txt

Stream editor find-and-replace text globally (g) per line.

find / -name "*.conf" 2>/dev/null

Search the entire filesystem for specific configuration file extensions.

find / -mtime -1 2>/dev/null

Forensic hunt: locate files modified within the last 24 hours.

ps aux

Snapshot of every active running process across all users.

ss -tulnp

List all listening TCP/UDP sockets with owning process IDs.

netstat -antp

Active network sockets and connections on legacy Linux distributions.

cat /etc/passwd | cut -d: -f1

Pipe chaining — extract username column using cut delimiter.

tail -f /var/log/auth.log

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:

Bash // SSH Brute-Force Detection Pipeline
cat /var/log/auth.log | grep "Failed password" | awk '{print $11}' | sort | uniq -c | sort -nr
  • Step 1 (cat /var/log/auth.log): Streams authentication log records to stdout.
  • Step 2 (grep "Failed password"): Filters exclusively to failed login attempt events.
  • Step 3 (awk '{print $11}'): Extracts the 11th whitespace-delimited column containing the attacker's source IP address.
  • Step 4 (sort | uniq -c): Sorts IP records and tallies the total occurrences per unique IP.
  • Step 5 (sort -nr): Sorts numerically in descending order, producing a ranked scoreboard of IP addresses brute-forcing SSH.
  • Practice Drill 03.1 · World-Writable File Hunting

    Write a single command to find every regular file under /home that is world-writable.

    Reveal Solution
    Command: find /home -perm -o+w -type f 2>/dev/null
    Mechanism: -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.
    Practice Drill 03.2 · Web Traffic Log Analysis

    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
    Command: awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -5
    Breakdown: 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.
    Practice Drill 03.3 · Inverted Pattern Matching

    What is the difference between grep "error" sys.log and grep -v "error" sys.log?

    Reveal Solution
    Standard Match: 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.
    SEC // 04

    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

    Diagram // 5-Field Cron Scheduling Expression
    *  *  *  *  *  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
    Why this matters for persistence Cron jobs, systemd timers, and init scripts are the top persistence mechanisms used by attackers — malware registers cron entries to retain access after system restarts. During incident response, checking /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.
    Practice Drill 04.1 · Persistence Audit

    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
    Comprehensive Check:
    1. Check all user crontabs: for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done
    2. Audit system cron directories: /etc/crontab, /etc/cron.d/, /etc/cron.daily/, /etc/cron.hourly/
    3. Audit systemd timers: systemctl list-timers --all
    4. Inspect startup hooks: /etc/rc.local and shell profile scripts (/etc/profile, ~/.bashrc).
    Practice Drill 04.2 · Writable Cron PrivEsc

    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
    Exploitation: Append a reverse shell or privileged command into cleanup.sh:
    echo 'chmod +s /bin/bash' >> /opt/scripts/cleanup.sh
    When 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.
    SEC // 05

    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

    Bash // Variables, Conditionals, Loops & Functions
    #!/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:

    Bash // quick_recon.sh — Fast Subnet Ping Sweep
    #!/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."
    Practice Drill 05.1 · Username Loop

    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
    One-Liner: for user in admin root guest test; do echo "Testing user: $user"; done
    Wordlist Pattern: while read -r user; do echo "Testing user: $user"; done < users.txt
    Practice Drill 05.2 · Script Bug Vulnerability

    What is dangerously flawed about this cleanup script line: rm -rf $dir/*?

    Reveal Solution
    Flaw: The variable $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:?}"/*.
    SEC // 06

    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
    Rule of engagement Kali is a framework, not a magic button. Knowing a tool exists is meaningless unless you understand the protocol mechanics beneath it. Always inspect man pages and help flags (--help) before running scans, and never target systems without explicit, written authorization.

    Fresh Kali Installation Hardening Checklist

  • 1. Update Repositories: Run sudo apt update && sudo apt full-upgrade -y (Kali rolling release updates frequently).
  • 2. Change Default Credentials: Immediately change default passwords if using a pre-packaged VM image.
  • 3. Configure Non-Root User: Use a dedicated user account for daily testing rather than operating as root.
  • 4. Install Virtualization Guest Tools: Ensure VirtualBox Guest Additions / VMware Tools are active for smooth display scaling and clipboard sync.
  • 5. Create Clean VM Snapshot: Take a baseline snapshot before installing custom tools so you can revert instantly when experiments break packages.
  • Practice Drill 06.1 · Least Privilege Habits

    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
    Safety & Blast Radius: Running as root removes the operating system's permission safety net. A syntax typo in a destructive command or executing an untrusted payload from the web immediately gains total system compromise.
    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.
    SEC // 07

    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
    Why this matters for pivoting SSH tunneling flags (-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.
    Practice Drill 07.1 · Local Port Forwarding

    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
    Command: ssh -L 9000:internal-host:8443 user@jumpbox
    Mechanism: Visiting https://localhost:9000 in your local browser now tunnels directly through the jump box to internal-host:8443.
    Practice Drill 07.2 · Key Authentication Security

    Why is Ed25519 public-key SSH authentication strictly superior to password-based authentication?

    Reveal Solution
    Entropy: Cryptographic keys have massive entropy and are practically immune to offline brute-force attacks.
    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.
    SEC // 08

    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

  • 1. Hypervisor Selection: Install VirtualBox (open-source) or VMware Workstation Player / Fusion.
  • 2. Deploy Target & Attacker VMs: Download a Kali Linux VM (attacker) and a vulnerable target VM (Metasploitable2, DVWA, or VulnHub image).
  • 3. Network Isolation (Host-Only): Configure both VM network adapters to Host-Only or Internal Network mode — never Bridged.
  • 4. Connectivity Verification: Verify that the attacker and target VMs can ping each other, but cannot communicate with your home network devices or the internet.
  • 5. Baseline Snapshots: Take clean VM snapshots before launching attacks so you can roll back corrupt services in seconds.
  • 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
    Ethics & Legal Boundaries Only attack machines you own or are explicitly authorized to test in writing (e.g. TryHackMe, HackTheBox, or your local isolated VMs). Executing port scans or exploit payloads against unauthorized external infrastructure is a violation of computer fraud laws in almost every jurisdiction worldwide.
    Practice Drill 08.1 · Network Adapter Misconfiguration

    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
    Danger: Bridged mode connects the VM directly to your physical home or office network. ARP spoofing traffic will poison the ARP tables of real household or company devices (smart TVs, work laptops, gateway router), disrupting legitimate traffic and potentially violating organizational policy or law.
    Practice Drill 08.2 · Snapshot Utility

    Why is taking a hypervisor snapshot before practicing exploit chains considered a critical practice habit?

    Reveal Solution
    Resilience: Exploits frequently crash system services, corrupt database tables, or lock out user accounts. A snapshot allows you to restore the virtual machine to a clean, working state in under 5 seconds without having to reinstall the operating system.
    SEC // 09

    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.

    Phase 02 Completion Progress 0 of 12 Completed (0%)

    Recommended Platforms for Continued Practice

  • OverTheWire: Bandit: The gold-standard interactive wargame teaching Linux command line proficiency through 30+ progressively difficult SSH levels.
  • TryHackMe "Linux Fundamentals": Guided 3-part room series walking through commands, file permissions, and process management.
  • LinPEAS & linux-smart-enumeration: Run these privilege escalation scripts on your lab boxes after performing manual enumeration to audit what you missed.
  • Next in Roadmap

    Phase 03 · Windows Architecture & PowerShell

    NTFS permissions, Registry forensics, SAM/LSASS process security, and defensive/offensive PowerShell scripting.

    Explore 10-Phase Pipeline