#
Man-in-the-Middle (MitM) Attacks
CRITICAL SEVERITY NETWORK ATTACK EAVESDROPPING
#
Overview
A Man-in-the-Middle (MitM) attack occurs when an attacker secretly intercepts and potentially alters communications between two parties who believe they are directly communicating with each other.
In One Sentence
A digital eavesdropper secretly sits between you and the website, reading and potentially changing everything you send or receive.
#
Simple Explanation
#
Real-World Analogy
Imagine you're sending a secret letter to your friend:
You → Post Office → Your Friend
You → Attacker (opens, reads, reseals) → Your Friend
- Intercepts your letter before it reaches your friend
- Opens and reads everything
- Can modify the contents
- Reseals it and sends it to your friend
- Neither you nor your friend realizes someone read the letter
Critical Point
Both you and your friend think you're communicating directly, but an invisible middleman is reading and potentially changing everything.
#
In the Digital World
Your Computer → Internet → Bank Website
Your Computer → Attacker → Bank Website
↑
(reads everything)
- Your passwords
- Credit card numbers
- Private messages
- Session cookies
- Any data you send or receive
#
Types of MitM Attacks
#
:icon-wifi: 1. WiFi Eavesdropping
Attacker creates fake WiFi networks or monitors unencrypted WiFi traffic
Coffee Shop WiFi (Real): "Starbucks_WiFi"
Attacker's WiFi (Fake): "Starbucks_WiFi_Free" ← Stronger signal
User connects to fake WiFi
↓
All traffic goes through attacker's laptop
↓
Attacker can see and modify everything
# Attacker's screen (using Wireshark)
192.168.1.101 → facebook.com
POST /login HTTP/1.1
email=victim@email.com&password=SecretPass123
192.168.1.101 → bank.com
Cookie: session=abc123xyz...
192.168.1.101 → webmail.com
Reading email: "Your password reset code is 583921"
Public WiFi Network
↓
Attacker's laptop running packet sniffer
↓
Captures all unencrypted traffic from other users
#
:icon-network: 2. ARP Spoofing (ARP Poisoning)
Tricking devices on a local network to send data through the attacker's machine
ARP (Address Resolution Protocol) maps:
IP Address → MAC Address
Computer asks: "Who has IP 192.168.1.1?"
Router responds: "That's me, MAC address AA:BB:CC:DD:EE:FF"
Computer saves: 192.168.1.1 = AA:BB:CC:DD:EE:FF
Victim Computer: "Who has 192.168.1.1 (router)?"
Attacker: "That's me! MAC address 11:22:33:44:55:66" (lying)
Victim now sends all traffic to attacker instead of router
↓
Attacker forwards traffic to real router
↓
Victim doesn't notice, but attacker reads everything
# Attacker's commands (on local network)
echo 1 > /proc/sys/net/ipv4/ip_forward
# Make victim think attacker is the router
arpspoof -i eth0 -t 192.168.1.100 192.168.1.1
# Make router think attacker is the victim
arpspoof -i eth0 -t 192.168.1.1 192.168.1.100
# Now all traffic flows through attacker
wireshark
#
3. DNS Spoofing
Redirecting domain name lookups to attacker-controlled servers
You type: bank.com
Computer asks DNS server: "What's the IP for bank.com?"
DNS responds: "198.51.100.10"
Browser connects to 198.51.100.10 (real bank)
You type: bank.com
Attacker intercepts DNS request
Attacker responds faster than real DNS: "bank.com is at 203.0.113.50"
Browser connects to 203.0.113.50 (attacker's fake site)
- Looks identical to real bank.com
- You enter password → stolen
#
:icon-lock-open: 4. SSL Stripping
Downgrading HTTPS connections to HTTP, removing encryption
1. User types: "http://bank.com"
2. Server redirects: "Use https://bank.com instead"
3. Browser connects via HTTPS (encrypted)
1. User types: "http://bank.com"
2. Attacker intercepts request
3. Attacker connects to bank via HTTPS (encrypted: Attacker ↔ Bank)
4. Attacker responds to user via HTTP (unencrypted: User ↔ Attacker)
5. User thinks they're on bank.com, doesn't notice missing lock icon
6. All data visible to attacker
User ←[HTTPS encrypted]→ Bank
(Attacker can't read)
User ←[HTTP unencrypted]→ Attacker ←[HTTPS encrypted]→ Bank
↑ visible to attacker
#
:icon-certificate: 5. HTTPS Spoofing (Fake Certificates)
Using fake SSL certificates to impersonate secure websites
Certificate issued by: DigiCert (trusted)
Browser: ✓ Secure connection
Certificate issued by: Attacker (self-signed, untrusted)
Browser: ⚠️ Warning: Certificate not trusted
Most users click "Proceed anyway" → compromised
If attacker compromises a Certificate Authority:
- Can issue valid certificates for any domain
- Browser shows "Secure" with no warnings
- Perfect impersonation
Attacker tricks victim into installing fake root certificate:
"Install this certificate to access company WiFi"
After installation:
- Attacker can issue certificates for any site
- Browser trusts them (because root cert is trusted)
- No warnings shown
#
6. Session Hijacking
Stealing session cookies to impersonate logged-in users
1. User logs into website
2. Server sends session cookie: session_id=abc123xyz
3. Attacker intercepts cookie (via MitM)
4. Attacker uses stolen cookie
5. Server thinks attacker is the legitimate user
# Attacker captures traffic
tcpdump -i wlan0 -A | grep "Cookie:"
# Output:
Cookie: session_id=a1b2c3d4e5f6; user=victim@email.com
# Attacker uses stolen cookie
curl https://target.com/account \
-H "Cookie: session_id=a1b2c3d4e5f6" \
-H "User-Agent: Mozilla/5.0..."
# Attacker now has full access to victim's account
#
Real-World Examples
#
Case Study 1: Lenovo Superfish (2015)
Pre-installed malware that performed MitM on HTTPS traffic
- Affected all Lenovo laptops sold in 2014-2015
- Hundreds of thousands of devices compromised
- $3.5 million settlement
- Lenovo pre-installed "Superfish" adware on laptops
- Superfish installed root certificate on system
- Intercepted all HTTPS traffic
- Decrypted, injected ads, re-encrypted
- Users saw "secure" lock icon, but traffic was compromised
Normal HTTPS:
User ←[encrypted]→ Website
With Superfish:
User ←[encrypted]→ Superfish ←[encrypted]→ Website
↑
(can read everything)
#
Case Study 2: NSA QUANTUM Program (2013)
Nation-state MitM on global internet traffic
- Unknown number of targets
- Compromise of secure communications
- Government surveillance on mass scale
User requests: download.example.com/update.exe
↓
NSA detects request
↓
NSA responds FASTER than real server with malicious update.exe
↓
User's computer executes NSA malware
#
Case Study 3: DarkHotel APT (2014)
Targeted MitM attacks on hotel WiFi networks
- CEOs, executives, government officials targeted
- Sensitive corporate and government data stolen
- Global espionage campaign
Executive connects to hotel WiFi
↓
Visits Adobe.com to download Flash update
↓
Attacker intercepts request
↓
Serves malware disguised as Flash update
↓
Executive installs malware
↓
Attacker gains access to laptop and corporate network
#
Prevention & Mitigation
#
1. Always Use HTTPS
Force HTTPS on all pages and implement HSTS
from flask import Flask, redirect, request
@app.before_request
def force_https():
if not request.is_secure:
url = request.url.replace('http://', 'https://', 1)
return redirect(url, code=301)
@app.after_request
def set_hsts(response):
response.headers['Strict-Transport-Security'] = \
'max-age=31536000; includeSubDomains; preload'
return response
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https') {
res.redirect(`https://${req.header('host')}${req.url}`);
} else {
next();
}
});
// Set HSTS header
app.use((req, res, next) => {
res.setHeader('Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload');
next();
});
# Force HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Set HSTS Header
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Submit your domain: hstspreload.org
Requirements:
1. Serve valid HTTPS certificate
2. Redirect HTTP to HTTPS
3. Serve HSTS header on all subdomains
4. HSTS max-age of at least 1 year
Benefits:
- Browsers hardcode your domain as HTTPS-only
- Protection from first visit
- Used by Chrome, Firefox, Safari, Edge
#
2. Certificate Pinning
Hardcode which certificates/CAs your app trusts
// Pin specific certificate
let pinnedCertificates: Set<Data> = [
loadCertificate(name: "bank-cert")
]
func session(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// Get server certificate
let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)
let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data
// Check if it matches pinned certificate
if pinnedCertificates.contains(serverCertificateData) {
completionHandler(.useCredential, URLCredential(trust: serverTrust))
} else {
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
<!-- res/xml/network_security_config.xml -->
<network-security-config>
<domain-config>
<domain includeSubdomains="true">bank.com</domain>
<pin-set>
<pin digest="SHA-256">7HIpactkIAq2Y49orFOOQKurWxmmSFZhBCoQYcRhJ3Y=</pin>
<pin digest="SHA-256">fwza0LRMXouZHRC8Ei+4PyuldPDcf3UKgO/04cDM1oE=</pin>
</pin-set>
</domain-config>
</network-security-config>
#
3. Use VPN on Public WiFi
Your Device → Public WiFi → Internet
↑ attacker can intercept
Your Device → [Encrypted VPN Tunnel] → VPN Server → Internet
↑ attacker only sees encrypted data
VPN encrypts all traffic, even HTTP, protecting against:
- WiFi eavesdropping
- ARP spoofing
- DNS spoofing
- SSL stripping (partially)
#
4. Mutual TLS Authentication (mTLS)
Client verifies server's certificate
Server doesn't verify client
Client verifies server's certificate
Server verifies client's certificate
↓
Both parties authenticated
MitM can't impersonate either side
import ssl
from flask import Flask
app = Flask(__name__)
# Configure mTLS
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.verify_mode = ssl.CERT_REQUIRED # Require client certificate
context.load_cert_chain('server.crt', 'server.key')
context.load_verify_locations('client-ca.crt') # Trust client CA
if __name__ == '__main__':
app.run(ssl_context=context, host='0.0.0.0', port=443)
const https = require('https');
const fs = require('fs');
const options = {
hostname: 'api.example.com',
port: 443,
path: '/api/data',
method: 'GET',
cert: fs.readFileSync('client.crt'),
key: fs.readFileSync('client.key'),
ca: fs.readFileSync('server-ca.crt')
};
const req = https.request(options, (res) => {
console.log('Authenticated via mTLS');
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.end();
#
5. DNS Security (DNSSEC & DoH)
Client: "What's the IP for bank.com?"
Attacker: "It's 203.0.113.50" (fake)
Client: Trusts the response
Client: "What's the IP for bank.com?"
DNS: "It's 198.51.100.10, here's my signature"
Client: Verifies signature with public key
↓
Signature valid = Trust response
Signature invalid = Reject response
// Programmatic DNS over HTTPS
const fetch = require('node-fetch');
async function lookupDNS(domain) {
const response = await fetch(
`https://cloudflare-dns.com/dns-query?name=${domain}&type=A`,
{
headers: {
'Accept': 'application/dns-json'
}
}
);
const data = await response.json();
return data.Answer.map(a => a.data);
}
// This request is encrypted (HTTPS), preventing DNS spoofing
#
Detection & Testing
#
Detection Indicators
WARNING SIGNS:
- Browser shows "Not Secure" or certificate warnings
- Certificate issuer is unknown or unexpected
- Certificate dates are invalid
- Domain name doesn't match certificate
Action: DO NOT PROCEED. Close the site immediately.
# Check ARP table for duplicates
arp -a
# Normal output:
192.168.1.1 AA:BB:CC:DD:EE:FF
192.168.1.100 11:22:33:44:55:66
# Suspicious (ARP spoofing):
192.168.1.1 AA:BB:CC:DD:EE:FF
192.168.1.1 11:22:33:44:55:66 ← Same IP, different MAC!
# Check DNS resolution
nslookup bank.com
# Compare with known good DNS
nslookup bank.com 8.8.8.8
# Different results = potential DNS spoofing
#
Detection Tools
# Filter for ARP spoofing
arp.duplicate-address-detected
# Filter for SSL issues
ssl.handshake.type == 1
# Look for:
- Duplicate ARP responses
- Self-signed certificates
- Unexpected certificate authorities
# Run XArp on your network
xarp
# Alerts on:
- ARP cache poisoning
- MAC address conflicts
- Suspicious ARP traffic
Visit: https://crt.sh/?q=yourdomain.com
Check for:
- Unexpected certificates issued
- Certificates from unknown CAs
- Certificates you didn't request
#
Security Checklist
#
For Organizations
- Force HTTPS on all pages
- Implement HSTS with preload
- Deploy certificate pinning in mobile apps
- Use mTLS for API authentication
- Enable DNSSEC for domains
- Implement ARP spoofing detection
- Segment network with VLANs
- Use WPA3 for WiFi networks
- Deploy intrusion detection systems
- Monitor certificate transparency logs
#
For End Users
- Always verify HTTPS (padlock icon)
- Never ignore certificate warnings
- Use VPN on public WiFi
- Check URLs carefully before entering credentials
- Keep software updated
- Use cellular data for sensitive transactions
- Enable 2FA on all accounts
- Don't install unknown certificates
- Be suspicious of WiFi networks
- Use password managers (detects phishing sites)
#
Key Takeaways
Primary Defenses
- Always use HTTPS with HSTS - Prevents SSL stripping and downgrade attacks
- Implement certificate pinning - Prevents fake certificate attacks
- Use VPN on public WiFi - Encrypts all traffic including DNS
- Deploy mTLS for APIs - Mutual authentication prevents impersonation
Critical Points
- MitM attacks can steal passwords, session cookies, and sensitive data in real-time
- Even HTTPS can be compromised if users ignore certificate warnings
- Public WiFi is inherently insecure without VPN protection
- DNS spoofing can redirect users to fake websites
Best Practices
- Never ignore browser security warnings
- Use VPN when on untrusted networks
- Verify website certificates before entering credentials
- Enable HSTS preload for your domains
- Monitor network for ARP spoofing and DNS tampering
#
References & Resources
#
Official Documentation
#
Testing Tools
- Wireshark - Network Protocol Analyzer
- XArp - ARP Spoofing Detection
- SSLyze - SSL/TLS Scanner
- mitmproxy - MitM Proxy for Testing
#
Learning Resources
#
Layerd AI Protection
Layerd AI Guardian Proxy prevents Man-in-the-Middle attacks:
- Certificate validation - Automatically verifies SSL/TLS certificates
- Anomaly detection - ML identifies suspicious network patterns
- Real-time blocking - Prevents ARP spoofing and DNS tampering
- Zero configuration - Automatic HTTPS enforcement
Learn more about Layerd AI Protection →
Remember: Man-in-the-Middle attacks can compromise even encrypted connections if proper precautions aren't taken. Always use HTTPS, verify certificates, and use VPN on untrusted networks.
Never ignore browser security warnings!
Last updated: November 2025