Skip to content
SecureKhan
Go back

How Email Works for Pentesters: SMTP, SPF, DKIM, DMARC Explained

How Email Works for Pentesters

TL;DR: Email uses SMTP for sending, POP3/IMAP for receiving. SPF, DKIM, and DMARC protect against spoofing. Understanding email flow is essential for phishing assessments and email security testing.


Table of Contents

Open Table of Contents

Quick Reference

Email Ports

PortProtocolSecurityUse
25SMTPNone/STARTTLSServer-to-server
465SMTPSImplicit TLSSubmission (deprecated)
587SMTPSTARTTLSClient submission
110POP3None/STARTTLSReceive mail
995POP3SImplicit TLSReceive mail (secure)
143IMAPNone/STARTTLSReceive mail
993IMAPSImplicit TLSReceive mail (secure)

Essential Commands

CommandPurposeExample
dig TXTQuery SPF/DKIM/DMARCdig TXT example.com
nmap smtpSMTP enumerationnmap --script smtp-* -p 25 target
swaksSMTP testingswaks --to test@target.com
telnetManual SMTPtelnet mail.target.com 25
mxtoolboxOnline email testingmxtoolbox.com

Email Security Records

RecordDNS TypePurposeExample
SPFTXTAuthorize sendersv=spf1 include:_spf.google.com -all
DKIMTXTSign messagesselector._domainkey.example.com
DMARCTXTPolicy enforcement_dmarc.example.com
MXMXMail server10 mail.example.com

Why Email Matters for Pentesters

Phishing: The #1 Attack Vector

Year% of Breaches Starting with Phishing
202036%
202141%
202239%
202344%

What Pentesters Test

  1. Email spoofing - Can we send as target domain?
  2. SPF/DKIM/DMARC - Are protections configured correctly?
  3. SMTP enumeration - User harvesting, version info
  4. Phishing simulation - Social engineering assessments
  5. Email headers - Information disclosure
  6. Open relays - Unauthorized mail forwarding

Real-World Email Attacks

AttackTechniqueImpact
BEC (Business Email Compromise)Domain spoofing$26B+ losses (FBI 2023)
Credential PhishingFake login pagesAccount takeover
Malware DeliveryMalicious attachmentsSystem compromise
Supply ChainVendor impersonationMulti-org breach

Email Architecture

TL;DR: Email travels from sender’s client → sender’s server → recipient’s server → recipient’s client.

Email Flow

┌──────────────┐                                    ┌──────────────┐
│   Sender     │                                    │  Recipient   │
│   (Alice)    │                                    │    (Bob)     │
│              │                                    │              │
│ alice@a.com  │                                    │ bob@b.com    │
└──────┬───────┘                                    └──────▲───────┘
       │                                                   │
       │ 1. Compose & Send                                 │ 6. Retrieve
       │    (SMTP:587)                                     │    (IMAP:993)
       │                                                   │
       ▼                                                   │
┌──────────────┐                                    ┌──────────────┐
│  Mail Server │   2. SMTP Relay    ┌───────────►  │  Mail Server │
│   (a.com)    │─────────────────────│             │    (b.com)   │
│              │                     │             │              │
│  MTA + MSA   │   3. DNS MX Lookup  │             │   MTA + MDA  │
└──────────────┘      for b.com ─────┘             └──────────────┘


                    ┌──────────┐
                    │   DNS    │
                    │  Server  │
                    └──────────┘
                    Returns: MX 10 mail.b.com

Email Components

ComponentFull NameRole
MUAMail User AgentEmail client (Outlook, Gmail web)
MSAMail Submission AgentAccepts mail from MUA
MTAMail Transfer AgentRoutes mail between servers
MDAMail Delivery AgentDelivers to mailbox
MXMail ExchangerDNS record pointing to mail server

Complete Email Journey

1. Alice writes email to bob@b.com
2. Alice's MUA connects to MSA (SMTP:587, authenticated)
3. MSA accepts and forwards to MTA
4. MTA queries DNS for b.com MX record
5. DNS returns: MX 10 mail.b.com
6. MTA connects to mail.b.com (SMTP:25)
7. Remote MTA verifies SPF, DKIM, DMARC
8. MDA stores in Bob's mailbox
9. Bob's MUA retrieves via IMAP:993

