# Module Pentest Forensics - Rex::Forensics

> **Parent Agent**: Rex (pentest.md)
> **Sources**: defense-against-black-arts.json, hard-hatter-hacking.json, bb-kali-linux-pentest-full.json
> **Focus**: Digital Forensics, Incident Response, Anti-Forensics

---

## Specialisation

Ce module couvre la forensique et l'anti-forensique:
- Disk Forensics & Imaging
- Memory Forensics
- Network Forensics
- Log Analysis
- Evidence Collection
- Anti-Forensics Techniques

---

## DISK FORENSICS

### Acquisition d'Image

```bash
# DD (bit-by-bit copy)
dd if=/dev/sda of=/mnt/evidence/disk.dd bs=4M status=progress

# DD avec hash verification
dd if=/dev/sda | tee disk.dd | md5sum > disk.md5

# DC3DD (forensic dd)
dc3dd if=/dev/sda of=disk.dd hash=md5 hash=sha256 log=dc3dd.log

# FTK Imager (Windows)
# GUI tool pour acquisition forensique

# Guymager (Linux GUI)
guymager

# Format E01 (Expert Witness)
ewfacquire /dev/sda
```

### Montage Read-Only

```bash
# Monter image en read-only
mount -o ro,loop,noexec disk.dd /mnt/evidence

# Avec offset (si partition)
fdisk -l disk.dd  # Trouver offset
mount -o ro,loop,offset=1048576 disk.dd /mnt/evidence

# Losetup pour multiple partitions
losetup -Pf disk.dd
mount -o ro /dev/loop0p1 /mnt/part1
```

### Verification Integrite

```bash
# Hash MD5
md5sum disk.dd > disk.md5
md5sum -c disk.md5

# Hash SHA256
sha256sum disk.dd > disk.sha256
sha256sum -c disk.sha256

# Hash multiples avec hashdeep
hashdeep -c md5,sha256 -r /evidence/ > hashes.txt
hashdeep -avvl -k hashes.txt -r /evidence/
```

---

## MEMORY FORENSICS

### Acquisition Memoire

```bash
# Linux - LiME (Linux Memory Extractor)
insmod lime.ko "path=/tmp/memory.lime format=lime"

# Windows - WinPMEM
winpmem.exe memory.raw

# Windows - DumpIt
DumpIt.exe

# Windows - FTK Imager
# Via GUI

# Volatility - Profiles
volatility -f memory.raw imageinfo
```

### Volatility 3

```bash
# Installation
pip install volatility3

# Info image
vol -f memory.raw windows.info

# Liste processus
vol -f memory.raw windows.pslist
vol -f memory.raw windows.pstree

# Processus caches (unlinked)
vol -f memory.raw windows.psscan

# Connexions reseau
vol -f memory.raw windows.netstat
vol -f memory.raw windows.netscan

# DLLs charges
vol -f memory.raw windows.dlllist

# Handles
vol -f memory.raw windows.handles

# Registry
vol -f memory.raw windows.registry.hivelist
vol -f memory.raw windows.registry.printkey

# Dump processus
vol -f memory.raw windows.memmap --pid 1234 --dump

# Malfind (code injection)
vol -f memory.raw windows.malfind

# Hashdump
vol -f memory.raw windows.hashdump

# Commandes executees
vol -f memory.raw windows.cmdline

# Environment
vol -f memory.raw windows.envars
```

### Volatility 2 (Legacy)

```bash
# Profile
volatility -f memory.raw imageinfo
volatility -f memory.raw --profile=Win7SP1x64 pslist

# Commandes communes
--profile=PROFILE pslist      # Processus
--profile=PROFILE pstree      # Arbre processus
--profile=PROFILE psscan      # Scan processus
--profile=PROFILE netscan     # Reseau
--profile=PROFILE filescan    # Fichiers
--profile=PROFILE dlllist     # DLLs
--profile=PROFILE malfind     # Malware
--profile=PROFILE hashdump    # Hashes
--profile=PROFILE hivelist    # Registry hives
--profile=PROFILE cmdscan     # Commandes
--profile=PROFILE consoles    # Console history
```

---

## AUTOPSY / SLEUTH KIT

### Autopsy (GUI)

