# Chapter 6 Labs: Digital Forensics and Penetration Testing: Introduction

Chapter 6 introduces the twin disciplines of digital forensics and penetration testing through five
hands-on labs. The forensic labs build the acquire-hash-verify discipline; the pentest labs cover
recon, exploitation of a deliberately vulnerable web app, ATT&CK technique mapping, and the
reporting drill that turns raw tool output into a credible two-part deliverable.

---

## Prerequisites

| Requirement | Notes |
|---|---|
| Docker + Docker Compose v2 | `docker compose version` - must be v2 |
| 4 GB free RAM | juice-shop + recon-target + tools runner |
| 4 GB free disk | images; Kali build is ~1.5 GB |
| Host tools (Lab a + b only) | See per-lab sections below |

---

## Quick Start (Labs c, d, and the notebook)

```bash
# From this directory
docker compose up -d recon-target juice-shop jupyter

# Open Juice Shop (Lab d):  http://localhost:8080
# Open recon-target (Lab c): http://localhost:8081
# Open Jupyter (notebook lab): http://localhost:8888  token: labtoken

# Launch an interactive tools shell (Labs c, d, e):
docker compose run --rm tools bash
```

---

## Lab (a): Image and Hash a Test USB with dd

**Objective:** Acquire a bit-stream image of a physical or synthesised storage device, prove
integrity with SHA-256, mount the image read-only, and verify the hash is unchanged - the
forensic acquisition loop in miniature.

**Host setup (not containerised)**

`dd`, `dc3dd`, `sha256sum`, and `mount` are host-side system tools. Running them inside a
container against a real USB device requires passing the block device through as a privileged
volume, which is a security boundary violation you should not normalise in a training environment.
Run this lab directly on a Linux host or VM.

**Prepare a synthetic test image (no real USB needed):**

```bash
# On the host (Linux) -- installs mtools if needed
sudo apt install dosfstools mtools   # Debian/Ubuntu
bash seed/make-test-fs.sh            # builds evidence/test.img + evidence/test.img.sha256
```

**Walkthrough:**

1. Identify the target device (or use the synthetic image):

   ```bash
   lsblk   # note the node, e.g. /dev/sdb -- be certain; imaging the wrong device destroys data
   ```

   For this lab, substitute `evidence/test.img` as the source (`if=`) to avoid a real device.

2. Acquire a bit-stream image:

   ```bash
   sudo dd if=/dev/sdX of=evidence/acquired.img bs=4M conv=noerror,sync iflag=fullblock status=progress
   # or with inline hashing (preferred -- one read pass, no discrepancy on bad sectors):
   sudo dc3dd if=/dev/sdX of=evidence/acquired.img hash=sha256 log=evidence/acquired.log
   ```

3. Record and verify the hash:

   ```bash
   sha256sum evidence/acquired.img | tee evidence/acquired.img.sha256
   sha256sum -c evidence/acquired.img.sha256   # must print: acquired.img: OK
   ```

4. Mount the image read-only (never the original device):

   ```bash
   sudo mount -o ro,noload,loop evidence/acquired.img /mnt/evidence
   # noload prevents ext4 journal replay (a write); add norecovery for XFS
   ```

5. Prove the mount changed nothing:

   ```bash
   sudo umount /mnt/evidence
   sha256sum -c evidence/acquired.img.sha256   # still OK = handling was sound
   ```

**Expected output:** Both `sha256sum -c` calls return `acquired.img: OK`.

**Verify completion:** Pre- and post-mount hashes match. If using `dc3dd`, the `.log` file shows
the inline hash matching the separately computed `sha256sum`.

**Cleanup:** `rm -rf /mnt/evidence` (unmount first). The image file itself is your lab artefact;
keep it for Lab (b).

**Upstream reference:** ACPO Good Practice Guide for Digital Evidence; NIST SP 800-86.

---

## Lab (b): Autopsy Walk-Through on a Prepared Case

**Objective:** Load a prepared disk image in Autopsy 4.x, run the standard ingest pipeline, find a
deleted file and a web artefact, and generate a report - the everyday loop of disk forensics.

**Host setup (not containerised)**

Autopsy is a GUI Java/Swing application that bundles The Sleuth Kit. It requires a desktop
environment and cannot run headlessly in a container in any meaningful way for this lab.

**Install Autopsy:**

- Windows: download the installer from https://www.autopsy.com/download/ (bundles Java runtime).
- Linux/macOS: install Java 17 first (`apt install openjdk-17-jdk` / `brew install temurin@17`),
  then download the Autopsy release from the same URL.