SMTP Deep Dive

TL;DR: SMTP (Simple Mail Transfer Protocol) is the protocol for sending email. Understanding SMTP commands is essential for testing.

SMTP Conversation

┌────────────────────────────────────────────────────────────────────┐
│                    SMTP Session Example                            │
├────────────────────────────────────────────────────────────────────┤
│                                                                    │
│  Client connects to server:25                                      │
│                                                                    │
│  S: 220 mail.example.com ESMTP Postfix                            │
│  C: EHLO sender.com                                               │
│  S: 250-mail.example.com                                          │
│  S: 250-PIPELINING                                                │
│  S: 250-SIZE 10240000                                             │
│  S: 250-STARTTLS                                                  │
│  S: 250-AUTH PLAIN LOGIN                                          │
│  S: 250 8BITMIME                                                  │
│  C: MAIL FROM:<alice@sender.com>                                  │
│  S: 250 Ok                                                        │
│  C: RCPT TO:<bob@example.com>                                     │
│  S: 250 Ok                                                        │
│  C: DATA                                                          │
│  S: 354 End data with <CR><LF>.<CR><LF>                          │
│  C: Subject: Test Email                                           │
│  C: From: alice@sender.com                                        │
│  C: To: bob@example.com                                           │
│  C:                                                               │
│  C: This is the email body.                                       │
│  C: .                                                             │
│  S: 250 Ok: queued as 12345                                       │
│  C: QUIT                                                          │
│  S: 221 Bye                                                       │
│                                                                    │
└────────────────────────────────────────────────────────────────────┘

SMTP Commands

CommandPurposeExample
HELOIdentify sender (basic)HELO sender.com
EHLOIdentify sender (extended)EHLO sender.com
MAIL FROMSpecify senderMAIL FROM:<alice@sender.com>
RCPT TOSpecify recipientRCPT TO:<bob@target.com>
DATABegin message contentDATA
QUITEnd sessionQUIT
VRFYVerify user existsVRFY bob
EXPNExpand mailing listEXPN admins
RSETReset sessionRSET
AUTHAuthenticateAUTH PLAIN ...
STARTTLSUpgrade to TLSSTARTTLS

SMTP Response Codes

CodeMeaningExample
2XXSuccess250 Ok
3XXContinue354 Start mail input
4XXTemporary failure450 Mailbox unavailable
5XXPermanent failure550 User not found

SMTP Vulnerabilities

VulnerabilityImpactCheck
Open RelaySend spam through serverMAIL FROM external, RCPT TO external
VRFY enabledUser enumerationVRFY username
EXPN enabledList enumerationEXPN mailinglist
No STARTTLSTraffic interceptionCheck EHLO response
Weak AUTHCredential brute forceTest AUTH mechanisms
AttackDetectDefend
Open relay abuseMonitor outbound volumeRequire authentication
User enumerationLog VRFY/RCPT attemptsDisable VRFY/EXPN
Credential stuffingMonitor failed authsRate limiting, MFA
SpoofingCheck SPF/DKIM/DMARCImplement all three
SMTP Testing Commands
# === Manual SMTP Testing ===

# Connect with telnet
telnet mail.target.com 25

# Connect with openssl (TLS)
openssl s_client -connect mail.target.com:465
openssl s_client -starttls smtp -connect mail.target.com:587

# === Test for Open Relay ===

# Using telnet
telnet mail.target.com 25
EHLO test.com
MAIL FROM:<test@external.com>
RCPT TO:<anyone@another-external.com>
# If "250 Ok" - OPEN RELAY!

# Using nmap
nmap --script smtp-open-relay -p 25 mail.target.com

# === User Enumeration ===

# VRFY method
telnet mail.target.com 25
VRFY admin
VRFY bob
VRFY nonexistent

# RCPT TO method (more reliable)
MAIL FROM:<test@test.com>
RCPT TO:<admin@target.com>     # 250 = exists
RCPT TO:<nonexistent@target.com>  # 550 = doesn't exist

# Using smtp-user-enum
smtp-user-enum -M VRFY -U users.txt -t mail.target.com
smtp-user-enum -M RCPT -U users.txt -t mail.target.com

# === Using swaks ===

