Delight Cybersecurity  ·  Workbook Series
Student Workbook
🐧 Linux Edition

Email Threat Analysis

Phishing Triage · Attachment Forensics · BEC Investigation — Fully Adapted for Linux VM

📋 Labs 4 · 5 · 6 ⚡ Intermediate Level ⏱ ~5–6 hours total 🎓 Security+ SY0-801: 2.3 · 2.5 · 4.1 · 4.7 · 5.6 🐧 Kali Linux (also Ubuntu / Debian / REMnux)

Delight Cybersecurity · Workbook Series

📑 Table of Contents

  1. Linux VM Setup & Tool Installation
  2. Overview & Learning Objectives
  3. Lab 4 — Email Attachment Analysis
    1. Where to Get Sample Files
    2. Part A — Metadata Extraction
    3. Part B — Macro & Embedded Script Detection
    4. Part C — Sandbox Detonation & Report Reading
    5. Part D — RTF and PDF Attachments
    6. Part E — QR Code Phishing (Quishing)
  4. Lab 5 — BEC (Business Email Compromise)
    1. Where to Get Sample .eml Files
    2. Part A — The Suspicious Email
    3. Part B — Header Analysis
    4. Part C — Verification Workflow & Verdict
    5. Part D — Email Authentication Records (SPF, DKIM, DMARC, BIMI)
  5. Lab 6 — Full Triage Workflow
    1. After the Incident — Awareness & Metrics
  6. Resources, Practice Samples & Quick-Reference
  7. Instructor Notes
Setup

Linux VM Setup & Tool Installation

This workbook is written entirely for a Linux VM. Every command runs in a standard terminal — no Windows required. The commands are written for Kali Linux, the recommended system for this series. They also work on Ubuntu, Debian and REMnux, with the differences noted below.

🐧
Before you start: Create a VM snapshot in VirtualBox or VMware before downloading any samples. That gives you a clean restore point if anything goes wrong. Allocate at least 4 GB RAM and 40 GB disk to your VM.

Recommended Distributions

DistroWhy It Works WellBest For
REMnuxPurpose-built malware analysis distro — ExifTool, oletools and oledump.py are pre-installedAnyone who wants the least setup
Ubuntu 24.04 LTSStable and widely documented; pdfid and pdf-parser are not in its package listBeginners to Linux
Debian 13Lightweight, stable, low resource useOlder hardware / small VMs

One-Time Tool Installation

Run this entire block once after creating your VM. It installs every tool used across all three labs.

# ── Step 1: Update package lists ──────────────────────────────────
sudo apt update

# ── Step 2: Tools from the package manager ────────────────────────
sudo apt install -y libimage-exiftool-perl python3-docx python3-olefile pipx \
    file xxd binutils curl wget unzip git whois dnsutils ripmime qrencode zbar-tools

# ── Step 3: oletools (olevba, rtfobj, oleid) in its own environment ─
pipx install oletools
pipx ensurepath

# ── Step 4: oledump.py — a separate tool, NOT part of oletools ─────
mkdir -p ~/.local/bin
wget -O ~/.local/bin/oledump.py \
  https://raw.githubusercontent.com/DidierStevens/DidierStevensSuite/master/oledump.py
sed -i '1s/python$/python3/' ~/.local/bin/oledump.py
chmod +x ~/.local/bin/oledump.py

# ── Step 5: PDF tools (Kali and REMnux; skip on Ubuntu and Debian) ─
sudo apt install -y pdfid pdf-parser

# ── Step 6: Optional — Thunderbird to open .eml files visually ────
sudo apt install -y thunderbird

# ── Now CLOSE the terminal, open a new one, and verify ────────────
echo "--- ExifTool ---" && exiftool -ver
echo "--- olevba ---"   && olevba --help | head -1
echo "--- oledump ---"  && oledump.py --version
echo "--- Python 3 ---" && python3 --version
echo "--- All done! ---"
⚠️
If olevba or oledump.py is "not found", you have not yet opened a new terminal. pipx ensurepath adds ~/.local/bin to your PATH for both zsh (Kali's default shell) and bash, but only for terminals opened afterwards.
💡
Why pipx? Current Kali and Debian block system-wide pip3 install. Older guides get round this with --break-system-packages, which can damage Python packages the operating system depends on. pipx installs each Python tool in its own isolated environment and is the supported method.

Verify Tool Paths

which exiftool       # → /usr/bin/exiftool
which olevba         # → ~/.local/bin/olevba
which oledump.py     # → ~/.local/bin/oledump.py
which pdf-parser     # → /usr/bin/pdf-parser (Kali and REMnux only)
which ripmime        # → /usr/bin/ripmime
python3 --version    # → Python 3.11 or higher

Create Your Working Directory

# Create an isolated folder structure for all lab work
mkdir -p ~/email-threat-labs/{lab4,lab5,lab6,samples}
cd ~/email-threat-labs
ls -la   # should show lab4  lab5  lab6  samples

# Always copy sample files INTO this directory before analysing them
# Never analyse files from ~/Downloads or the Desktop
✅
Once setup is complete, take a fresh VM snapshot labelled "tools-installed-clean". Restore to this snapshot between labs to keep your environment consistent.

Overview & Learning Objectives

Complete these three labs in order. Each builds on skills from the previous one. By the end, you will be able to triage a complete phishing email from first receipt through to a structured incident report — using only a Linux terminal and free web tools.

Lab 4 — Attachment Analysis

Metadata, macros, sandbox reports, RTF and PDF files, QR-code phishing, IOC identification.

⏱ ~110 min Security+ 2.3 · 2.5 · 4.1

Lab 5 — BEC Scenario

Header forensics, lookalike domains and spoofing, SPF/DKIM/DMARC/BIMI records, wire transfer fraud verification.

⏱ ~90 min Security+ 2.3 · 2.5 · 4.1 · 5.6

Lab 6 — Full Triage Workflow

End-to-end structured incident report: sender, links, attachment, affected users, actions — then awareness and metrics.

⏱ ~120 min Security+ 2.5 · 4.1 · 4.7 · 5.6

Tools Used Across All Labs

ToolPurposeHow to Install on Linux
ExifToolFile metadata extractionsudo apt install libimage-exiftool-perl
olevba / oletoolsOffice macro analysispipx install oletools
oledump.pyLow-level OLE stream inspectionSeparate download — see the setup block
pdf-parserPDF JavaScript / object inspectionsudo apt install pdfid pdf-parser (Kali, REMnux)
fileDetect true file type regardless of extensionPre-installed on all Linux distros
sha256sum / md5sumGenerate hashes for VirusTotal lookupPre-installed on all Linux distros
stringsExtract readable text from any binarysudo apt install binutils
whoisDomain registration lookupsudo apt install whois
ripmimeExtract attachments from a saved emailsudo apt install ripmime
rtfobjFind objects embedded in RTF filesIncluded with oletools
pdfidCount risky features in a PDFsudo apt install pdfid (Kali, REMnux)
zbarimg / qrencodeRead and create QR codes without a phonesudo apt install zbar-tools qrencode
digLook up SPF, DKIM, DMARC and BIMI records in DNSsudo apt install dnsutils
curl / wgetDownload samples, query APIs from terminalsudo apt install curl wget
VirusTotalFile & URL reputationWeb — virustotal.com
Any.runCloud sandbox (Windows environment); public reports can be read without uploading anythingWeb — any.run
MXToolboxEmail header analysisWeb — mxtoolbox.com/EmailHeaders
URLScan.ioURL inspection without visiting the page yourself (scans are public by default)Web — urlscan.io
AbuseIPDBIP reputation check (free API)Web + curl API — abuseipdb.com
🚨
Golden Safety Rule: All work happens inside your Linux VM. Never copy sample files to your host machine. Never open a suspicious file in any application on the VM — all analysis is terminal-only unless you are using a cloud sandbox.
Lab 4

Email Attachment Analysis

A user forwards an email with a suspicious Word document. Your job is to examine the file without executing it — extract metadata, detect hidden macros, then see how a cloud sandbox reveals its behaviour.

Security+ SY0-801 objectives: 2.3 (attachment-based threat vectors), 2.5 (indicators of compromise), 4.1 (sandboxing).

🚨
Safety: Do NOT open any sample file in LibreOffice or any application on your VM — macros can execute even on Linux if enabled. All analysis is terminal-only in this lab.

Where to Get Sample Files for Lab 4

Use Option A unless your instructor tells you otherwise. It is completely safe and every command in this lab has been written to work with it. Options C and D involve real malware and are for instructor-supervised sessions only.

💡
Which Office files can carry macros? A .docx or .xlsx file cannot contain a macro. Macros live in the older .doc / .xls formats and in the macro-enabled formats .docm, .dotm and .xlsm. A .docx can still be dangerous in other ways — for example by carrying a link, as the sample in this lab does.
📌
Beyond the exam: Since 2022 Microsoft Office has blocked macros in files that arrive from the internet by default. Macro attacks still occur, but attackers have largely moved to other attachments: PDFs and Word files containing links or QR codes, HTML files, OneNote files, and disk images or archives holding shortcut files. The analysis method you learn here — identify the true type, hash it, read the metadata, look inside without opening — applies to all of them.
📦 Option A — Create the Safe Practice Files (Recommended · Zero Risk)

This creates two harmless files. suspicious_invoice.docx is a Word file with suspicious metadata and an embedded link. practice_macro.vba is the text of a macro that only displays a message box; olevba can analyse it exactly as it would a macro found inside a document. The address in both files is a reserved documentation address that does not exist.

# Create the Word file
python3 - <<'PYEOF'
import datetime, os, shutil, zipfile
from docx import Document

lab = os.path.expanduser("~/email-threat-labs/lab4")
os.makedirs(lab, exist_ok=True)
path = os.path.join(lab, "suspicious_invoice.docx")

doc = Document()
props = doc.core_properties
props.author = "builder01"
props.last_modified_by = "admin"
props.created = datetime.datetime(2025, 2, 14, 3, 21, 7)
props.modified = datetime.datetime(2025, 3, 1, 9, 44, 22)
doc.add_heading("Invoice #2025-0312", level=1)
doc.add_paragraph("Please find your outstanding payment details below.")
doc.add_paragraph("Amount due: $12,500.00")
doc.add_paragraph("Pay online now: http://198.51.100.47/pay/invoice-0312")
doc.save(path)

# python-docx cannot set the Company field, so patch it inside the ZIP
tmp = path + ".tmp"
with zipfile.ZipFile(path) as zin, zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED) as zout:
    for item in zin.infolist():
        data = zin.read(item.filename)
        if item.filename == "docProps/app.xml":
            data = data.replace(b"<Company/>", b"<Company>UNKNOWN</Company>")
            data = data.replace(b"Microsoft Macintosh Word", b"Microsoft Office Word")
            data = data.replace(b"<AppVersion>14.0000", b"<AppVersion>16.0000")
        zout.writestr(item, data)