**Prepare an image:**

Use `evidence/acquired.img` from Lab (a), or download a public teaching corpus:
- NIST CFReDS: https://cfreds.nist.gov/ (disk images for training)
- Digital Corpora "M57-Patents": https://digitalcorpora.org/corpora/scenarios/m57-patents-scenario

**Walkthrough:**

1. Launch Autopsy and choose "Create New Case". Set a case name, base directory, and examiner name.

2. Add Data Source: "Add Data Source > Disk Image or VM File", select the `.img` or `.E01` file.

3. Configure ingest modules: enable Hash Lookup, Keyword Search, Recent Activity, EXIF, File Type
   Identification, and Timeline. Start ingest.

4. Browse deleted files: "File Views > Deleted Files" shows recovered names and metadata.

5. Inspect metadata: right-click a file to view timestamps, MFT/inode address. On NTFS, compare
   $STANDARD_INFORMATION and $FILE_NAME timestamps - a mismatch flags timestomping (ATT&CK T1070).

6. Find artefacts: check "Web History" / "Web Downloads" under Results. Run a keyword search for
   a term the scenario plants. Tag relevant hits.

7. Build a timeline: open the "Timeline" view to place file-system and artefact events on one axis.

8. Generate a report: "Generate Report > HTML or Excel", including tagged items. This is the
   reproducible artefact - another examiner can open and verify against the same image.

**Expected output:** At least one deleted file recovered; at least one web artefact located; a
report HTML file generated in the Autopsy case directory.

**Verify completion:** The report HTML opens in a browser and lists the recovered artefacts with
timestamps and source paths.

**Cleanup:** Close the case in Autopsy. The case directory and image file persist as your artefact.

**Upstream reference:** Autopsy documentation: https://sleuthkit.org/autopsy/docs/

---

## Lab (c): Recon a Docker Target, Passive then Active

**Objective:** Fingerprint a running web target with passive and active techniques - `whatweb`,
`nmap`, `gobuster` - recording all output for the reporting drill in Lab (e).

**Setup:**

```bash
docker compose up -d recon-target
# target is at http://localhost:8081
docker compose run --rm tools bash   # opens a shell in the tools container
```

**Authorisation guard rail:** Run these commands only against the provided lab target
(`ch06-recon-target`, 172.28.6.x on the lab-net) or a system you own and are authorised to test.
Scanning someone else's system without authorisation is a criminal offence under Ireland's Criminal
Justice (Offences Relating to Information Systems) Act 2017, the UK Computer Misuse Act 1990,
and the US CFAA. This lab is the runnable enforcement of that rule - the container is the boundary.

**Walkthrough (commands run inside the tools container):**

1. Passive-leaning fingerprint (single HTTP request):

   ```bash
   whatweb -a 1 http://recon-target:3000
   ```

   Record the web server, framework, and version strings reported.

2. Active port and service scan across all TCP ports:

   ```bash
   nmap -sV -sC -p- recon-target
   ```

   Then a targeted aggressive sweep of likely web ports:

   ```bash
   nmap -A -p 80,443,3000 recon-target
   ```

3. Active content brute-force (directory enumeration):

   ```bash
   gobuster dir -u http://recon-target:3000 \
     -w /usr/share/wordlists/dirb/common.txt \
     -o /labs/evidence/gobuster-recon-target.txt
   ```

4. Save all output. The nmap and whatweb results feed directly into Lab (e):

   ```bash
   nmap -A -p 3000 recon-target -oN /labs/evidence/nmap-recon-target.txt
   whatweb -a 1 http://recon-target:3000 > /labs/evidence/whatweb-recon-target.txt
   ```

**Expected output:** nmap identifies at least one open TCP port and the service/version; gobuster
returns at least one non-404 path; whatweb identifies the application framework.

**Verify completion:** Three output files in `evidence/`: `nmap-recon-target.txt`,
`whatweb-recon-target.txt`, `gobuster-recon-target.txt`. All contain findings.

**Cleanup:** `docker compose stop recon-target`

---

## Lab (d): Exploit OWASP Juice Shop and Map to ATT&CK

**Objective:** Exploit two vulnerabilities in OWASP Juice Shop (SQL injection login bypass and
broken access control / IDOR), find the Score Board, and map each finding to ATT&CK techniques
and OWASP Top 10 / CWE numbers.

**Setup:**

```bash
docker compose up -d juice-shop
# browse to http://localhost:8080
```