# Basic send test
swaks --to test@target.com --server mail.target.com

# Test authentication
swaks --to test@target.com --server mail.target.com \
    --auth LOGIN --auth-user user --auth-password pass

# Test with custom from
swaks --to victim@target.com --from ceo@target.com \
    --server mail.target.com

# === Nmap Scripts ===

# All SMTP scripts
nmap --script "smtp-*" -p 25,465,587 mail.target.com

# Specific scripts
nmap --script smtp-commands -p 25 mail.target.com
nmap --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY} -p 25 mail.target.com
nmap --script smtp-vuln-cve2010-4344 -p 25 mail.target.com

POP3 and IMAP

TL;DR: POP3 downloads and (usually) deletes email. IMAP keeps email on server with folder sync. Both used for retrieving mail.

POP3 vs IMAP

FeaturePOP3IMAP
Email storageDownloads to clientStays on server
Multiple devicesPoor supportFull sync
FoldersNo supportFull support
SearchLocal onlyServer-side
BandwidthDownload allDownload on demand
OfflineFull accessLimited
Ports110 (plain), 995 (SSL)143 (plain), 993 (SSL)

POP3 Commands

CommandPurpose
USERSpecify username
PASSSpecify password
STATMailbox statistics
LISTList messages
RETRRetrieve message
DELEDelete message
QUITEnd session

IMAP Commands

CommandPurpose
LOGINAuthenticate
SELECTSelect mailbox
FETCHRetrieve message
SEARCHSearch messages
STOREModify flags
LOGOUTEnd session
POP3/IMAP Testing Commands
# === POP3 Testing ===

# Connect
telnet mail.target.com 110
# or with SSL
openssl s_client -connect mail.target.com:995

# Authenticate
USER testuser
PASS testpass

# List messages
STAT
LIST

# Retrieve message
RETR 1

# === IMAP Testing ===

# Connect
telnet mail.target.com 143
# or with SSL
openssl s_client -connect mail.target.com:993

# Authenticate
a1 LOGIN testuser testpass

# List folders
a2 LIST "" "*"

# Select inbox
a3 SELECT INBOX

# Fetch message
a4 FETCH 1 FULL

# Search
a5 SEARCH FROM "sender@example.com"

# === Nmap Scripts ===

nmap --script "pop3-*" -p 110,995 mail.target.com
nmap --script "imap-*" -p 143,993 mail.target.com

# Brute force
nmap --script pop3-brute -p 110 mail.target.com
nmap --script imap-brute -p 143 mail.target.com

Email Headers Analysis

TL;DR: Email headers reveal the full path an email took, authentication results, and potential forgery indicators.

Key Headers

HeaderPurposeSecurity Relevance
FromDisplayed senderCan be spoofed
Return-PathEnvelope senderUsed for SPF
ReceivedRouting pathTrace email path
Message-IDUnique identifierIdentify duplicates
X-Originating-IPSender’s IPGeographic info
Authentication-ResultsSPF/DKIM/DMARC resultsVerify authenticity
DKIM-SignatureDigital signatureVerify integrity
X-MailerClient softwareReconnaissance

Reading Received Headers

Received headers are read BOTTOM-UP (oldest first):

Received: from mail.final.com (mail.final.com [1.2.3.4])    ← Most recent
        by recipient-server.com (Postfix)
        for <bob@recipient.com>; Mon, 1 Jan 2024 12:00:00 +0000

Received: from mail.middle.com (mail.middle.com [5.6.7.8])  ← Middle hop
        by mail.final.com (Postfix)
        for <bob@recipient.com>; Mon, 1 Jan 2024 11:59:00 +0000

Received: from sender-server.com (sender-server.com [9.10.11.12]) ← First hop
        by mail.middle.com (Postfix)
        for <bob@recipient.com>; Mon, 1 Jan 2024 11:58:00 +0000

Reading path: sender-server.com → mail.middle.com → mail.final.com → recipient

Authentication-Results Header

Authentication-Results: mx.recipient.com;
    spf=pass (sender IP is 1.2.3.4) smtp.mailfrom=sender.com;
    dkim=pass (signature was verified) header.d=sender.com;
    dmarc=pass (p=REJECT sp=REJECT) header.from=sender.com