shutil.move(tmp, path)
print(f"Test file created -> {path}")
PYEOF

# Create the practice macro (plain text — it cannot run)
cat > ~/email-threat-labs/lab4/practice_macro.vba <<'EOF'
' TRAINING SAMPLE - harmless. This macro only displays a message box.
' The address below is a reserved documentation address that does not exist.
Sub AutoOpen()
    Dim updateServer As String
    updateServer = "http://198.51.100.47/stage2.exe"
    MsgBox "Training sample - this macro does nothing else."
End Sub
EOF

ls -lh ~/email-threat-labs/lab4/
📦 Option B — LetsDefend Challenge Files (Guided + Scored)

LetsDefend provides phishing email samples as part of its SOC simulator. Each challenge gives you a downloadable .eml or attachment.

Steps:

  1. Create a free account at letsdefend.io
  2. Find the Email Analysis learning path
  3. Each challenge provides a downloadable sample — save to ~/email-threat-labs/lab4/
  4. Your answers are scored automatically — useful for self-assessment
📦 Option C — MalwareBazaar (Instructor-Supervised · Live Malware)

MalwareBazaar hosts confirmed malicious Office documents tagged by family. All samples are zipped with password infected. Every API request now needs a free Auth-Key: sign in at auth.abuse.ch and create one in your profile. The same key works for ThreatFox and URLhaus. Take a VM snapshot first.

cd ~/email-threat-labs/lab4

# Keep your key in a variable for this terminal session — never save it in a script
read -s -p "Paste your abuse.ch Auth-Key: " ABUSECH_KEY; echo

# List recent samples tagged VBA and show their SHA256 hashes
curl -s -X POST https://mb-api.abuse.ch/api/v1/ \
  -H "Auth-Key: $ABUSECH_KEY" \
  -d 'query=get_taginfo&tag=VBA&limit=5' | python3 -m json.tool | grep sha256_hash

# Download one sample by its SHA256 hash (replace PASTE_SHA256_HERE)
curl -s -X POST https://mb-api.abuse.ch/api/v1/ \
  -H "Auth-Key: $ABUSECH_KEY" \
  -d 'query=get_file&sha256_hash=PASTE_SHA256_HERE' \
  --output macro_sample.zip

# Unzip — password is always: infected
unzip -P infected macro_sample.zip
ls -lh
🚨
These are live, functioning malware samples. Never extract outside a VM. Never transfer to your host machine.
📦 Option D — theZoo GitHub Repository (Instructor-Supervised · Live Malware)

A curated repository of real malware samples for educational use. Take a VM snapshot before cloning.

# Clone into your samples directory
cd ~/email-threat-labs/samples
git clone https://github.com/ytisf/theZoo.git

# Browse the available samples
ls theZoo/malware/Binaries/ | head -40
🚨
These are live, functioning malware samples. Never extract outside a VM. Never transfer to your host machine.

Part A — Metadata Extraction

💡
What is metadata? Files embed hidden information — who created them, on what software, at what time, and for which organisation. This "data about data" often exposes the real attacker even when the email body looks convincing.

Step-by-Step Commands (Linux Terminal)

  1. Navigate to your lab directory:
    cd ~/email-threat-labs/lab4
  2. Always confirm the true file type first — never trust the extension:
    file suspicious_invoice.docx
    # Expected: Microsoft Word 2007+ (ZIP)
    # If it says something different, the extension may be faked
  3. Generate file hashes for VirusTotal lookup:
    sha256sum suspicious_invoice.docx
    md5sum    suspicious_invoice.docx
  4. Run ExifTool to extract all metadata:
    exiftool suspicious_invoice.docx
  5. Extract only the most forensically interesting fields:
    exiftool -Creator -LastModifiedBy -Company \
             -CreateDate -ModifyDate -Application \
             suspicious_invoice.docx
    
    # Field names differ by file type: Word files store the author as "Creator".
    # If a field prints nothing, run plain "exiftool file" and read the real names.
  6. For PDF attachments instead of .docx:
    exiftool -Producer -Creator -Author -CreateDate report.pdf
  7. Linux bonus — inspect the raw ZIP structure (a .docx is a ZIP archive):
    # List all files inside the docx without extracting
    unzip -l suspicious_invoice.docx
    
    # Extract and read the core metadata XML directly
    mkdir /tmp/docx_inspect
    unzip suspicious_invoice.docx -d /tmp/docx_inspect
    cat /tmp/docx_inspect/docProps/core.xml
    
    # Hunt for embedded URLs or IPs across all XML files
    grep -rEo '(https?://[^ "<>]+|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})' \
      /tmp/docx_inspect/ | grep -vE 'schemas\.|w3\.org|purl\.org'
    # The second grep removes the dozens of harmless format-definition addresses
    # that every Word file contains, leaving only what the author put there
    
    # Clean up
    rm -rf /tmp/docx_inspect
  8. Cross-reference the Creator field against the claimed sender in the email.

Sample ExifTool Output — Annotated

File Name        : suspicious_invoice.docx
Creator          : builder01            ← Does NOT match the claimed sender "FedEx Billing"
Last Modified By : admin                ← Generic admin account
Company          : UNKNOWN              ← Legitimate docs embed a company name
Create Date      : 2025:02:14 03:21:07Z ← 3 AM creation — outside business hours
Modify Date      : 2025:03:01 09:44:22Z
Application      : Microsoft Office Word
🚩
Red Flags in this output:
  • Creator 'builder01' — does not match claimed sender 'FedEx Billing'
  • Creation time 03:21 AM — outside normal business hours
  • Company is UNKNOWN — legitimate corporate documents almost always embed a company name
  • Caution: metadata is set by whoever made the file and can be faked or left blank. Treat it as a lead to follow up, never as proof on its own

Analysis Checklist — Record Your Findings

Part B — Macro & Embedded Script Detection

💡
What are macros? Office documents can contain VBA (Visual Basic for Applications) scripts that run automatically when the file is opened. Attackers embed them to download malware, run PowerShell, or establish persistence. On Linux, olevba lets you read the macro source safely — no execution risk.

