Week 3: Linux for Hackers
MITRE ATT&CK: Tactic — TA0002 (Execution), TA0003 (Persistence), Technique — T1059 (Command and Scripting Interpreter)
Real-World Attack Scenario: The Equifax Linux Servers
In the 2017 Equifax breach, attackers moved laterally from Windows systems to Linux-based web servers:
- Initial Access via Struts: Exploited CVE-2017-5638 on Apache Struts (Java) running on Linux
- Initial Shell: Received command execution as the Tomcat user (low-privilege)
- Linux Enumeration: Ran enumeration commands to understand the environment:bash
uname -a # Kernel version for exploit targeting cat /etc/passwd # User enumeration ls -la /home/ # Finding other users sudo -l # What can sudo do without password - Privilege Escalation: Exploited misconfigured SUID binaries or kernel vulnerability
- Persistence: Added cron job for recurring access:bash
echo "*/5 * * * * root /tmp/.hidden/backdoor.sh" >> /etc/crontab - Lateral Movement: Used Linux server as pivot to access internal databases
Why this week matters: TheEquifax attackers succeeded partly because their Linux servers had unpatched vulnerabilities, world-writable cron scripts, and SUID binaries with known exploits. Understanding Linux security misconfigs is essential for both offense and defense.
Objectives
- Master Linux command line for security work
- Understand file permissions, processes, and services
- Write bash scripts for automation
- Learn system administration for security testing
File System Hierarchy
/ — Root (top of tree)
/bin — Essential user binaries (ls, cp, mv, cat)
/sbin — System binaries (ifconfig, fdisk, iptables)
/etc — Configuration files (system-wide)
/home — User home directories
/root — Root user's home (NOT /home/root)
/var — Variable data (logs, spools, tmp)
/tmp — Temporary files (world-writable, cleared on reboot)
/opt — Optional/third-party software
/proc — Virtual filesystem (kernel + process info)
/sys — Virtual filesystem (hardware, kernel modules)
/usr — User programs and libraries
/boot — Boot loader, kernel images
/dev — Device files (hdd, tty, null, zero, random)Critical security files:
/etc/passwd— user database (readable by all, a design flaw)/etc/shadow— hashed passwords (root only)/etc/sudoers— sudo permissions/etc/shadow— actual password hashes/var/log/— all system and application logs
Essential Commands
File Operations
bash
# Navigation
pwd # Print working directory
cd /path/to/dir # Change directory
ls -la # List all files with details
ls -lah # Human-readable sizes
ls -lt # Sort by modification time
ls -lSr # Sort by size, smallest first
# File details
file filename # Determine file type
stat filename # Detailed metadata
wc -l file # Line count
# Create/read/write
touch newfile
echo "text" > file # Overwrite
echo "text" >> file # Append
cat file # Display all
less file # Paginated view
head -n 20 file # First 20 lines
tail -n 20 file # Last 20 lines
tail -f /var/log/syslog # Follow log in real-time
# Copy/move/delete
cp source dest
cp -r source/ dest/
mv oldname newname
rm filename
rm -rf directory/ # Force recursive delete
# Find
find / -name filename 2>/dev/null
find / -perm -4000 # Find SUID files
find / -user username
find / -mtime -7 # Modified in last 7 days
find / -size +100M # Files > 100MBText Manipulation
bash
# grep - search patterns
grep "pattern" file
grep -r "pattern" directory/
grep -i "pattern" file # Case insensitive
grep -n "pattern" file # Show line numbers
grep -E "regex" file # Extended regex
grep -v "pattern" file # Invert match (NOT)
grep -o "pattern" file # Only matching part
# cut - extract columns
cut -d: -f1 /etc/passwd # First field, colon-delimited
cut -d' ' -f1,3 file
# awk - pattern scanning
awk '{print $1}' file # First column
awk -F: '{print $1,$7}' /etc/passwd
awk '/pattern/ {print $0}' file
# sed - stream editor
sed 's/old/new/g' file # Replace all
sed -n '10,20p' file # Lines 10-20
sed -i 's/old/new/g' file # In-place edit
# sort and uniq
sort file | uniq # Unique lines
sort file | uniq -c # Count occurrences
sort -t: -k3 -n /etc/passwd # Sort by numeric UID
# xargs - build commands
find . -name "*.txt" | xargs rm
echo "a b c" | xargs -n1 echoPermissions (CRITICAL)
Symbolic: u=rwx, g=rx, o=r
Numeric: 755 = rwxr-xr-x
644 = rw-r--r--
600 = rw-------
4755 = SUID (run as owner, regardless of user)
2755 = SGID (run as group)
4750 = SUID + SGID
Permission bits:
r = 4 (read)
w = 2 (write)
x = 1 (execute)
u = user (owner)
g = group
o = others
a = allbash
# Change permissions
chmod 755 file # Numeric
chmod u+x file # Add execute for owner
chmod go-w file # Remove write from group/others
chmod +x file # Add execute for all
# Change owner/group
chown user:group file
chown -R user:group directory/
# Special bits
chmod u+s file # SUID
chmod g+s directory # SGID
chmod +t /tmp # Sticky bit (only owner can delete)
# Find permission issues
find / -perm -4000 2>/dev/null # SUID files
find / -perm -o+w -type d 2>/dev/null # World-writable dirsProcess Management
bash
# View processes
ps aux # All processes, detailed
ps -ef # Full format
ps aux | grep nginx
pstree # Tree view
# Real-time
top # Interactive process viewer
htop # Enhanced (if installed)
iotop # I/O by process
nethogs # Bandwidth by process
# Process control
kill <PID> # Terminate gracefully
kill -9 <PID> # Force kill
kill -SIGTERM <PID>
pkill processname # Kill by name
killall processname
# Background/foreground
./script.sh & # Run in background
jobs # List background jobs
fg %1 # Bring job 1 to foreground
Ctrl+Z # Suspend current job
bg # Resume in background
# Start/stop services
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl status nginx
systemctl enable nginx # Start at bootNetworking Commands
bash
# Interface info
ip addr show
ip link set eth0 up/down
ip addr add 192.168.1.100/24 dev eth0
# Routing
ip route show
ip route add default via 192.168.1.1
ip route add 10.0.0.0/24 via 192.168.1.1
# Connections
ss -tunap # All connections (TCP/UDP/RAW/PROC)
netstat -tunap # Older alternative
ss -tunap | grep :80
# DNS
/etc/resolv.conf
host example.com
dig example.com
# Edit hosts file
/etc/hosts
127.0.0.1 localhost
192.168.1.100 target.localPackage Management
bash
# Debian/Ubuntu
apt update # Refresh package lists
apt upgrade # Upgrade all packages
apt install package # Install
apt remove package # Remove
apt search keyword # Search packages
apt list --installed # List installed
# Kali-specific
apt install kali-tools-top10 # Top 10 tools
# Python packages
pip install package
pip install -r requirements.txt
# Old SysV init
service nginx startShell Scripting
Basic Script Structure
bash
#!/bin/bash
# Comments start with #
# Variables (NO spaces around =)
NAME="value"
NUM=42
OUTPUT=$(command) # Command substitution
FILES=$(ls -1)
# Special variables
$0 # Script name
$1 # First argument
$# # Number of arguments
$@ # All arguments
$$ # Process ID
$? # Exit status (0 = success)
# Arrays
ARRAY=(one two three)
${ARRAY[0]}
${ARRAY[@]} # All elements
# Conditionals
if [ "$VAR" == "value" ]; then
echo "matched"
elif [ "$VAR" == "other" ]; then
echo "other"
else
echo "default"
fi
# File tests
if [ -f "/path/to/file" ]; then # Exists and is file
if [ -d "/path/to/dir" ]; then # Exists and is directory
if [ -r "/path/to/file" ]; then # Readable
if [ -w "/path/to/file" ]; then # Writable
if [ -x "/path/to/file" ]; then # Executable
if [ -z "$VAR" ]; then # Empty
if [ -n "$VAR" ]; then # Not empty
# Loops
for i in {1..10}; do
echo "Number $i"
done
for file in *.txt; do
echo "Processing $file"
done
while read line; do
echo "$line"
done < file.txt
# Functions
function_name() {
local arg1="$1" # Local variable
echo "$arg1"
return 0 # Exit code
}
# Case statement
case "$VAR" in
value1)
echo "one"
;;
value2)
echo "two"
;;
*)
echo "default"
;;
esacPractical Hacking Scripts
Port Scanner Bash Script
bash
#!/bin/bash
# Simple TCP port scanner
if [ -z "$1" ]; then
echo "Usage: $0 <target_ip> [start_port] [end_port]"
exit 1
fi
TARGET=$1
START=${2:-1}
END=${3:-1024}
echo "Scanning $TARGET ports $START-$END..."
for PORT in $(seq $START $END); do
(echo >/dev/tcp/$TARGET/$PORT) 2>/dev/null && echo "Port $PORT is OPEN"
doneFast Discovery Scan
bash
#!/bin/bash
# Quick host discovery on a subnet
SUBNET="$1"
if [ -z "$SUBNET" ]; then
echo "Usage: $0 <subnet (e.g., 10.0.0.)>"
exit 1
fi
for i in {1..254}; do
IP="${SUBNET}${i}"
(ping -c1 -W1 $IP >/dev/null 2>&1) && echo "$IP is UP" &
done
wait
echo "Scan complete"System Administration Essentials
User Management
bash
# Add/remove users
useradd -m -s /bin/bash username
userdel -r username
passwd username
# Modify users
usermod -aG sudo username # Add to sudo group
usermod -e 2025-12-31 username # Set account expiry
# Sudo access
visudo # Edit sudoers safely
username ALL=(ALL:ALL) ALL # Full sudo
# Groups
groups username
groupadd groupname
usermod -g groupname usernameService Management
bash
# systemd (modern)
systemctl list-units --type=service --state=running
systemctl status nginx
systemctl start|stop|restart nginx
systemctl enable|disable nginx # Boot start
journalctl -u nginx -f # View logs
# Legacy (SysV)
service nginx status
update-rc.d nginx defaultsLog Analysis
bash
# System logs
/var/log/syslog # Debian/Ubuntu general
/var/log/messages # RHEL/CentOS general
/var/log/auth.log # Authentication (Debian)
/var/log/secure # Authentication (RHEL)
/var/log/nginx/access.log
/var/log/nginx/error.log
# Real-time monitoring
tail -f /var/log/auth.log
tail -f /var/log/syslog
# Search logs
grep "Failed password" /var/log/auth.log
grep "error" /var/log/syslog | tail -50
# Users last logged in
last
lastb # Failed login attempts
who
w # Who is logged in and what doingScheduled Tasks (Cron)
bash
# Cron syntax
# * * * * * command
# │ │ │ │ │
# │ │ │ │ └─── Day of week (0-7, 0/7 = Sunday)
# │ │ │ └───── Month (1-12)
# │ │ └─────── Day of month (1-31)
# │ └───────── Hour (0-23)
# └─────────── Minute (0-59)
# Examples
0 * * * * # Every hour
0 0 * * * # Midnight daily
*/5 * * * * # Every 5 minutes
0 4 * * 0 # Sunday at 4 AM
30 3 * * * # 3:30 AM daily
# Manage
crontab -l # List current user's crons
crontab -e # Edit crontab
crontab -r # Remove all crons
# System-wide crons
ls /etc/cron.d/
ls /etc/cron.daily/Practice Labs
Lab 1: Permission Exploitation
bash
# Find SUID files on Metasploitable
find / -perm -4000 2>/dev/null
# Check for world-writable directories
find / -type d -perm -o+w 2>/dev/null | head -20
# Find files owned by specific user
find / -user msfadmin 2>/dev/null
# Exploit SUID binary (if found)
# Example: find command with SUID
find . -exec /bin/bash -p \; -quitLab 2: Log Analysis
bash
# Analyze SSH attempts on Kali
tail -f /var/log/auth.log | grep sshd
# From another machine, attempt SSH with wrong password
# Observe failed attempts in real-time
# Use grep to find patterns
grep "Failed password" /var/log/auth.log | tail -20
grep "Accepted" /var/log/auth.log | tail -20Lab 3: Script Automation
bash
# Create the port scanner script above
# Run against Metasploitable
./portscan.sh 10.0.0.5 1 100
# Compare speed with nmap
time nmap -p 1-100 10.0.0.5Key Takeaways
- Filesystem hierarchy — know standard paths (
/etc,/var/log,/tmp,/home) - Permissions — SUID/SGID bits can lead to privilege escalation
- Processes — understand how to list, kill, background processes
- Bash scripting — automate repetitive tasks; essential for efficiency
- Logs — know where to look for authentication, system, and application events
Next Week Preview
Week 4 introduces Python for Security — you'll learn to script exploits, automate recon, and build tools. This is the skill that separates script kiddies from real hackers.