```markdown
## Workflow Autopsy

1. **New Case**
   - Case name, number, examiner

2. **Add Data Source**
   - Disk image (E01, DD, RAW)
   - Local disk
   - Logical files

3. **Ingest Modules**
   - Hash lookup
   - Keyword search
   - Recent activity
   - Extension mismatch
   - Encryption detection
   - Email parser
   - Deleted files

4. **Analysis**
   - Timeline
   - File system
   - Web artifacts
   - Communications
```

### Sleuth Kit CLI

```bash
# Info filesystem
fsstat image.dd

# Lister fichiers
fls -r image.dd

# Info fichier par inode
istat image.dd 12345

# Extraire fichier par inode
icat image.dd 12345 > extracted_file

# Trouver fichiers supprimes
fls -d image.dd

# Timeline
fls -m "/" -r image.dd > bodyfile.txt
mactime -b bodyfile.txt > timeline.csv

# Chercher par nom
ffind image.dd 12345   # inode -> path
```

---

## LOG ANALYSIS

### Linux Logs

```bash
# Logs importants
/var/log/auth.log       # Authentification
/var/log/syslog         # Systeme
/var/log/kern.log       # Kernel
/var/log/apache2/       # Apache
/var/log/nginx/         # Nginx
/var/log/mysql/         # MySQL
/var/log/secure         # Red Hat auth
~/.bash_history         # Historique bash

# Analyser auth.log
grep "Failed password" /var/log/auth.log
grep "Accepted password" /var/log/auth.log
grep "sudo" /var/log/auth.log

# Derniers logins
last
lastlog
lastb  # Failed logins

# Wtmp/Utmp analysis
utmpdump /var/log/wtmp
```

### Windows Event Logs

```powershell
# Event Viewer locations
C:\Windows\System32\winevt\Logs\

# Important logs
Security.evtx        # Security events
System.evtx          # System events
Application.evtx     # Application events
Microsoft-Windows-PowerShell%4Operational.evtx

# Event IDs importants
# 4624 - Successful logon
# 4625 - Failed logon
# 4648 - Explicit credential logon
# 4672 - Special privileges assigned
# 4688 - Process creation
# 4698 - Scheduled task created
# 4720 - User account created
# 7045 - Service installed

# PowerShell analysis
Get-WinEvent -Path ".\Security.evtx" | Where-Object {$_.Id -eq 4624}

# Export to CSV
Get-WinEvent -Path ".\Security.evtx" | Export-Csv events.csv
```

### Log2Timeline (Plaso)

```bash
# Creer super timeline
log2timeline.py timeline.plaso image.dd

# Filtrer et exporter
psort.py -o l2tcsv timeline.plaso > timeline.csv

# Filtrer par date
psort.py -o l2tcsv timeline.plaso "date > '2024-01-01'" > filtered.csv
```

---

## NETWORK FORENSICS

### Wireshark Analysis

```bash
# Filtres forensiques
http.request            # Requetes HTTP
http contains "password"
smtp                    # Email
ftp                     # FTP
dns                     # DNS queries
tcp.flags.syn == 1      # SYN packets
ip.addr == 192.168.1.1  # IP specifique

# Export objects
File > Export Objects > HTTP/SMB/TFTP

# Follow stream
Right-click > Follow > TCP Stream
```

### NetworkMiner

```bash
# Outil GUI pour extraction automatique
# - Images
# - Fichiers
# - Credentials
# - Sessions
# - DNS queries
# - Parametres
```

### Zeek (Bro)

```bash
# Analyser pcap
zeek -r capture.pcap

# Logs generes
conn.log      # Connexions
dns.log       # DNS
http.log      # HTTP
ssl.log       # SSL/TLS
files.log     # Fichiers transferes
```

---

## ANTI-FORENSICS

### Techniques (pour comprendre les menaces)

```markdown
## Data Destruction

1. **Secure deletion**
   - Overwrite multiple times
   - shred, srm, wipe

2. **Encryption**
   - Full disk encryption
   - File-level encryption

3. **Steganography**
   - Cacher donnees dans images/audio

## Artifact Elimination

1. **Log clearing**
   - Windows Event logs
   - Linux logs

2. **History deletion**
   - Browser history
   - Command history

3. **Timestomping**
   - Modifier dates fichiers

## Trail Obfuscation

1. **VPN/Tor**
2. **Spoofing**
3. **Live OS (Tails)**
```