Step-by-Step Commands

  1. Confirm oletools is installed and working:
    olevba --help | head -1
  2. Run the initial macro scan on the Word file, then on the practice macro:
    cd ~/email-threat-labs/lab4
    olevba suspicious_invoice.docx
    # Expected: "No VBA or XLM macros found." — correct, a .docx cannot hold one
    
    olevba practice_macro.vba
    # Expected: the macro source, then a table with AutoExec and IOC rows
  3. Review the flags olevba assigns — look for: AutoExec, Suspicious, IOC
  4. Real macros hide their strings with encoding tricks. Ask olevba to decode them and show the source with the hidden values put back in:
    olevba --decode --reveal practice_macro.vba
  5. Use oledump.py for a low-level OLE stream inspection:
    oledump.py suspicious_invoice.docx
    # Expected here: "no OLE file was found" — this .docx has no macro container
    
    # On a real macro document (.doc or .docm), streams holding macros are
    # marked with 'M'. Dump one with:
    oledump.py -s A3 -v macro_document.docm
    # Replace A3 with whichever stream number shows 'M' 
  6. For PDF attachments — scan for embedded JavaScript:
    pdf-parser -s JavaScript suspicious.pdf
    # On some systems the command is:
    pdf-parser.py -s JavaScript suspicious.pdf
  7. Hunt for readable URLs and commands. A .docx is compressed, so strings finds nothing in it; read the text inside the ZIP instead. On an old-format .doc, strings works directly:
    # .docx / .docm — look inside the ZIP
    unzip -p suspicious_invoice.docx word/document.xml \
      | sed 's/<[^>]*>/ /g' \
      | grep -oiE '(https?://[^ ]+|powershell|cmd\.exe|wscript)'
    
    # Old .doc format — strings works directly
    strings old_format.doc \
      | grep -iE '(http|powershell|cmd\.exe|base64|shell|wscript)' 

What olevba Reports on a Real Malicious Macro — Annotated

Your practice macro produces the AutoExec and IOC rows. A real malicious macro typically shows all of these:

TypeKeywordWhat It Means
AutoExecAutoOpenCode runs the moment the document is opened — no user click required
SuspiciousShellMacro may launch an external application
SuspiciousPowerShellMacro may invoke PowerShell (Windows command runner)
SuspiciousBase64 StringsObfuscated payload — deliberately encoded to evade antivirus
IOC198.51.100.47C2 IP address embedded in the macro
IOChttp://198.51.100.47/stage2.exeSecond-stage payload download URL

Decoded Macro Source (Example)

Sub AutoOpen()
  Dim cmd As String
  cmd = "powershell -nop -w hidden -enc " & _
        "aQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQA..."
  Shell cmd
End Sub
🚨
What this macro does:
  • AutoOpen — fires immediately on file open, no prompts to the user
  • Base64-encoded PowerShell — the long string is an obfuscated command that evades AV
  • -w hidden — hides the terminal window from the victim (Windows flag)
  • Shell call — executes a system command, used here to download and run a remote payload
🐧
Linux note: The macro contains Windows-only commands (PowerShell, Shell). Running this in LibreOffice on Linux would not trigger the payload since these commands don't exist — but never open it anyway. Some macro families detect the OS and carry Linux-specific payloads.

IOC Checklist — Tick Everything You Find

Part C — Sandbox Detonation & Report Reading

💡
What is sandbox detonation? You upload the file to an online service that runs it inside an isolated Windows VM in the cloud and records every action — processes spawned, network connections made, files written, registry changes — with zero risk to your Linux VM.
🚨
Beyond the exam: Anything you upload to a free sandbox or to VirusTotal becomes visible to other users — including attackers, who watch these services to learn whether they have been detected. In a real job, look up the file's hash first; upload the file itself only if the hash is unknown, the file contains no confidential information, and your organisation's policy allows it.

Read a Public Sandbox Report (Any.run)

Your practice files are harmless, so detonating them would show nothing. Instead, study a report that someone else has already produced for a real malicious document. No upload and no account are needed to read public reports.

  1. In your VM browser, open the public submissions list at app.any.run/submissions
  2. Find a submission with a Malicious verdict whose file is an Office document (.doc, .docm or .xlsm)
  3. Open it and watch the recorded session
  4. Review the report sections: Process Tree · Network · File System · Verdict

If you later need to submit a file yourself: a free Any.run account asks for a business email address (other applicants are verified through its Discord server), the free plan offers a Windows 10 64-bit environment, and every free submission is public. hybrid-analysis.com is an alternative with a free tier.

What to Look For

🌲 Process Tree winword.exe spawning cmd.exe → powershell.exe is the classic malicious chain. Screenshot it for your report.
🌐 Network Activity C2 beaconing — HTTP POST to unknown IPs, DNS queries for random-looking domains.
📁 File Drops New .exe, .dll, or .bat files written to %TEMP%, AppData, or ProgramData.
🔒 Persistence Registry Run key writes, scheduled task creation, startup folder drops.
🐧
Local sandbox option (advanced): You can run CAPEv2 — the maintained successor to the discontinued Cuckoo Sandbox — locally on Linux to keep samples entirely offline. See github.com/kevoreilly/CAPEv2 for setup instructions — requires nested VM support in your hypervisor.
💡
Cross-reference tip: Take every IP and domain from the sandbox report and check it on AbuseIPDB, VirusTotal, and ThreatFox. These cross-references become your final IOC list for the report.

Part D — RTF and PDF Attachments

💡
Why these two formats? With macros blocked by default, RTF and PDF files are now among the most common malicious attachments. An RTF file cannot hold a macro, but it can carry embedded objects that exploit weaknesses in Word, and it is often given a .doc extension so that it looks like an ordinary Word file. A PDF can contain links, scripts and actions that fire when the file is opened. The method is the same as before: true type, hash, metadata, then look inside without opening.

Create the Safe Practice Files

Both files are harmless. The RTF file is plain text with a link; the PDF contains a link and a script that would only display a message box. The address in both is a reserved documentation address.

cd ~/email-threat-labs/lab4

# An RTF file disguised with a .doc extension
cat > payment_advice.doc <<'EOF'
{\rtf1\ansi\deff0
{\fonttbl{\f0 Arial;}}
{\info{\author builder01}{\company UNKNOWN}{\title Payment Advice}}
\f0\fs24 PAYMENT ADVICE\par
\par
Your payment could not be processed. Review the details here:\par
{\field{\*\fldinst{HYPERLINK "http://198.51.100.47/pay/advice-7731"}}{\fldrslt{\ul View payment advice}}}\par
}
EOF

# A PDF with a link, an automatic action and a harmless script
python3 - <<'PYEOF'
import os

path = os.path.expanduser("~/email-threat-labs/lab4/delivery_notice.pdf")
link = "http://198.51.100.47/track/parcel-5521"
text = "Your parcel could not be delivered. Click here to reschedule."

stream = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET".encode()
objects = [
    b"<< /Type /Catalog /Pages 2 0 R /OpenAction 6 0 R >>",
    b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
    b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R "
    b"/Resources << /Font << /F1 5 0 R >> >> /Annots [7 0 R] >>",
    b"<< /Length %d >>\nstream\n" % len(stream) + stream + b"\nendstream",
    b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
    b"<< /S /JavaScript /JS (app.alert\\('Training sample - harmless'\\);) >>",
    b"<< /Type /Annot /Subtype /Link /Rect [72 710 420 735] "
    b"/A << /S /URI /URI (" + link.encode() + b") >> >>",
    b"<< /Author (builder01) /Creator (Unknown) /Producer (pdf-kit 0.1) "
    b"/CreationDate (D:20250214032107Z) >>",
]

pdf = b"%PDF-1.4\n"
offsets = []
for number, body in enumerate(objects, start=1):
    offsets.append(len(pdf))
    pdf += b"%d 0 obj\n" % number + body + b"\nendobj\n"
xref = len(pdf)
pdf += b"xref\n0 %d\n0000000000 65535 f \n" % (len(objects) + 1)
for offset in offsets:
    pdf += b"%010d 00000 n \n" % offset
pdf += b"trailer\n<< /Size %d /Root 1 0 R /Info 8 0 R >>\n" % (len(objects) + 1)
pdf += b"startxref\n%d\n%%%%EOF\n" % xref

with open(path, "wb") as f:
    f.write(pdf)
print(f"Sample PDF created -> {path}")
PYEOF

ls -lh payment_advice.doc delivery_notice.pdf

Analyse the RTF File

# 1. True type — the extension says Word, the content says otherwise
file payment_advice.doc
# Expected: Rich Text Format data

# 2. Hash and metadata
sha256sum payment_advice.doc
exiftool -Author -Company -Title payment_advice.doc

# 3. olevba refuses it — and tells you which tool to use instead
olevba payment_advice.doc 2>&1 | tail -1

# 4. List embedded objects — the main danger in RTF files
rtfobj payment_advice.doc
# An empty table means no embedded objects. On a malicious file each row
# is an object; "Possibly an exploit" or an executable file name is a
# strong indicator.

# 5. RTF is text, so links can be read directly
grep -oE 'https?://[^ "}]+' payment_advice.doc
grep -c -E '\\(object|objdata)' payment_advice.doc      # 0 = no embedded-object keywords

Analyse the PDF File

# 1. True type, hash and metadata
file delivery_notice.pdf
sha256sum delivery_notice.pdf
exiftool -Author -Creator -Producer -CreateDate delivery_notice.pdf

# 2. Count the risky features (Kali and REMnux)
pdfid delivery_notice.pdf
# Read the lines that are NOT zero. In this file:
#   /OpenAction  1   something happens automatically when the file opens
#   /JS  /JavaScript  1   the file contains a script