Breakdown:
- spf=pass    → Email came from authorized server
- dkim=pass   → Email wasn't modified in transit
- dmarc=pass  → Domain's policy was satisfied
Header Analysis Commands
# View raw email headers (in email client)
# Gmail: Show original
# Outlook: View source

# Analyze with online tools
# - mxtoolbox.com/EmailHeaders.aspx
# - mailheader.org

# Command line analysis
# Save email as .eml file, then:
cat email.eml | grep -E "^(From|To|Subject|Received|Authentication|DKIM|Return-Path|X-)"

# Parse received headers
cat email.eml | grep "^Received:" | tac

# Check for spoofing indicators
cat email.eml | grep -E "(Reply-To|Return-Path|From)"
# If From and Return-Path domains differ - suspicious!

SPF (Sender Policy Framework)

TL;DR: SPF is a DNS record that lists which servers can send email for a domain. Receiving servers check if the sender’s IP is authorized.

How SPF Works

1. Sender sends email claiming to be from example.com

2. Receiving server checks SPF:
   ┌──────────────┐
   │ DNS Query:   │
   │ TXT example. │──────────► DNS Server
   │ com          │
   └──────────────┘                 │

                              ┌─────▼─────┐
                              │ SPF Record│
                              │ v=spf1    │
                              │ ip4:1.2.3.│
                              │ 4 -all    │
                              └───────────┘

3. Server checks if sender IP matches record:
   - Sender IP: 1.2.3.4 → PASS
   - Sender IP: 9.9.9.9 → FAIL

SPF Syntax

v=spf1 ip4:192.168.1.0/24 include:_spf.google.com -all
│      │                   │                        │
│      │                   │                        └── Qualifier
│      │                   └── Include another SPF record
│      └── Allow this IP range
└── SPF version (required)

SPF Mechanisms

MechanismPurposeExample
ip4IPv4 address/rangeip4:192.168.1.1
ip6IPv6 address/rangeip6:2001:db8::/32
aA record of domaina:mail.example.com
mxMX recordsmx
includeInclude another SPFinclude:_spf.google.com
allMatch everything else-all
existsCheck DNS existenceexists:%{i}.bl.example.com

SPF Qualifiers

QualifierMeaningResult
+ (default)PassAccept
-FailReject
~Soft failAccept but mark
?NeutralAccept

Common SPF Records

# Google Workspace
v=spf1 include:_spf.google.com ~all

# Microsoft 365
v=spf1 include:spf.protection.outlook.com -all

# Multiple providers
v=spf1 include:_spf.google.com include:sendgrid.net ip4:1.2.3.4 -all

# Strict (no email from this domain)
v=spf1 -all

SPF Vulnerabilities

IssueRiskCheck
No SPF recordSpoofing possibledig TXT domain.com
~all instead of -allSoft fail allows deliveryCheck qualifier
Too many includes>10 DNS lookups = permerrorCount mechanisms
No SPF on subdomainsSubdomain spoofingCheck sub.domain.com
AttackDetectDefend
Spoof without SPFCheck for TXT recordPublish SPF
Exploit ~allCheck SPF qualifierUse -all
Subdomain spoofingCheck all subdomainsSPF on all subdomains
SPF Testing Commands
# Query SPF record
dig TXT example.com +short | grep spf

# Detailed query
dig TXT example.com

# Check subdomain SPF
dig TXT mail.example.com +short

# Count DNS lookups (max 10)
# Use online tools like mxtoolbox.com/spf.aspx

# Test SPF from command line
# Install: pip install pyspf
spfquery -i 1.2.3.4 -s sender@example.com -h mail.example.com

# Using kitterman.com/spf/validate.html for validation

DKIM (DomainKeys Identified Mail)

TL;DR: DKIM adds a digital signature to emails. The receiving server verifies the signature using a public key in DNS.

How DKIM Works

Sending Server:
┌─────────────────────────────────────────────────────┐
│ 1. Compose email                                    │
│ 2. Generate hash of headers + body                  │
│ 3. Sign hash with private key                       │
│ 4. Add DKIM-Signature header                        │
└─────────────────────────────────────────────────────┘

                    │ Email with signature