### Detection Anti-Forensics

```bash
# Detecter timestomping
# NTFS: $STANDARD_INFORMATION vs $FILE_NAME
# Comparer MAC times

# Detecter wiping
# Chercher patterns de zeros/random

# Detecter steganographie
stegdetect image.jpg
steghide info image.jpg
binwalk image.jpg

# Detecter logs effaces
# Gaps dans timestamps
# Event ID 1102 (audit log cleared)
```

---

## INCIDENT RESPONSE

### First Responder Checklist

```markdown
## Actions Immediates

1. **Documenter la scene**
   - Photos
   - Notes
   - Temoins

2. **Preservation des preuves**
   - Ne pas eteindre si allume
   - Isoler du reseau (debrancher cable, pas WiFi off)
   - Memory dump AVANT disk

3. **Chain of custody**
   - Qui, quoi, quand, ou
   - Signatures
   - Stockage securise

4. **Collecte volatile**
   - Memoire RAM
   - Connexions reseau
   - Processus en cours
   - Utilisateurs connectes
```

### Ordre de Volatilite

```markdown
## Du plus volatile au moins volatile

1. Registres CPU, cache
2. Memoire (RAM)
3. Etat reseau (connexions, routing)
4. Processus en cours
5. Disques (donnees temporaires)
6. Disques (donnees permanentes)
7. Configurations (registry, logs)
8. Backups, archives
```

### Scripts IR

```bash
# Linux - Collecte rapide
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
mkdir /tmp/ir_$DATE

# Info systeme
uname -a > /tmp/ir_$DATE/system.txt
ps aux > /tmp/ir_$DATE/processes.txt
netstat -tulpn > /tmp/ir_$DATE/network.txt
last > /tmp/ir_$DATE/logins.txt
cat /etc/passwd > /tmp/ir_$DATE/users.txt

# Windows - Collecte rapide
# (PowerShell)
$date = Get-Date -Format "yyyyMMdd_HHmmss"
$folder = "C:\IR_$date"
New-Item -ItemType Directory -Path $folder

systeminfo > "$folder\systeminfo.txt"
Get-Process > "$folder\processes.txt"
Get-NetTCPConnection > "$folder\network.txt"
Get-LocalUser > "$folder\users.txt"
```

---

## OUTILS FORENSIQUES

| Categorie | Outil | Usage |
|-----------|-------|-------|
| **Imaging** | DD, DC3DD, FTK Imager | Acquisition disque |
| **Memory** | Volatility, LiME | Analyse memoire |
| **Disk** | Autopsy, Sleuth Kit | Analyse filesystem |
| **Network** | Wireshark, NetworkMiner | Analyse pcap |
| **Timeline** | Plaso (log2timeline) | Super timeline |
| **Steganography** | Steghide, Stegdetect | Detection steg |
| **Carving** | Foremost, Scalpel | Recovery fichiers |
| **Registry** | RegRipper | Analyse registry |

---

## COMMANDES MODULE

| Commande | Description |
|----------|-------------|
| `*disk-image` | Acquisition forensique |
| `*mem-dump` | Memory forensics |
| `*timeline-create` | Creer timeline |
| `*log-analyze` | Analyse logs |
| `*ir-collect` | Collecte IR |

---

## WORKFLOW FORENSIQUE

```
1. PREPARATION
   ├── Documentation
   ├── Outils prets
   └── Stockage prevu

2. IDENTIFICATION
   ├── Scene physique
   ├── Machines concernees
   └── Scope de l'investigation

3. COLLECTION
   ├── Memory dump (volatile d'abord!)
   ├── Disk imaging
   ├── Network captures
   └── Chain of custody

4. PRESERVATION
   ├── Hash verification
   ├── Write-blockers
   └── Copies de travail

5. ANALYSIS
   ├── Timeline
   ├── File system
   ├── Registry/Logs
   └── Memory artifacts

6. REPORTING
   ├── Findings documentes
   ├── IoCs identifies
   └── Recommandations
```

---

## REFERENCES

- **defense-against-black-arts.json** - Ch.1-3 (Live CD, Forensics)
- **hard-hatter-hacking.json** - Ch.42-43 (Anti-Forensics)
- SANS Digital Forensics
- NIST SP 800-86 (Forensics Guide)