**Authorisation guard rail:** OWASP Juice Shop is a deliberately vulnerable application designed
for training. Run exploits only against your own local container (ch06-juice-shop). Never attempt
these techniques against any system you do not own and have explicit written authorisation to test.

**Walkthrough:**

1. Find the Score Board: Juice Shop hides its challenge tracker. Inspect the JavaScript source or
   intercept traffic to find `/score-board`. Finding it is Challenge 1.

2. SQL injection login bypass (ATT&CK T1190 "Exploit Public-Facing Application"):

   Navigate to http://localhost:8080/#/login. In the email field enter:

   ```
   ' OR 1=1--
   ```

   (include the trailing space before the two dashes, then any string as password)

   The injected `OR 1=1` makes the authentication query return the first user (administrator),
   bypassing authentication with no valid credentials.

   Record on the Score Board: the "Login Admin" challenge should mark as solved.

3. Broken access control / IDOR (OWASP A01:2021 / CWE-639):

   While logged in, inspect the basket API request in browser DevTools (Network tab). Note the
   basket ID in the URL (e.g. `/rest/basket/1`). Change the ID to another integer - you can read
   another user's basket. This is CWE-639 (Authorization Bypass through User-Controlled Key) and
   CWE-284 (Improper Authorization).

   ATT&CK note: there is no clean 1:1 ATT&CK technique for IDOR. The nearest umbrella technique
   is T1190 (initial access vector) or T1078 (if valid credentials are used for the lateral move).
   Use OWASP/CWE for the vulnerability classification; ATT&CK for the attacker-behaviour framing.

4. Record findings for Lab (e). For each finding note:
   - Affected asset (URL, parameter, endpoint)
   - Technique used and request sent
   - Response received (evidence)
   - ATT&CK ID (if clean 1:1) or OWASP/CWE + adjacent ATT&CK

**Two-lens mapping table:**

| Finding | OWASP / CWE | ATT&CK | Clean 1:1? |
|---|---|---|---|
| SQL injection login bypass | A03 Injection / CWE-89 | T1190 Exploit Public-Facing Application | Partial |
| Broken access control (IDOR) | A01 Broken Access Control / CWE-639+CWE-284 | T1190 + T1078 (adjacent only) | No - use OWASP/CWE |

**Expected output:** Score Board shows "Login Admin" as solved. DevTools shows basket contents
for a user ID you did not log in as.

**Verify completion:** Score Board solved count increases with each completed challenge.

**Cleanup:** `docker compose stop juice-shop`

---

## Lab (notebook): Run the Kill-Chain Mapper Notebook

**Objective:** Run `06_attack_kill_chain_mapper.ipynb` to build the kill-chain x ATT&CK tactic
coverage matrix and the Sony Pictures 2014 heat-map. Everything runs offline (stubbed STIX bundle,
no network calls). Confirm all assertions hold.

**Setup:**

```bash
docker compose up -d jupyter
# Open http://localhost:8888 - token: labtoken
# Navigate to 06_attack_kill_chain_mapper.ipynb and open it.
```

**Walkthrough:**

1. Run the imports cell (Cell 1). Confirm the pinned version prints:
   `Pinned to MITRE ATT&CK Enterprise v19.0 (captured 11 May 2026)`.

2. Run the stub-bundle cell (Cell 2). The function `fetch_attack_bundle()` returns an inline STIX
   dict - no network access. Confirm "Stubbed bundle loaded" prints with tactic and technique counts.

3. Run the parse cell (Cell 3). The `assert len(tactics_df) == 14` guard checks the tactic count
   (14 Enterprise tactics). The chapter text notes v19.0 has 15 tactics; if your copy of the stub
   has been updated to v19.0 with 15 tactics, update the assertion to `== 15` accordingly.

4. Run the kill-chain cell (Cell 4). Confirm `assert len(kill_chain) == 7` holds.

5. Run the mapping cell (Cell 5). The binary kill-chain x tactic matrix is built. Confirm the
   assertion that every phase maps to at least one tactic.

6. Run Cell 6 to render Heat-map 1 (kill-chain vs ATT&CK tactic coverage).

7. Run Cell 6b (the Sony case findings cell). Confirm `assert len(findings_df) == 13` holds and
   every technique ID resolves to a known tactic (zero unknowns).

8. Run Cell 8 to render Heat-map 2 (Sony 2014 ATT&CK tactic heat - colour clusters at
   Reconnaissance and Impact, consistent with a destructive endpoint-wiper attack).