# 3. Show the script and the link (Kali and REMnux)
pdf-parser -s JavaScript delivery_notice.pdf
pdf-parser -s URI delivery_notice.pdf

# 4. The same check on any Linux system, using strings
strings delivery_notice.pdf \
  | grep -oE '/(OpenAction|JS|JavaScript|URI|Launch|EmbeddedFile)\b' | sort | uniq -c
strings delivery_notice.pdf | grep -oE 'https?://[^ )]+'
pdfid keywordWhat it meansConcern
/OpenAction, /AAAn action runs automatically when the file or a page opensHigh when combined with a script or launch action
/JS, /JavaScriptThe file contains a scriptHigh — ordinary documents rarely need one
/LaunchThe file tries to start a programVery high
/EmbeddedFileAnother file is hidden inside the PDFExtract it and analyse it separately
/URIThe file contains a linkCheck the destination; the most common lure today
/ObjStmObjects are stored compressedCan hide the keywords above from simple searches

Analysis Checklist — RTF and PDF

Part E — QR Code Phishing (Quishing)

💡
What is quishing? The phishing link is delivered as a QR code inside an image instead of as text. This works for two reasons. Email filters that scan message text for bad links see only a picture. And the victim scans the code with a personal phone, which sits outside the company's web filtering and monitoring. A request to "scan this code" in an unexpected email is a red flag in itself.

Create the Sample Email

cd ~/email-threat-labs/lab4

# Make the QR image, then wrap it in an email
qrencode -s 6 -o qr.png "https://mfa-enrol.acme-corp-security.example/setup?u=sarah.okafor"
python3 - <<'PYEOF'
import os
from email.message import EmailMessage

lab = os.path.expanduser("~/email-threat-labs/lab4")
with open(os.path.join(lab, "qr.png"), "rb") as f:
    image = f.read()

msg = EmailMessage()
msg["Return-Path"] = "<security@acme-corp-security.example>"
msg["Received"] = ("from mail.acme-corp-security.example (mail.acme-corp-security.example [203.0.113.90]) "
                   "by mx1.acme-corp.example with ESMTPS id 3Kd8V5; "
                   "Tue, 18 Mar 2025 09:12:44 +0100")
msg["Message-ID"] = "<20250318081242.7730@mail.acme-corp-security.example>"
msg["Date"] = "Tue, 18 Mar 2025 09:12:42 +0100"
msg["From"] = '"Acme IT Security" <security@acme-corp-security.example>'
msg["To"] = "sarah.okafor@acme-corp.example"
msg["Subject"] = "Action required: re-enrol your authenticator app by Friday"
msg.set_content(
    "Hello Sarah,\n\n"
    "Our records show your multi-factor authentication enrolment expires\n"
    "this Friday. To keep access to email and payroll, scan the QR code in\n"
    "the attached image with your phone camera and follow the steps.\n\n"
    "Acme IT Security\n", cte="7bit")
msg.add_attachment(image, maintype="image", subtype="png", filename="mfa_enrolment.png")

out = os.path.join(lab, "qr_phish.eml")
with open(out, "wb") as f:
    f.write(msg.as_bytes())
os.remove(os.path.join(lab, "qr.png"))
print(f"Sample email created -> {out}")
PYEOF

Analyse It Without Using a Phone

# 1. Read the message and search it for links
sed '/^$/q' qr_phish.eml
grep -c 'https\?://' qr_phish.eml
# Expected: 0 — there is no link anywhere in the text for a filter to find

# 2. Extract the attached image
ripmime -i qr_phish.eml -d qr_extracted
ls qr_extracted
file qr_extracted/mfa_enrolment.png

# 3. Decode the QR code on your analysis machine — never with your phone
zbarimg --raw -q qr_extracted/mfa_enrolment.png

# 4. Record the result in defanged form
zbarimg --raw -q qr_extracted/mfa_enrolment.png | sed 's/^http/hxxp/; s/\./[.]/g'
🚩
Reading the result: the code leads to mfa-enrol.acme-corp-security.example. The registered domain is acme-corp-security.example — a different domain from Acme's real acme-corp.example, with a reassuring word added. The ?u=sarah.okafor part identifies the victim, so the attacker knows exactly who scanned it.

Analysis Checklist — QR Code

✅ Lab 4 Deliverable

  • Screenshot of ExifTool output with anomalies highlighted
  • olevba findings table with your interpretation of each flag
  • Link to the public sandbox report you studied, with a screenshot of its process tree
  • Final IOC list: SHA256 hash, IP address(es), domain(s), dropped file hashes — written in defanged form (see Lab 5)
  • Part D: the true type of payment_advice.doc, and the non-zero pdfid keywords for the PDF with your interpretation
  • Part E: the decoded QR address in defanged form and its registered domain
  • One-paragraph verdict: is this malicious, and what does it try to do?
Lab 5

BEC — Business Email Compromise

The finance department receives an urgent email appearing to come from the CFO requesting a $47,000 wire transfer. Your job is to determine whether it is legitimate — using header analysis, authentication checks, and company policy verification.

Security+ SY0-801 objectives: 2.3 (email and impersonation as threat vectors), 2.5 (spear phishing, whaling, impersonation), 4.1 (SPF, DKIM, DMARC, BIMI), 5.6 (BEC awareness).

💡
What is BEC? Business Email Compromise is a social engineering attack where criminals impersonate executives to trick employees into transferring money or sensitive data. It relies on psychological manipulation, not malware — making it harder for technical controls to catch. In exam terms, an email aimed at one named person is spear phishing; when the target or the person impersonated is a senior executive, as here, it is whaling.

Where to Get Sample .eml Files for Lab 5

📦 Option A — Create Two Realistic BEC .eml Files (Recommended · Zero Risk)

The commands below create two plain-text email files. The first is the wire-transfer request, sent from a lookalike domain the attacker registered. The second is a follow-up that forges the company's real domain. Comparing the two is the heart of this lab. Acme's real domain is acme-corp.example.

# Email 1 — sent from a lookalike domain
cat > ~/email-threat-labs/lab5/bec_wire_transfer.eml <<'EOF'
Return-Path: <j.whitfield@acme-corps.example>
Received: from mx1.acme-corp.example (mx1.acme-corp.example [192.0.2.25])
        by mailstore.acme-corp.example with ESMTPS id 7Fq2k1;
        Fri, 14 Mar 2025 16:47:05 +0100
Authentication-Results: mx1.acme-corp.example;
  spf=pass smtp.mailfrom=acme-corps.example;
  dkim=pass header.d=acme-corps.example;
  dmarc=pass (p=none) header.from=acme-corps.example
Received: from mail.acme-corps.example (mail.acme-corps.example [203.0.113.12])
        by mx1.acme-corp.example with ESMTPS id 4Zx9Q0;
        Fri, 14 Mar 2025 16:47:03 +0100
Message-ID: <20250314154701.GA12847@bulk-mailer.example.net>
Date: Fri, 14 Mar 2025 16:47:01 +0100
From: "James Whitfield" <j.whitfield@acme-corps.example>
Reply-To: j.whitfield.cfo@freemail.example
To: accounts.payable@acme-corp.example
Subject: URGENT -- Vendor Payment Required Today
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"

Hi Sarah,

I'm in a board meeting all afternoon and need you to process an urgent
wire transfer before close of business today. Our new vendor Apex
Logistics Solutions requires payment to initiate the Q2 contract.

Amount: $47,250.00
Bank: Example Bank (fictional)
Account: 0000-000-00   Routing: 000000000

Please action this immediately and do not cc anyone else -- this is
confidential until the contract is signed. I'll explain everything Monday.

James Whitfield
CFO, Acme Corporation
EOF

# Email 2 — forges the real company domain
cat > ~/email-threat-labs/lab5/bec_spoofed.eml <<'EOF'
Return-Path: <j.whitfield@acme-corp.example>
Received: from mx1.acme-corp.example (mx1.acme-corp.example [192.0.2.25])
        by mailstore.acme-corp.example with ESMTPS id 9Lm3p7;
        Fri, 14 Mar 2025 16:52:11 +0100
Authentication-Results: mx1.acme-corp.example;
  spf=fail (sender not permitted) smtp.mailfrom=acme-corp.example;
  dkim=none (message not signed);
  dmarc=fail (p=none) header.from=acme-corp.example
Received: from unknown (HELO mail.acme-corp.example) [203.0.113.12]
        by mx1.acme-corp.example with ESMTP id 2Bv8T4;
        Fri, 14 Mar 2025 16:52:09 +0100
Message-ID: <20250314155207.GA12901@bulk-mailer.example.net>
Date: Fri, 14 Mar 2025 16:52:07 +0100
From: "James Whitfield" <j.whitfield@acme-corp.example>
Reply-To: j.whitfield.cfo@freemail.example
To: accounts.payable@acme-corp.example
Subject: RE: URGENT -- Vendor Payment Required Today
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"

Sarah, following up on my last message. Has the payment gone out?
I need confirmation in the next 30 minutes.

