# 🦠 Malware — Taxonomy & Hands-On Analysis

![Python](https://img.shields.io/badge/Python-3.10%2B-blue?style=flat-square&logo=python)
![Jupyter](https://img.shields.io/badge/Jupyter-Notebooks-orange?style=flat-square&logo=jupyter)
![Families](https://img.shields.io/badge/Malware_Families-8-red?style=flat-square)
![Use](https://img.shields.io/badge/Use-Educational_Only-critical?style=flat-square)
![MITRE](https://img.shields.io/badge/MITRE_ATT%26CK-Referenced-purple?style=flat-square)

This section explores **eight malware families** through working, non-destructive Python examples. Each module follows the same pedagogical pattern: observe the attack technique at a conceptual level, understand what defenders look for, and walk away with a clearer picture of why security controls exist.

> [!CAUTION]
> All code in this section is strictly for educational use in a controlled lab environment.
> Running any of these examples outside an isolated VM may trigger AV/EDR alerts, violate policies, or break applicable law.
> See [`DISCLAIMER.md`](DISCLAIMER.md) for the full terms before opening any file.

---

## 🗺️ Malware Taxonomy at a Glance

| # | Family | Self-replicates? | Needs host? | Remote control? | Primary goal |
|---|--------|:-:|:-:|:-:|---|
| 1 | 🔴 **Virus** | ✅ | ✅ (host file) | ❌ | File infection & payload delivery |
| 2 | 🟠 **Worm** | ✅ | ❌ | ✅ | Autonomous network propagation |
| 3 | 🟡 **Trojan** | ❌ | ❌ (disguise) | ✅ | Backdoor / reverse shell |
| 4 | 🔵 **Adware** | ❌ | ❌ | ❌ | Aggressive ad injection |
| 5 | 🟣 **Persistence** | ❌ | ❌ | ❌ | Surviving reboots & evading AV |
| 6 | 🔴 **Infostealer** | ❌ | ❌ | ✅ | Credential & session theft |
| 7 | 🟠 **Exfiltration** | ❌ | ❌ | ✅ | Covert data transfer |
| 8 | 🟡 **Scareware** | ❌ | ❌ | ❌ | Social engineering via fear |

---

## 1 — 🔴 Virus [`1-Virus/`](1-Virus/)

> *"A virus is code that replicates by injecting itself into a host."*

### What it simulates
A Python script that **scans its directory for other `.py` files** and injects a malicious payload into each one. Once the infected files are executed by a legitimate user or program, the payload activates.

### Files
| File | Description |
|------|-------------|
| [`Coding_Python_Virus.ipynb`](1-Virus/Coding_Python_Virus.ipynb) | Step-by-step virus construction: payload definition → host scanning → injection → infection testing |
| [`VIRUS_LIFECYCLE.md`](VIRUS_LIFECYCLE.md) | 7-stage lifecycle: Creation → Replication → Infection → Activation → Execution → Detection → Removal |

### Key concepts
- **Host dependency**: a virus needs an existing file to attach to
- **Privilege context**: the virus runs with the same permissions as the infected script's launcher
- **Why modern AVs catch it**: signature + heuristic detection of self-modifying code patterns

> [!NOTE]
> The notebook uses harmless "do nothing" Python scripts as test hosts. No system files are touched.

---

## 2 — 🟠 Worm [`2-Worm/`](2-Worm/)

> *"A worm needs no host — it spreads itself across the network autonomously."*

### What it simulates
**Abraworm** is a network-propagating worm (SSH-based) that:
1. Scans random IP/port combinations for SSH servers
2. Attempts login with auto-generated username/password pairs
3. Searches the compromised host for files containing `"abracadabra"`
4. Exfiltrates matching files to a designated drop server
5. Installs a copy of itself on the remote host

### Files
| File | Description |
|------|-------------|
| [`abraworm.py`](2-Worm/abraworm.py) | The worm implementation (uses `paramiko` + `scp`) |
| [`abraworm.md`](2-Worm/abraworm.md) | Full documentation: architecture, pre-conditions, debug mode instructions |

### Key concepts
- **Self-propagation without user action** (contrast with the virus above)
- **SSH as attack vector**: credential guessing at scale
- **Exfiltration loop**: infected hosts become relay nodes
- **Deliberate weakness**: the built-in credential strategy is intentionally ineffective for safety

> [!WARNING]
> The worm requires Python + `paramiko` + `scp` on both attacker and victim hosts, and valid SSH credentials to work at all. Run only in `debug` mode against machines you own — see `abraworm.md` for setup.

---

## 3 — 🟡 Trojan [`3-Trojan/`](3-Trojan/)

> *"The most dangerous gift is the one you open yourself."*

### What it simulates
A **fully functional Snake game** (Pygame) with a **reverse shell payload** embedded inside. When the game launches, it silently opens a TCP connection to the attacker's IP on port 4444 and attaches a shell (`cmd.exe` / `bash`). The attacker who is listening receives full command-line access to the victim's machine.

### Files
| File | Description |
|------|-------------|
| [`Example_trojan_horse.ipynb`](3-Trojan/Example_trojan_horse.ipynb) | Walkthrough: how the payload is embedded, how the C2 channel works, Red Team tactics |
| [`dino.py`](3-Trojan/dino.py) | Alternative trojanized game (Dino runner) |
| [`snake/snake.py`](3-Trojan/snake/snake.py) | The Snake game — legit-looking carrier |

### Key concepts
- **Social engineering as the delivery vector** — the victim installs it willingly
- **Reverse shell vs bind shell**: the victim initiates the connection outward (bypasses most firewalls)
- **C2 channel (Command & Control)**: port 4444 as the attacker's listener
- **No self-replication**: Trojans rely entirely on deception

> [!TIP]
> Play the real Snake game first, then open the notebook to see exactly which lines were added — and why defenders use code-signing and sandboxed app stores.

---

## 4 — 🔵 Adware [`4-Adware/`](4-Adware/)

> *"Adware turns your screen into a billboard you never agreed to rent."*

### What it simulates
A Tkinter-based GUI application that **spawns an infinite cascade of popup windows**, each displaying a random ad image (from `ads/`) with a randomly generated price. The windows are non-closeable by the user in the intended way — closing one triggers another.

### Files
| File | Description |
|------|-------------|
| [`adware.py`](4-Adware/adware.py) | The popup engine: random image picker, price generator, hover-triggered UI |
| [`ads/`](4-Adware/ads/) | 15 sample ad images used by the popups |

### Key concepts
- **UX hijacking**: legitimate GUI frameworks weaponised for disruption
- **Persistence via event loops**: the app never exits cleanly
- **Monetisation model of real adware**: pay-per-impression fraud even without the user clicking

> [!NOTE]
> This is a pure UI demo. It does not communicate with any network or modify any system settings.

---

## 5 — 🟣 Persistence [`5-Persistence/`](5-Persistence/)

> *"The most dangerous malware is the one that comes back after you think you've removed it."*

### What it simulates
Two complementary persistence techniques:
- **Scheduled task hijacking** via Windows Task Scheduler (`schtasks`): creates a task with a legitimate-sounding name (`SecurityScan`) that re-launches a payload after a delay
- **Defence impairment**: enumerates running AV/EDR processes and attempts to terminate them before the payload executes

### Files
| File | Description |
|------|-------------|
| [`persistence.py`](5-Persistence/persistence.py) | Task Scheduler manipulation: delete → create → delayed execution |
| [`ImpairDefenses.py`](5-Persistence/ImpairDefenses.py) | AV process enumeration and termination attempt |
| [`av_processes.json`](5-Persistence/av_processes.json) | Reference list of known AV/EDR process names |
| [`Persistence.md`](5-Persistence/Persistence.md) | Deep-dive: how modern AV detects this exact pattern (process tree, schtasks flags, sandbox evasion logic) |

### Key concepts
- **MITRE ATT&CK T1053**: Scheduled Task/Job persistence
- **MITRE ATT&CK T1562**: Impair Defenses
- **Masquerading**: naming malicious tasks to look like system services
- **Time-based sandbox evasion**: scheduling execution ~1 minute into the future outruns most automated sandbox analysis windows
- **Behavioral detection**: why AV acts on *what code does*, not just *what code looks like*

> [!IMPORTANT]
> `Persistence.md` is arguably the most instructive file in this module — it explains **why** this code gets detected even when obfuscated, which is the core lesson for defenders.

---

## 6 — 🔴 Infostealer [`6-Infostealer/`](6-Infostealer/)

> *"The most valuable thing on your computer isn't your files — it's your sessions."*

### What it simulates
Three complementary attack vectors studied through a real-world malware case:

1. **Zebo-0.1.0 analysis** — a PyPI package caught in the wild by FortiGuard Labs. Techniques: keylogging (`pynput`), periodic screen capture (`PIL.ImageGrab`), hex-encoded C2 URL to Firebase, log exfiltration.
2. **User discovery** — WMI enumeration of local accounts: usernames, admin status, password policy, disabled flags.
3. **Cookie hijacking** — reads Firefox's `cookies.sqlite` directly from disk to steal authenticated web sessions without knowing any passwords.

### Files
| File | Description |
|------|-------------|
| [`Malware_Analysis_Zebo.ipynb`](6-Infostealer/Malware_Analysis_Zebo.ipynb) | Annotated reverse-engineering of Zebo: obfuscation, keylogging, C2, exfiltration |
| [`UserDiscovery.py`](6-Infostealer/UserDiscovery.py) | WMI-based local user enumeration (Windows) |
| [`WebSessionCookieHijack.py`](6-Infostealer/WebSessionCookieHijack.py) | Firefox cookie database theft via SQLite |
| [`Analyzing Malicious Intent...pdf`](<6-Infostealer/Analyzing Malicious Intent in Python Code: A Case Study | FortiGuard Labs.pdf>) | Original FortiGuard Labs report on Zebo-0.1.0 |

### Key concepts
- **Supply chain attack**: malware distributed via the official PyPI package index
- **Obfuscation**: hex-encoded strings to hide C2 endpoints from static analysis
- **Keylogging**: every keystroke → local file → encrypted upload
- **Pass-the-cookie attack**: session tokens bypass MFA entirely
- **MITRE ATT&CK T1056** (keylogging), **T1539** (steal web session cookie), **T1033** (system owner/user discovery)

> [!WARNING]
> `WebSessionCookieHijack.py` reads real browser data if executed on your own machine. Run it only in a dedicated lab environment with a throwaway profile.

---

## 7 — 🟠 Exfiltration [`7-Exfiltration/`](7-Exfiltration/)

> *"Getting in is the first step. Getting the data out — without being caught — is the art."*

### What it simulates
A survey of **covert data exfiltration channels** used by modern malware, combined with an extended analysis of the Zebo-0.1.0 exfiltration pipeline. Topics range from plain HTTP POST uploads to abuse of legitimate messaging platforms as covert C2 channels.

### Files
| File | Description |
|------|-------------|
| [`Exfiltration_methods.ipynb`](7-Exfiltration/Exfiltration_methods.ipynb) | Taxonomy of exfiltration techniques: HTTP/HTTPS, messaging platform abuse (Telegram bots), DNS tunnelling, and more |
| [`Malware_Analysis_Zebo.ipynb`](7-Exfiltration/Malware_Analysis_Zebo.ipynb) | Zebo's exfiltration pipeline in detail: log file → Firebase REST API upload |

### Key concepts
- **HTTP/HTTPS exfiltration**: POST to attacker server, CDN abuse, WebDAV
- **Messaging platform abuse**: Telegram Bot API, Discord webhooks as covert C2
- **Why HTTPS makes detection harder**: encrypted traffic hides payload content from DPI
- **Detection strategies**: DLP, anomalous outbound traffic volume, unexpected domains in DNS logs
- **MITRE ATT&CK TA0010** (Exfiltration tactic)

> [!TIP]
> Read `Exfiltration_methods.ipynb` before diving into the Zebo analysis — it gives you the vocabulary to classify exactly what Zebo is doing at each step.

---

## 8 — 🟡 Scareware [`8-Scareware/`](8-Scareware/)

> *"Scareware doesn't break your computer — it breaks your confidence."*

### What it simulates
A Tkinter application that **impersonates a critical system error**: a red-background window titled "Critical System Error!" displays a alarming fake diagnostic image (`message.jpg`) alongside a call-to-action that pushes the user toward a fraudulent support number or malicious URL.

### Files
| File | Description |
|------|-------------|
| [`fake_error.py`](8-Scareware/fake_error.py) | The scareware UI: full-screen red window, alarming error image, fake support CTA |
| [`message.jpg`](8-Scareware/message.jpg) | The fake error screen image displayed to the victim |

### Key concepts
- **Social engineering, not code execution**: the payload is psychological
- **Authority impersonation**: mimicking OS / Microsoft / Apple error dialogs
- **Urgency manufacturing**: "Your computer is infected — call NOW"
- **The business model**: victims call premium-rate numbers or buy fake "AV" software
- **Why technical controls alone aren't enough**: this bypasses all security software

> [!NOTE]
> No network calls, no file modifications, no privilege escalation. The entire attack surface is the user's emotional response.

---

## 🧭 Suggested Learning Path

```
1-Virus          → understand host-dependent replication
      ↓
2-Worm           → understand autonomous propagation
      ↓
3-Trojan         → understand social engineering delivery + C2
      ↓
5-Persistence    → understand how malware survives detection
      ↓
6-Infostealer    → understand post-compromise data collection
      ↓
7-Exfiltration   → understand how collected data leaves the system
      ↓
4-Adware         → understand monetisation-focused malware
8-Scareware      → understand purely psychological attack surfaces
```

---

## ⚙️ Prerequisites

```bash
pip install paramiko scp pillow pynput requests pygame tkinter
```

> [!WARNING]
> Some modules (Worm, Infostealer, Persistence) require a **Windows environment** or specific system libraries (`wmi`, `schtasks`). Run them in a dedicated VM — not on your primary machine.

---

## 🛡️ The Defender's Lens

Every module in this section has a mirror image in defensive security:

| 🔴 Attack | 🔵 Defence |
|-----------|------------|
| Virus injection into `.py` files | File integrity monitoring (FIM), read-only deployment |
| Worm SSH credential guessing | MFA, fail2ban, SSH key-only auth, network segmentation |
| Trojan reverse shell | Egress filtering, process tree monitoring, code signing |
| Adware popup loops | Application whitelisting, sandboxed app stores |
| Scheduled task persistence | Privileged task auditing, SIEM alerts on `schtasks` |
| Keylogging + screen capture | EDR behavioral rules, input API hooking detection |
| Exfiltration via HTTPS/Telegram | DLP, DNS monitoring, UEBA anomaly detection |
| Scareware social engineering | User awareness training, IT support hotlines |

> *The goal is never to build better attacks — it's to build better defenders.*