Receiving Server:
┌─────────────────────────────────────────────────────┐
│ 1. Extract DKIM-Signature                           │
│ 2. Query DNS for public key                         │
│    (selector._domainkey.domain.com)                 │
│ 3. Verify signature                                 │
│ 4. If valid, email wasn't modified                  │
└─────────────────────────────────────────────────────┘

DKIM Signature Header

DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
    d=example.com; s=selector1;
    h=from:to:subject:date:message-id;
    bh=base64-body-hash=;
    b=base64-signature-here=

Breakdown:
v=1          → DKIM version
a=rsa-sha256 → Algorithm
c=relaxed    → Canonicalization (how whitespace is handled)
d=example.com→ Signing domain
s=selector1  → Selector (to find public key)
h=from:to:...→ Headers that were signed
bh=...       → Body hash
b=...        → Signature

DKIM DNS Record

DNS Query: selector1._domainkey.example.com TXT

Response:
v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...

Breakdown:
v=DKIM1 → Version
k=rsa   → Key type
p=...   → Public key (base64)

DKIM Vulnerabilities

IssueRiskCheck
No DKIMNo integrity checkQuery _domainkey
Weak key (<1024 bit)Key factoringCheck key size
Key not rotatedCompromised keyCheck key age
Signature missing headersPartial protectionCheck h= tag
AttackDetectDefend
Modify unsigned headersCheck h= tagSign all headers
Replay signed emailCheck Message-IDInclude date in signature
Key compromiseMonitor DKIM failuresRegular key rotation
DKIM Testing Commands
# Find DKIM selector (look at email headers)
# DKIM-Signature: ... s=selector1 ...

# Query DKIM record
dig TXT selector1._domainkey.example.com +short

# Common selectors to try
for selector in default google selector1 selector2 s1 s2 dkim; do
    echo "Trying: $selector"
    dig TXT ${selector}._domainkey.example.com +short
done

# Verify DKIM key size
dig TXT selector1._domainkey.example.com | grep -o 'p=[^;]*' | \
    sed 's/p=//' | base64 -d | openssl rsa -pubin -text -noout 2>/dev/null | \
    grep "Public-Key"

# Online validation
# - mxtoolbox.com/dkim.aspx
# - mail-tester.com

DMARC (Domain-based Message Authentication)

TL;DR: DMARC tells receiving servers what to do when SPF and DKIM fail, and where to send reports.

How DMARC Works

┌─────────────────────────────────────────────────────────────────┐
│                     DMARC Decision Flow                          │
└─────────────────────────────────────────────────────────────────┘


                    ┌──────────────────┐
                    │ Check SPF        │
                    │ (envelope from)  │
                    └────────┬─────────┘

              ┌──────────────┴──────────────┐
              │                             │
         SPF Pass                      SPF Fail
              │                             │
              ▼                             ▼
    ┌──────────────────┐         ┌──────────────────┐
    │ SPF Aligned?     │         │ Check DKIM       │
    │ (domain matches  │         │                  │
    │  header From)    │         └────────┬─────────┘
    └────────┬─────────┘                  │
             │                 ┌──────────┴──────────┐
       ┌─────┴─────┐           │                     │
       │           │      DKIM Pass             DKIM Fail
    Aligned    Not Aligned     │                     │
       │           │           ▼                     ▼
       │           │  ┌──────────────────┐   ┌──────────────┐
       │           │  │ DKIM Aligned?    │   │ DMARC FAIL   │
       │           │  └────────┬─────────┘   │ Apply policy │
       │           │           │             └──────────────┘
       │           │     ┌─────┴─────┐
       │           │  Aligned    Not Aligned
       │           │     │           │
       ▼           ▼     ▼           ▼
    ┌─────────────────────────────────────────────────────┐
    │              DMARC PASS           │   DMARC FAIL    │
    │    (at least one aligned pass)    │  Apply policy   │
    └─────────────────────────────────────────────────────┘

DMARC Record

_dmarc.example.com TXT "v=DMARC1; p=reject; rua=mailto:dmarc@example.com; ruf=mailto:forensics@example.com; pct=100"

Breakdown:
v=DMARC1        → Version
p=reject        → Policy (none, quarantine, reject)
rua=mailto:...  → Aggregate report address
ruf=mailto:...  → Forensic report address
pct=100         → Percentage of emails to apply policy
sp=reject       → Subdomain policy
adkim=s         → DKIM alignment (s=strict, r=relaxed)
aspf=s          → SPF alignment (s=strict, r=relaxed)