James Whitfield
CFO, Acme Corporation
EOF

ls -l ~/email-threat-labs/lab5/

These files are entirely safe — plain text with no executable content.

📦 Option B — Phishing URL Feeds (Instructor-Supervised · Live Links)

OpenPhish publishes a free feed of currently active phishing links. Every line is a live malicious URL: never open one in a browser. The command below prints five of them in defanged form, so they cannot be clicked by accident. (PhishTank, used in older guides, has closed new registrations and its bulk download now needs a key.)

cd ~/email-threat-labs/lab5
curl -s https://openphish.com/feed.txt | head -5 \
  | sed 's/^http/hxxp/; s/\./[.]/g'

Note: the feed provides URLs, not full .eml files. Use them only for link-analysis practice with URLScan.io and VirusTotal.

📦 Option C — LetsDefend Email Analysis Challenges (Guided + Real .eml Files)

LetsDefend includes guided BEC and phishing scenarios with real downloadable .eml files and automatic answer scoring.

  1. Create a free account at letsdefend.io
  2. Go to Learning → SOC Analyst Path → Email Analysis
  3. Download the provided .eml file from any BEC challenge
  4. Save to ~/email-threat-labs/lab5/ and use the commands in Part B below
📦 Option D — Blue Team Labs Online (Free Graded Challenges)

BTLO has dedicated email forensics challenges that include .eml files containing spoofed BEC emails with real header data.

Website: blueteamlabs.online → Challenges → Email Analysis
Download the challenge file directly from your VM browser and save to ~/email-threat-labs/lab5/.

Part A — The Suspicious Email

Spot the Social Engineering — Tick Each Red Flag You See

Part B — Header Analysis

💡
What are email headers? Every email carries technical metadata — routing servers, authentication results, sending IPs, and reply-to addresses. Not all of it can be trusted. The sender writes most headers and can put anything in them: From, Reply-To, Message-ID, Date, and any Received lines below their own. The headers you can rely on are the ones your own mail servers added on arrival: the top Received lines and Authentication-Results.
📌
Read Received lines from the bottom up. Each server that handles a message adds its own line at the top, so the lowest line is the earliest hop and the highest is the last. The lowest line written by a server you trust shows the address the message really arrived from.

Analyse Headers Using the Linux Terminal

cd ~/email-threat-labs/lab5

# ── 1. View the complete raw email ───────────────────────────────
cat bec_wire_transfer.eml

# ── 2. Show headers only (everything before the first blank line) ─
sed '/^$/q' bec_wire_transfer.eml

# ── 3. Compare the sender fields in BOTH emails ──────────────────
grep -i "^From:\|^Reply-To:\|^Return-Path:" bec_wire_transfer.eml bec_spoofed.eml

# ── 4. Check SPF / DKIM / DMARC results in each email ────────────
grep -i -A 3 "^Authentication-Results" bec_wire_transfer.eml
grep -i -A 3 "^Authentication-Results" bec_spoofed.eml

# ── 5. Trace the route: read these from the BOTTOM line upwards ──
grep -i -A 2 "^Received:" bec_wire_transfer.eml

# ── 6. Extract all IP addresses from the headers ─────────────────
grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' \
  bec_wire_transfer.eml | sort -u

# ── 7. Is the sending IP a known Tor exit node? ──────────────────
curl -s "https://check.torproject.org/torbulkexitlist" | grep -c "^203.0.113.12$"
# Prints 0 here: 203.0.113.12 is a reserved documentation address.
# On a real case, 1 means the sender was hiding behind Tor.

# ── 8. Practise reading registration records on a real, safe target
whois google.com | grep -i "creation date\|registrar:"
whois 8.8.8.8    | grep -i "orgname\|country"
# On a real case you would look up the sender's domain and IP.
# A domain created days before the email arrived is a strong red flag.
📌
Beyond the exam: Defang indicators before you share them. When you write a suspicious URL, domain or IP into a ticket, chat or report, change it so that nobody can click it by accident and no software fetches it automatically: http becomes hxxp and each dot becomes [.]. Example: hxxp://198[.]51[.]100[.]47/pay. To convert one from the terminal: echo "http://198.51.100.47/pay" | sed 's/^http/hxxp/; s/\./[.]/g'

The Headers — What the Evidence Shows

Email 1 — the lookalike domain. Everything passes:

Authentication-Results: mx1.acme-corp.example;
  spf=pass smtp.mailfrom=acme-corps.example;    ← passes — for the ATTACKER'S domain
  dkim=pass header.d=acme-corps.example;        ← passes — signed with the attacker's own key
  dmarc=pass (p=none) header.from=acme-corps.example
Received: from mail.acme-corps.example (mail.acme-corps.example [203.0.113.12])
Message-ID: <20250314154701.GA12847@bulk-mailer.example.net>  ← different domain again (weak hint)
From: "James Whitfield" <j.whitfield@acme-corps.example>       ← one extra letter
Reply-To: j.whitfield.cfo@freemail.example                      ← free webmail
🚨
The most important lesson in this lab: "pass" does not mean "safe". SPF, DKIM and DMARC only prove that a message really came from the domain in its address. The attacker registered acme-corps.example, so they set up all three correctly and the email passes every check. Authentication tells you which domain sent the message; deciding whether that domain is the right one is still your job. The same is true when a criminal breaks into a real mailbox and sends from it.

Email 2 — the forged real domain. The attacker claims to be acme-corp.example itself, which they do not control:

Authentication-Results: mx1.acme-corp.example;
  spf=fail (sender not permitted) smtp.mailfrom=acme-corp.example;
  dkim=none (message not signed);
  dmarc=fail (p=none) header.from=acme-corp.example
Received: from unknown (HELO mail.acme-corp.example) [203.0.113.12]  ← same attacker IP
From: "James Whitfield" <j.whitfield@acme-corp.example>            ← looks perfect

What Each Result in Email 2 Means

❌ SPF Fail Server 203.0.113.12 is not in acme-corp.example's published list of authorised senders.
❌ DKIM None The message carries no signature at all. Only a system holding the domain's private key could have produced a valid one.
❌ DMARC Fail — but delivered Neither SPF nor DKIM passed for the domain in the From address. Acme's policy is p=none (monitor only), so the forgery was still delivered. A policy of p=quarantine or p=reject would have stopped it.
❌ Reply-To Hijack Any reply from Sarah goes to the attacker's webmail — the real CFO never sees her response.

SPF / DKIM / DMARC Quick Reference

ProtocolResultMeaningVerdict
SPFpassSending server is on the domain's authorised list✅ Came from that domain's servers
SPFfailSending server is NOT on the list❌ FAIL
SPFsoftfailNot on the list, but the domain asks receivers to be lenient⚠️ WARN
DKIMpassValid signature from the domain named in header.d✅ Unaltered, and signed by that domain
DKIMfailA signature is present but does not verify — altered in transit or forged❌ FAIL
DKIMnoneThe message was not signed at all⚠️ No evidence either way
DMARCpassSPF or DKIM passed for the same domain shown in the From address (this matching is called alignment)✅ The From domain is genuine
DMARCfailNeither passed for the From domain — the address is probably forged❌ FAIL
DMARC policyp=none / p=quarantine / p=rejectWhat the domain owner asks receivers to do with failures: only report them, send to spam, or refuseℹ️ Set by the domain owner

Part C — Verification Workflow & Verdict

💡
What is out-of-band verification? Contacting the requester through a completely independent channel — phone, in person, video call — that the attacker cannot intercept or fake. Never use contact details from inside the suspicious email itself. Be aware that criminals now also use deepfake voice and video to impersonate executives on calls, so a familiar voice on an incoming call is not proof — always call back on a number you already hold.

Verification Checklist — Do All of These Before Escalating

🔴 Verdict: Confirmed BEC Attempt

Email 1 comes from a lookalike domain (acme-corps.example) that passes authentication only because the attacker owns it. Email 2 forges the real domain and fails SPF and DMARC. Both arrive from the same IP address and both redirect replies to a free webmail account. Multiple social engineering techniques are present: urgency, secrecy, executive impersonation, unavailability excuse.

Do NOT action the wire transfer. Preserve all evidence. Report to IT Security, Finance leadership, and the real CFO immediately.

Part D — Email Authentication Records (SPF, DKIM, DMARC, BIMI)

💡
Where do the results in the header come from? In Part B you read spf=, dkim= and dmarc= results. The receiving server produced them by looking up records that the sending domain publishes in DNS. Anyone can read those records. In this part you will look them up for real domains, then judge Acme's own setup. This part needs an internet connection.
ControlWhere the record livesWhat it publishes
SPF
Sender Policy Framework
TXT record on the domain itselfThe list of servers allowed to send mail for the domain
DKIM
DomainKeys Identified Mail
TXT record at selector._domainkey.domainThe public key that verifies the signature on each message
DMARC
Domain-based Message Authentication, Reporting and Conformance
TXT record at _dmarc.domainWhat receivers should do when SPF and DKIM fail for the From address, and where to send reports
BIMI
Brand Indicators for Message Identification
TXT record at default._bimi.domainThe brand logo that mail apps may show beside authenticated messages