9. Run Cell 9 (two-lens table). Note the "NO" entries in the "clean 1:1?" column for IDOR and XSS.

10. Run Cell 10 (reproducibility footer). Confirm "All assertions held" prints.

**Expected output:** Both heat-maps render. All assert statements pass silently. The footer prints
the version, source, and access date.

**Verify completion:** No AssertionError raised in any cell. The footer line reads
"All assertions held; notebook is self-contained and offline."

**Cleanup:** `docker compose stop jupyter`

---

## Lab (e): Reporting Drill - Raw Findings to Exec Summary and Technical Appendix

**Objective:** Take the unprocessed output from Labs (c) and (d) and produce a two-part pentest
report: a one-page executive summary (non-technical, business-risk framing) and a technical
appendix (per-finding anatomy with severity, reproduction, root cause, and remediation).

**Setup:** No new services. Requires the evidence files from Labs (c) and (d):
- `evidence/nmap-recon-target.txt`
- `evidence/whatweb-recon-target.txt`
- `evidence/gobuster-recon-target.txt`
- Notes from the Juice Shop SQL-injection and IDOR findings (Lab d)

**Walkthrough:**

1. **Triage by severity.** Before writing any prose, sort every finding into Critical / High /
   Medium / Low with a one-line rationale (impact x likelihood):
   - SQLi login bypass - Critical (unauthenticated admin access, full account table exposed)
   - Broken access control (IDOR) - High (lateral data access across all user baskets)
   - Verbose server banner (from nmap/whatweb) - Low (information disclosure, no direct exploit)

2. **Write the executive summary (1 page maximum).** Audience: non-technical decision-maker.
   State what was tested, the business risk in plain language (no CVE strings, no tool output,
   no screenshots), and the top findings ranked by severity. Example opener:
   "An authenticated user can log in as any account, including the administrator, by submitting a
   crafted email address. No valid password is required."

3. **Write the technical appendix.** One entry per finding with this fixed anatomy:
   - Affected asset: exact URL, parameter, or endpoint
   - Severity + rationale: the rating and the impact x likelihood reasoning
   - Reproduction steps: exact request/input that triggers the issue
   - Evidence: the response or returned record (screenshot or copied response body)
   - Root-cause analysis: why the bug exists (unparameterised SQL; missing object-level auth check)
   - Remediation: the specific fix (prepared statements; server-side ownership validation per request)

4. **Map each finding to ATT&CK and OWASP.** Tag the SQLi bypass to T1190; tag the IDOR to
   OWASP A01:2021 / CWE-639, noting the absence of a clean ATT&CK 1:1 (T1190 + T1078 adjacent).

5. **Self-grade against the tool-dump pitfall.** Re-read your appendix. Does every finding have a
   root cause and a fix an engineer could apply? Can a reader reproduce it from your steps alone?
   If any entry is pasted scanner output without triage and root cause, rewrite it.

6. **Export the deliverable.** On Linux/macOS, convert the markdown report to `.docx` using:

   ```bash
   # From the tools container or host (requires pandoc):
   pandoc reports/ch06-report.md -o reports/ch06-report.docx
   ```

   A report shared with a client is a document - never raw markdown.

**Expected output:** A two-section report with an executive summary (1 page) and a technical
appendix (3-4 entries). Every finding in the appendix carries all six anatomical elements.

**Verify completion:** Re-read the appendix. No entry consists of pasted tool output alone.
Every finding has a root cause, a remediation, and reproduction steps an engineer can follow.

**Cleanup:** No containers to stop. Retain `reports/ch06-report.md` and the `.docx` export.

---

## Teardown (all services)

```bash
docker compose down -v
```

This stops and removes all containers and named volumes. Local `evidence/`, `notebooks/`, and
`reports/` directories are preserved on the host.

---

## Safety and Authorisation

All offensive labs in this chapter (recon, exploitation) target containers running on your own
machine. The lab-net bridge network (`172.28.6.0/24`) is local-only; nothing is exposed to the
internet beyond the mapped localhost ports.

NEVER run nmap, gobuster, whatweb, or any exploit technique against a system you do not own and
have explicit written authorisation to test. Testing without authorisation is a criminal offence
under Ireland's Criminal Justice (Offences Relating to Information Systems) Act 2017, the UK
Computer Misuse Act 1990, and the US Computer Fraud and Abuse Act. The scope of authorisation
here is exactly: `localhost`, `recon-target`, `juice-shop` on the `lab-net` network.

No real malware is included or required anywhere in this lab pack.