DMARC Policies

PolicyActionUse Case
p=noneMonitor onlyInitial deployment
p=quarantineMark as spamTesting phase
p=rejectBlock emailFull enforcement

DMARC Vulnerabilities

IssueRiskCheck
No DMARCNo policy enforcementdig TXT _dmarc.domain.com
p=noneNo protection, just monitoringCheck policy tag
No subdomain policySubdomain spoofingCheck sp= tag
Low pctPartial protectionCheck pct value
AttackDetectDefend
Spoof with p=noneCheck DMARC policySet p=reject
Subdomain spoofingCheck sp= tagSet sp=reject
Lookalike domainMonitor reportsImplement DMARC
DMARC Testing Commands
# Query DMARC record
dig TXT _dmarc.example.com +short

# Check subdomain DMARC (inherits from parent if not set)
dig TXT _dmarc.sub.example.com +short

# Validate DMARC record
# Online: mxtoolbox.com/dmarc.aspx
# Online: dmarcanalyzer.com/dmarc/dmarc-record-check

# Full email authentication check
# Send test email to: check-auth@verifier.port25.com
# Or: ping@tools.mxtoolbox.com

Email Spoofing Techniques

TL;DR: Email spoofing sends emails with forged sender addresses. Success depends on target’s email security configuration.

Spoofing Decision Tree

Can we spoof @target.com?

1. Check SPF
   └── No SPF? → Likely spoofable
   └── SPF exists? → Check qualifier
       └── ~all (softfail)? → May work (marked suspicious)
       └── -all (fail)? → Check DMARC

2. Check DMARC
   └── No DMARC? → SPF softfail works
   └── p=none? → Spoofable (just monitored)
   └── p=quarantine? → Goes to spam
   └── p=reject? → Blocked

3. Check DKIM
   └── No DKIM? → No signature verification
   └── DKIM exists? → Email modification detected

4. Subdomain check
   └── Check sub.target.com (often unprotected)

Spoofing Techniques

TechniqueDescriptionBypasses
Direct spoofingSend as @target.comNo SPF/DMARC
Subdomain spoofingSend as @sub.target.comMissing subdomain records
Display name spoofing”CEO” attacker@evil.comUser awareness
Lookalike domain@target-corp.comTechnical controls
Reply-to manipulationFrom: legit, Reply-To: evilUser awareness
Header injectionMultiple From headersSome mail clients

Testing Checklist

Spoofing Test Commands
# === Reconnaissance ===

# Full email security check
echo "Checking email security for target.com"
echo "=== MX Records ==="
dig MX target.com +short

echo "=== SPF Record ==="
dig TXT target.com +short | grep spf

echo "=== DMARC Record ==="
dig TXT _dmarc.target.com +short

echo "=== DKIM (try common selectors) ==="
for s in default selector1 selector2 google s1 s2 k1; do
    result=$(dig TXT ${s}._domainkey.target.com +short 2>/dev/null)
    if [ -n "$result" ]; then
        echo "Found: ${s}._domainkey.target.com"
        echo "$result"
    fi
done

# === Spoofing Tests (authorized testing only) ===

# Using swaks to test spoofing
swaks --to victim@target.com \
      --from ceo@target.com \
      --server mail.target.com \
      --header "Subject: Urgent Request"

# Test with external SMTP (if target accepts)
swaks --to victim@target.com \
      --from ceo@target.com \
      --server smtp.yourserver.com

# Display name spoofing
swaks --to victim@target.com \
      --from '"John Smith CEO" <innocent@attacker.com>' \
      --server smtp.yourserver.com

# === Using SET (Social Engineering Toolkit) ===
# setoolkit → Social-Engineering Attacks → Mass Mailer Attack

# === Using Gophish (for phishing assessments) ===
# Configure sending profile with SMTP server
# Create email template
# Launch campaign

Email Security Testing

Comprehensive Testing Workflow

1. DNS Reconnaissance

   ├── MX records
   ├── SPF record
   ├── DKIM selectors
   └── DMARC policy