Look Up Real Records

# ── SPF: a TXT record on the domain that starts with v=spf1 ──────
dig +short TXT google.com | grep -i spf
# Typically: "v=spf1 include:_spf.google.com ~all"

# ── DMARC: always at _dmarc.<domain> ─────────────────────────────
dig +short TXT _dmarc.google.com
dig +short TXT _dmarc.cnn.com
# Look for the p= tag: none, quarantine or reject

# ── DKIM: needs the selector, found after s= in a message's
#    DKIM-Signature header. Gmail has used the selector 20230601;
#    selectors are rotated, so an empty answer means it has changed ─
dig +short TXT 20230601._domainkey.gmail.com
# Look for: v=DKIM1; k=rsa; p=<a long public key>

# ── BIMI: at default._bimi.<domain> ──────────────────────────────
dig +short TXT default._bimi.cnn.com
# Look for: v=BIMI1; l=<address of the logo>; a=<address of a certificate>

# ── A domain that publishes nothing returns nothing ──────────────
dig +short TXT _dmarc.acme-corp.example

How to Read the Records

RecordTagMeaning
SPFinclude: / ip4:Adds another organisation's servers, or a specific address range, to the allowed list
SPF~all / -allEverything else should be treated as suspicious (softfail) / rejected (fail)
DMARCp=Policy for failures: none (only report), quarantine (spam folder), reject (refuse)
DMARCrua=Address that receives daily summary reports — how a domain owner finds out who is sending in its name
DMARCsp= / pct=Policy for subdomains / percentage of failing mail the policy applies to
DKIMp=The public key. An empty p= means the key has been withdrawn
BIMIl= / a=Address of the logo file / address of the certificate proving the brand owns that logo
💡
How the four fit together: SPF and DKIM each check one thing. DMARC ties them to the address the reader actually sees and tells receivers what to do on failure. BIMI is the reward at the end: mail providers show a brand's logo only when the domain enforces DMARC (p=quarantine or p=reject), and the largest providers also require the certificate named in a=. BIMI does not block anything itself; it gives organisations a visible reason to finish their DMARC rollout.

Survey Three Organisations

Choose three real domains — for example your bank, your school or university, and a large online service. Run the SPF, DMARC and BIMI lookups for each and complete the record below.

Your survey
Domain 1: SPF ending (~all or -all) · DMARC policy (p=) · BIMI record present?
Domain 2: SPF ending (~all or -all) · DMARC policy (p=) · BIMI record present?
Domain 3: SPF ending (~all or -all) · DMARC policy (p=) · BIMI record present?
Which of the three could be forged most easily in the way Email 2 forged Acme? Why?

Assess Acme's Records

Acme Corporation's DNS administrator sends you the company's current records. Use them, and the two emails from Part B, to answer the questions.

acme-corp.example.            TXT  "v=spf1 include:_spf.mailhost.example ~all"
_dmarc.acme-corp.example.     TXT  "v=DMARC1; p=none; rua=mailto:dmarc@acme-corp.example"
(no DKIM record published)
(no BIMI record published)
Your assessment
Which record explains why Email 2 (the forged real domain) was delivered even though it failed?
What three changes would you recommend, and in what order?
Would those changes have stopped Email 1 (the lookalike domain)? Explain.
Name two controls that WOULD help against lookalike domains.

Model answer — check after completing your assessment:

  • The DMARC record: p=none asks receivers only to report failures, so the forgery was delivered. The SPF ~all ending is also lenient.
  • Recommended order: (1) turn on DKIM signing for all outgoing mail; (2) read the DMARC reports until every legitimate sender passes; (3) raise the policy in stages, p=quarantine then p=reject. Jumping straight to p=reject risks blocking the company's own mail.
  • No. Email 1 came from a different domain that the attacker owns and authenticated correctly. Acme's records only protect Acme's own domain name.
  • Against lookalikes: a banner on all mail from outside the organisation; monitoring for newly registered domains that resemble the company's; registering the obvious variants yourself; and, above all, the out-of-band payment verification process from Part C.
📌
Beyond the exam: Since 2024 Google and Yahoo have required anyone sending bulk email to their users to pass SPF and DKIM and to publish a DMARC record. This turned email authentication from a recommendation into a condition of getting mail delivered, and it is why you will find DMARC records on most large organisations' domains today.

✅ Lab 5 Deliverable

  • Terminal output showing SPF, DKIM, DMARC results for both .eml files, with one sentence explaining why Email 1 passes
  • List of social engineering techniques identified in the email body
  • The sending IP and lookalike domain, written in defanged form, and what you would check about each on a real case
  • Documented out-of-band verification steps taken
  • Part D: your three-domain survey and your assessment of Acme's records
  • Formal recommendation: block sender domain, notify CFO, file incident ticket, report to finance leadership
Lab 6

Full Triage Workflow

A complete phishing email has landed in the SOC queue. You have 90 minutes to produce a structured incident triage report covering all dimensions: sender analysis, link analysis, attachment forensics, affected users, and recommended response actions.

Security+ SY0-801 objectives: 2.5 (phishing, indicators of compromise), 4.1 (email security), 4.7 (incident response: identification, containment, notification, lessons learned), 5.6 (security awareness: training types, reporting, metrics).

Create the Sample Email

Run this once. It builds a harmless Word attachment, wraps it in a complete email with realistic headers, and saves it as helpdesk_phish.eml — the same form in which a reported email reaches a SOC analyst.

python3 - <<'PYEOF'
import datetime, os
from email.message import EmailMessage
from docx import Document

lab = os.path.expanduser("~/email-threat-labs/lab6")
os.makedirs(lab, exist_ok=True)
link = "https://microsoft365-secure-login.it-support-ticketing.example/verify?token=a7f3k"

# 1. Build the harmless attachment
tmp = os.path.join(lab, "tmp_attachment.docx")
doc = Document()
props = doc.core_properties
props.author = "win-build-07"
props.last_modified_by = "user"
props.created = datetime.datetime(2025, 3, 9, 23, 58, 12)
props.modified = datetime.datetime(2025, 3, 10, 0, 4, 51)
doc.add_heading("Account Activity Log", level=1)
doc.add_paragraph("Unusual sign-in activity was detected on your account.")
doc.add_paragraph("To view the full log, sign in here: " + link)
doc.save(tmp)

# 2. Build the email around it
msg = EmailMessage()
msg["Return-Path"] = "<noreply@it-support-ticketing.example>"
msg["Received"] = ("from mx1.yourcompany.example (mx1.yourcompany.example [192.0.2.25]) "
                   "by mailstore.yourcompany.example with ESMTPS id 5Hc1W9; "
                   "Mon, 10 Mar 2025 08:03:09 +0100")
msg["Authentication-Results"] = ("mx1.yourcompany.example; "
                                 "spf=pass smtp.mailfrom=it-support-ticketing.example; "
                                 "dkim=pass header.d=it-support-ticketing.example; "
                                 "dmarc=pass (p=none) header.from=it-support-ticketing.example")
msg["Received"] = ("from out.it-support-ticketing.example (out.it-support-ticketing.example [203.0.113.77]) "
                   "by mx1.yourcompany.example with ESMTPS id 8Rt6N2; "
                   "Mon, 10 Mar 2025 08:03:07 +0100")
msg["Message-ID"] = "<20250310070305.4471@out.it-support-ticketing.example>"
msg["Date"] = "Mon, 10 Mar 2025 08:03:05 +0100"
msg["From"] = '"IT-Helpdesk" <noreply@it-support-ticketing.example>'
msg["To"] = "all-staff@yourcompany.example"
msg["Subject"] = "Action Required: Your Microsoft 365 Account Will Be Suspended"
msg.set_content(
    "Dear Employee,\n\n"
    "Our systems have detected unusual sign-in activity on your Microsoft 365\n"
    "account. To prevent account suspension, you must verify your credentials\n"
    "within 24 hours.\n\n"
    "Click below to verify your account:\n" + link + "\n\n"
    "Your account activity log is attached for your review.\n\n"
    "Regards,\nIT Helpdesk Support Team\n", cte="7bit")
with open(tmp, "rb") as f:
    msg.add_attachment(f.read(), maintype="application",
                       subtype="vnd.openxmlformats-officedocument.wordprocessingml.document",
                       filename="AccountActivityLog_March2025.docx")
os.remove(tmp)

out = os.path.join(lab, "helpdesk_phish.eml")
with open(out, "wb") as f:
    f.write(msg.as_bytes())
print(f"Sample email created -> {out}")
PYEOF

The Email to Triage

