Documentation

# 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.

Man-in-the-Middle Illustration
Man-in-the-Middle Illustration


# 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
  1. Intercepts your letter before it reaches your friend
  2. Opens and reads everything
  3. Can modify the contents
  4. Reseals it and sends it to your friend
  5. Neither you nor your friend realizes someone read the letter

# 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
[Enable IP Forwarding]
# Attacker's commands (on local network)
echo 1 > /proc/sys/net/ipv4/ip_forward
[ARP Spoofing]
# 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
[Capture Traffic]
# 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
[Capture Cookie]
# Attacker captures traffic
tcpdump -i wlan0 -A | grep "Cookie:"

# Output:
Cookie: session_id=a1b2c3d4e5f6; user=victim@email.com
[Use Stolen Cookie]
# 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
  1. Lenovo pre-installed "Superfish" adware on laptops
  2. Superfish installed root certificate on system
  3. Intercepted all HTTPS traffic
  4. Decrypted, injected ads, re-encrypted
  5. 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

[Python/Flask]
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
[Node.js/Express]
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();
});
[Apache .htaccess]
# 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

[iOS]
// 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)
    }
}
[Android]
<!-- 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
[Server-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)
[Client-Side]
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


# References & Resources

# Official Documentation

# Testing Tools

# 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