2. SMTP Enumeration

   ├── Banner grabbing
   ├── Supported commands
   ├── User enumeration
   └── Open relay test


3. Authentication Testing

   ├── SPF validation
   ├── DKIM verification
   └── DMARC alignment


4. Spoofing Tests

   ├── Direct spoofing
   ├── Subdomain spoofing
   └── Display name spoofing


5. Report Findings

Testing Checklist

TestToolPass Criteria
MX records existdig MXRecords returned
SPF configureddig TXTv=spf1 present
SPF uses -alldig TXTEnds with -all
DKIM configureddig TXT selector._domainkeyKey present
DKIM key ≥1024 bitopensslRSA 1024+
DMARC configureddig TXT _dmarcv=DMARC1 present
DMARC p=rejectdig TXT _dmarcp=reject
No open relaynmap scriptRelay denied
VRFY disabledSMTP test502/252 response
STARTTLS supportedSMTP EHLOSTARTTLS in response

Tools Reference

Command Line Tools

ToolPurposeInstall
swaksSwiss army knife for SMTPapt install swaks
smtp-user-enumUser enumerationapt install smtp-user-enum
nmap smtp scriptsSMTP scanningBuilt into nmap
dnsreconDNS enumerationapt install dnsrecon
emkei.czOnline spoofing testWeb-based

Phishing Platforms

ToolPurposeType
GophishPhishing campaignsOpen source
King PhisherPhishing campaignsOpen source
SETSocial engineeringOpen source
Evilginx2Phishing + MFA bypassOpen source

Online Tools

ToolURLUse
MXToolboxmxtoolbox.comFull email check
Mail Testermail-tester.comDeliverability test
DMARC Analyzerdmarcanalyzer.comDMARC check
Learn DMARClearndmarc.comInteractive learning

Practice Labs

Beginner

ResourceFocus
TryHackMe - PhishingEmail basics
HackTheBox AcademySMTP enumeration
OverTheWireNetwork services

Intermediate

ResourceFocus
VulnHub mail machinesFull exploitation
Gophish labCampaign setup
Custom SMTP serverUnderstand protocols

Set Up Practice Environment

# Install local mail server for testing
# Using hMailServer (Windows) or Postfix (Linux)

# Postfix quick setup
apt install postfix
# Choose "Internet Site"
# Configure /etc/postfix/main.cf

# Test locally
swaks --to test@localhost --server localhost

# Set up Gophish for phishing practice
wget https://github.com/gophish/gophish/releases/latest/download/gophish-linux-64bit.zip
unzip gophish-linux-64bit.zip
./gophish
# Access at https://localhost:3333

Glossary

TermDefinition
BECBusiness Email Compromise
DKIMDomainKeys Identified Mail (signature)
DMARCDomain-based Message Authentication
Envelope FromMAIL FROM address (for SPF)
Header FromDisplayed From address
IMAPInternet Message Access Protocol
MDAMail Delivery Agent
MTAMail Transfer Agent
MUAMail User Agent (client)
MXMail Exchanger record
Open RelayServer that forwards mail for anyone
POP3Post Office Protocol v3
SelectorDKIM identifier in DNS
SMTPSimple Mail Transfer Protocol
SPFSender Policy Framework
STARTTLSUpgrade connection to TLS

What’s Next?

Now that you understand email security:

TopicDescriptionLink
DNS Deep DiveMX and TXT recordsDNS Guide
Social EngineeringPhishing techniquesComing Soon
Web App PentestingWeb-based attacksWeb App Guide
Authentication FlowsAuth mechanismsAuth Flows Guide

Summary

Email security is critical for penetration testing:

  1. SMTP - Know the protocol, test for open relay, user enumeration
  2. SPF - Check for existence and strict qualifier (-all)
  3. DKIM - Verify signature and key strength
  4. DMARC - Check policy enforcement (p=reject)
  5. Headers - Analyze for authentication results and routing
  6. Spoofing - Test based on security configuration

Key Findings to Report:


Found this guide helpful? Check out the other posts in the SecureKhan penetration testing series.


Share this post on:

Previous Post
TCP/IP Deep Dive for Pentesters: Flags, Attacks & Analysis
Next Post
Authentication Flows & Vulnerabilities: A Visual Whiteboard Guide