🚨
Never visit a link from a suspicious email. This one uses a reserved example domain that does not exist, so scanners will find nothing; on a real case you would submit the link to URLScan.io and VirusTotal instead of opening it.
💡
Subdomain deception: The URL microsoft365-secure-login.it-support-ticketing.example looks like a Microsoft URL at a glance. But the actual registered domain is it-support-ticketing.example (attacker-owned). The registered domain is the name directly in front of the public ending — .com, .example, or a two-part ending such as .co.uk or .com.ng. Everything to the left of it is a subdomain, which the domain's owner can set to any text they like.
📌
Beyond the exam: URL scanners publish what you submit. URLScan.io scans are public unless you choose a private visibility setting, and links in real emails often contain a token that identifies the recipient (like ?token=a7f3k here). Before scanning a real link, remove personal tokens where you can and choose the unlisted or private option.

Linux Triage Commands for Lab 6

Work through these commands in order. Each step feeds into the next section of your report.

cd ~/email-threat-labs/lab6

# ── Step 1: Preserve the evidence — hash the email before touching it
sha256sum helpdesk_phish.eml

# ── Step 2: Read the headers and the authentication results ───────
sed '/^$/q' helpdesk_phish.eml
grep -i -A 3 "^Authentication-Results" helpdesk_phish.eml

# ── Step 3: Find the sending IP (lowest Received line) ────────────
grep -i -A 2 "^Received:" helpdesk_phish.eml

# ── Step 4: Pull every link out of the email, defanged ────────────
grep -oE 'https?://[^ ]+' helpdesk_phish.eml | sort -u \
  | sed 's/^http/hxxp/; s/\./[.]/g'

# ── Step 5: Extract the attachment without opening the email ──────
ripmime -i helpdesk_phish.eml -d extracted
ls extracted
cp extracted/AccountActivityLog_March2025.docx .

# ── Step 6: Hash the attachment and check its true type ───────────
sha256sum AccountActivityLog_March2025.docx
file      AccountActivityLog_March2025.docx

# ── Step 7: Metadata ──────────────────────────────────────────────
exiftool -Creator -LastModifiedBy -Company \
         -CreateDate -ModifyDate -Application \
         AccountActivityLog_March2025.docx

# ── Step 8: Macro check ───────────────────────────────────────────
olevba AccountActivityLog_March2025.docx

# ── Step 9: Look inside the document for links ────────────────────
unzip -l AccountActivityLog_March2025.docx
unzip -p AccountActivityLog_March2025.docx word/document.xml \
  | sed 's/<[^>]*>/ /g' | grep -oiE 'https?://[^ ]+'

# ── Step 10: On a real case — domain age and IP reputation ────────
# whois <sender-domain>          (creation date: days old = red flag)
# AbuseIPDB / VirusTotal lookups for the sending IP and the file hash
# These return nothing for this lab's reserved example names.

Triage Report Template

Fill in each field as you work through your analysis. This becomes your final submitted incident report.

1. Incident Metadata
Analyst name, date and time of triage, ticket / case reference
Email subject and original recipient(s)
How was this email reported? (User, gateway alert, automated rule)
2. Sender Analysis
Display name vs actual From address — match or mismatch?
Domain WHOIS: registration date, registrar, owner country
SPF / DKIM / DMARC results from email headers
Originating IP reputation — AbuseIPDB score, VirusTotal detections
Does the domain impersonate a known brand or your internal IT team?
3. Link / URL Analysis
Full URL extracted from email source (do NOT click — copy from raw headers)
Actual registered domain vs subdomain deception explained
URLScan.io result: redirect chain and final destination
Final landing page category: credential harvester, malware download, or other
VirusTotal URL scan result and detection count
Domain age — flag if registered within the last 30 days
4. Attachment Analysis
File name, true type (from file command), size, SHA256 hash
ExifTool metadata findings: Creator, Company, CreateDate anomalies
olevba macro indicators: AutoExec triggers, suspicious keywords, IOCs
oledump.py stream findings
Sandbox detonation verdict and key observed behaviours
Full IOC list: IPs, domains, dropped file hashes, registry keys
5. Affected Users & Scope
All recipients — check mail gateway delivery logs
Did anyone click the link? (Proxy / firewall / SIEM logs)
Did anyone open the attachment? (EDR telemetry)
Any credential submissions detected? (Identity provider anomalies)
Blast radius assessment: isolated user vs department-wide vs all-staff
6. Recommended Actions
Immediate: quarantine all copies of the email from inboxes
Block: sender domain, originating IP, phishing URL at gateway and firewall
Notify: affected users with clear instructions — do not click, do not open
Credential reset: for anyone who clicked or submitted credentials — change the password, sign out all active sessions, and check for new MFA devices and mailbox forwarding rules
Threat intel: add all IOCs to SIEM, EDR, and firewall blocklists
Escalation: at what point does this become a P1 incident requiring exec notification?
Lessons learned: what email gateway rule would have caught this?
7. Verdict
Classification: Malicious / Suspicious / Benign — with confidence level
Attack type: credential phishing, malware delivery, BEC, or combo attack
Threat actor indicators: any attribution signals from IOCs or TTPs

After the Incident — Awareness & Metrics

💡
Why this belongs in triage: an incident is not finished when the email is quarantined. Staff must be told what happened and what to do, and the organisation should learn who needs more help. Security awareness is an exam objective in its own right, and writing clear advice for non-technical staff is one of the most-used skills in a junior security role.

Step 1 — Write the Staff Advisory

The phishing email reached every member of staff. Write the notice that goes out to them. Keep it under 120 words, use plain language, and cover the four fields below. Do not include the live link; if you must show the address, defang it.

Staff advisory
What happened — one or two sentences, no jargon
How to recognise the email — subject line and sender as staff saw them
What to do if you only received it · if you clicked the link · if you entered your password
How to report it, and who to contact with questions

Step 2 — Measure a Phishing Simulation

Six weeks later, the security team sends a harmless practice phishing email to all staff and records what each department did. Create the results file and the report script, then run it.

cd ~/email-threat-labs/lab6

cat > campaign.csv <<'EOF'
department,emails_sent,clicked_link,entered_password,reported
Finance,40,14,6,3
Sales,60,9,2,21
IT,25,1,0,19
Customer Service,75,22,11,8
Management,12,5,3,1
EOF

cat > campaign_report.py <<'PYEOF'
import csv

rows = list(csv.DictReader(open("campaign.csv")))
print(f"{'Department':18}{'Sent':>6}{'Click %':>9}{'Password %':>12}{'Report %':>10}")
totals = {"emails_sent": 0, "clicked_link": 0, "entered_password": 0, "reported": 0}
for row in rows:
    sent = int(row["emails_sent"])
    for key in totals:
        totals[key] += int(row[key])
    print(f"{row['department']:18}{sent:>6}"
          f"{int(row['clicked_link']) / sent * 100:>8.0f}%"
          f"{int(row['entered_password']) / sent * 100:>11.0f}%"
          f"{int(row['reported']) / sent * 100:>9.0f}%")
sent = totals["emails_sent"]
print("-" * 55)
print(f"{'Whole company':18}{sent:>6}"
      f"{totals['clicked_link'] / sent * 100:>8.0f}%"
      f"{totals['entered_password'] / sent * 100:>11.0f}%"
      f"{totals['reported'] / sent * 100:>9.0f}%")
PYEOF

python3 campaign_report.py
Type of trainingWhen it is used
Initial / onboardingFor every new member of staff, before they are given access
OngoingRegular refreshers and practice exercises for everyone
TargetedExtra training for a group facing a specific risk, such as finance staff and payment fraud
CorrectiveFollow-up for individuals who fell for a simulation or caused an incident — supportive, never punitive
Your analysis of the simulation
Which department has the highest click rate? Which has the lowest report rate?
Which two departments would you give targeted training first, and on what topic? (Think about which group a BEC attacker would aim at.)
The company-wide click rate is 24% and the report rate is 25%. Which number matters more to the security team, and why?
One metric you would add to next quarter's managerial report
📌
Beyond the exam: Experienced teams watch the report rate more closely than the click rate. Somebody will always click; what limits the damage is how quickly the first person reports the email, because one report lets the team remove it from every inbox. Programmes that punish people for clicking teach them to stay silent. The aim is a culture in which reporting is quick, easy and thanked.

Model Answers — Lab 6

📖
Complete your own analysis and fill in the report above before reading the model answers below.

Key findings students should identify:

  • From domain it-support-ticketing.example is not a Microsoft domain and not the company's own domain — it is attacker-registered.
  • Authentication passes (SPF, DKIM and DMARC) — exactly as in Lab 5, because the attacker owns the sending domain. A pass is not a clean bill of health.
  • Sending IP: 203[.]0[.]113[.]77, read from the lowest Received line.
  • Subdomain trick: microsoft365-secure-login is merely a subdomain of the attacker's domain, designed to fool a quick visual scan.
  • On a real case, URLScan.io would show the final page is a Microsoft 365 login clone — a credential harvester. Many such pages now relay the victim's login to the real site in real time and steal the signed-in session, which defeats one-time codes; this is why the response must include signing out all sessions, not only a password change.
  • The attachment contains no macro — olevba is clean. It carries the same phishing link inside the document, a common way to get a link past email filters that only scan the message body. "No macro" does not mean "safe".
  • Metadata: Creator win-build-07 does not match an IT helpdesk, Company is blank, and the file was created at 23:58 the night before it was sent.
  • Sent to all-staff — high blast radius. This is an organisation-wide incident, not an individual phish. Priority triage required immediately.
  • Verdict: Malicious — credential phishing, with the link delivered twice (message body and attachment). Classify as P1 if any user clicked the link or entered credentials.
  • Simulation: Management has the highest click rate (42%) and, with Finance, the lowest report rate (8%). Finance and Management are the priority for targeted training on BEC and payment fraud: they are the groups an attacker impersonates and targets, and one in four managers entered a password. Customer Service follows, because of its size and 29% click rate.
  • Click or report? The report rate. IT's 76% shows what is achievable; raising the company figure from 25% shortens the time an attack stays unnoticed. A useful added metric is the time from delivery to the first report.
Resources

Practice Sample Sources & Quick-Reference

🚨
Safety reminder: Download all malware samples directly into your isolated Linux VM. Use password-protected zips (password: infected) as provided. Take a VM snapshot before every download.

Free Sample Sources — by Lab

SourceBest ForWhat You GetLinux Download
MalwareBazaar
bazaar.abuse.ch
Lab 4Thousands of real malicious Office docs with confirmed VBA macros. Free; needs an abuse.ch Auth-Key. Instructor-supervised.See Lab 4, Option C
PhishTank
phishtank.org
Labs 5, 6Community-verified phishing URLs. New registrations are closed and bulk downloads need a key, so use OpenPhish instead unless you already hold an account.VM browser — phishtank.org
OpenPhish
openphish.com
Labs 5, 6Real-time phishing feed. Plain text URL list, free tier.curl https://openphish.com/feed.txt
URLhaus
urlhaus.abuse.ch
Lab 6Malicious URL database, great for link and domain analysis. Uses the same abuse.ch Auth-Key.VM browser — urlhaus.abuse.ch
LetsDefend
letsdefend.io
All labsGuided challenges with real .eml files. Automatically graded. Free tier.VM browser — letsdefend.io
Blue Team Labs Online
blueteamlabs.online
Labs 5, 6Free email forensics challenges with downloadable .eml files and scoring.VM browser — blueteamlabs.online
theZoo (GitHub)
github.com/ytisf/theZoo
Lab 4 (advanced)Live malware repository. VM snapshot required before use.git clone https://github.com/ytisf/theZoo.git
CyberDefenders
cyberdefenders.org
All labsDFIR challenges including email forensics. Free and paid tiers.VM browser — cyberdefenders.org
TryHackMe
tryhackme.com
All labsPhishing Emails 1–5 learning path. Beginner friendly, browser-based.VM browser — tryhackme.com

Linux Command Quick-Reference Card

📋 File Inspection — Always Run These First

file suspicious.docx                          # True file type — never trust the extension
sha256sum suspicious.docx                     # SHA256 hash for VirusTotal lookup
md5sum    suspicious.docx                     # MD5 hash
strings   suspicious.doc  | head -80          # Readable strings (old .doc; a .docx is compressed)
unzip -l  suspicious.docx                     # List internal files (docx is a ZIP)

📋 Metadata Extraction

exiftool file.docx                            # All metadata
exiftool -Creator -Company -CreateDate file.docx # Key forensic fields (Word: Creator = author)
exiftool -csv *.docx                          # Batch — all files, CSV output

# Read metadata XML directly from the docx ZIP
unzip file.docx docProps/core.xml -p          # Print core.xml to stdout

🔬 Macro Analysis

olevba file.docx                              # Detect macros + flag suspicious keywords
olevba --decode --reveal file.docm            # Decode hidden strings and show the source
oledump.py file.docx                          # Low-level OLE stream dump
oledump.py -s A3 -v file.docx                 # Dump stream A3 (macro-flagged stream)
pdf-parser -s JavaScript file.pdf             # Find JavaScript in a PDF
pdfid file.pdf                                # Count risky PDF features (read the non-zero lines)
rtfobj file.rtf                               # List objects embedded in an RTF file
zbarimg --raw -q image.png                    # Decode a QR code without a phone

# Quick hunt for links and commands inside a .docx / .docm
unzip -p file.docx word/document.xml | sed 's/<[^>]*>/ /g' | grep -oiE '(https?://[^ ]+|powershell|cmd\.exe|wscript)'

📧 Header Analysis from the Terminal

cat email.eml                                 # Full raw email
sed '/^$/q' email.eml                         # Headers only (stop at first blank line)
grep -i -A 3 "^Authentication-Results" email.eml  # SPF / DKIM / DMARC results
grep -i -A 2 "^Received:" email.eml           # Route — read from the bottom up
ripmime -i email.eml -d extracted             # Extract attachments
grep -i "^From:\|Reply-To:\|Return-Path:" email.eml
grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}' email.eml | sort -u   # All IPs

# Email authentication records (SPF, DMARC, DKIM, BIMI)
dig +short TXT domain.com | grep -i spf
dig +short TXT _dmarc.domain.com
dig +short TXT SELECTOR._domainkey.domain.com
dig +short TXT default._bimi.domain.com

# Also paste full headers into these web tools:
# mxtoolbox.com/EmailHeaders
# toolbox.googleapps.com/apps/messageheader

🔗 Link & Domain Analysis

# Defang an indicator before sharing it
echo "http://198.51.100.47/pay" | sed 's/^http/hxxp/; s/\./[.]/g'

# Terminal WHOIS — domain registration date is key
whois suspicious-domain.com
whois 8.8.8.8                                 # IP WHOIS (who owns the address)

# Check Tor exit node list
curl -s "https://check.torproject.org/torbulkexitlist" | grep "IP_ADDRESS"

# Web tools — use in VM browser, paste URL — do NOT click
# urlscan.io           — redirect chain + screenshot of final page
# virustotal.com       — URL + file reputation + community scores
# whois.domaintools.com — full domain history

🔍 IP & Hash Reputation (API from Terminal)

# AbuseIPDB — check IP abuse score (free API key required)
curl -s "https://api.abuseipdb.com/api/v2/check?ipAddress=IP_HERE" \
  -H "Key: YOUR_KEY" \
  -H "Accept: application/json" | python3 -m json.tool

# ThreatFox — search IOC database (free abuse.ch Auth-Key required)
curl -s -X POST https://threatfox-api.abuse.ch/api/v1/ \
  -H "Auth-Key: YOUR_ABUSECH_KEY" \
  -d '{"query":"search_ioc","search_term":"IP_OR_DOMAIN_HERE"}' \
  | python3 -m json.tool

# VirusTotal file hash lookup (free API key required)
curl -s "https://www.virustotal.com/api/v3/files/SHA256_HERE" \
  -H "x-apikey: YOUR_VT_KEY" | python3 -m json.tool | grep -i "malicious\|verdict"

💣 Sandbox Detonation

# Cloud sandboxes — use in VM browser, upload file there
# any.run              — interactive live session; free submissions are PUBLIC
# hybrid-analysis.com  — automated deep report, free tier
# joesandbox.com       — advanced behavioural analysis
# app.any.run/tasks    — view public community detonation reports

# Local option: CAPEv2 (successor to Cuckoo) runs entirely on Linux
# See: github.com/kevoreilly/CAPEv2

Instructor Notes

  • Recommended VM distro: Kali Linux, to match the rest of the series. REMnux is a good alternative for an analysis-only class: ExifTool, oletools and oledump.py are pre-installed.
  • Lab 4 samples: The safe practice files (Option A) are the default and need no internet. For a supervised live-malware session, search MalwareBazaar with the tag VBA for macro-laden .doc and .docm files. The API needs a free abuse.ch Auth-Key; test downloads before class and hand out SHA256 hashes rather than having every student create a key.
  • Lab 5 .eml files: The two synthetic .eml files in this workbook are the safest option, and the contrast between them (lookalike domain passing authentication, forged domain failing) is the key teaching point. For more advanced classes, set up a local Postfix mail server inside the VM so students can send and receive real emails with crafted headers.
  • Lab 6: PhishTool's free tier lets you import real .eml files and automatically extracts headers, links, and attachments — useful as a comparison to the manual Linux commands.
  • Guided platform: LetsDefend.io has a dedicated Email Analysis learning path with 15+ real alert scenarios graded by an automated SOC scoring system. Assign it as supplemental homework after Lab 5.
  • TryHackMe: The Phishing Emails rooms (1–5) work entirely inside a browser and can be completed from within the Linux VM — good for students who want to go further.
  • IOC notebook: Encourage students to keep a personal ioc_log.csv in their VM across all labs — recording hash, domain, IP, and source for every IOC they find. This becomes a useful personal threat intel reference.