fake_ap.py (2181B)
1 import unittest 2 import sys 3 import sys 4 import os 5 from scapy.layers.dot11 import * 6 from scapy.arch import str2mac 7 try: 8 from scapy.arch import get_if_raw_hwaddr 9 except: 10 from scapy.arch.unix import get_if_raw_hwaddr 11 from time import time, sleep 12 from threading import Thread 13 14 def if_hwaddr(iff): 15 return str2mac(get_if_raw_hwaddr(iff)[1]) 16 17 def config_mon(iface, channel): 18 """set the interface in monitor mode and then change channel using iw""" 19 os.system("ip link set dev %s down" % iface) 20 os.system("iw dev %s set type monitor" % iface) 21 os.system("ip link set dev %s up" % iface) 22 os.system("iw dev %s set channel %d" % (iface, channel)) 23 24 class AP: 25 def __init__(self, ssid, psk, mac=None, mode="stdio", iface="wlan0", channel=1): 26 self.channel = channel 27 self.iface = iface 28 self.mode = mode 29 if self.mode == "iface": 30 if not mac: 31 mac = if_hwaddr(iface) 32 config_mon(iface, channel) 33 if not mac: 34 raise Exception("Need a mac") 35 else: 36 self.mac = mac 37 self.boottime = time() 38 39 def get_radiotap_header(self): 40 return RadioTap() 41 42 def dot11_beacon(self, contents): 43 evil_packet = ( 44 self.get_radiotap_header() 45 / Dot11( 46 subtype=8, addr1="ff:ff:ff:ff:ff:ff", addr2=self.mac, addr3=self.mac 47 ) 48 / Dot11Beacon(cap=0x3101) 49 / contents 50 ) 51 self.sendp(evil_packet) 52 53 def run(self, contents): 54 interval = 0.05 55 num_beacons = 100 56 57 while num_beacons: 58 self.dot11_beacon(contents) 59 sleep(interval) 60 num_beacons -= 1 61 62 def start(self, contents): 63 self.thread = Thread(target=self.run, args=(contents,)) 64 self.thread.start() 65 66 def stop(self): 67 self.thread.join() 68 69 def sendp(self, packet, verbose=False): 70 if self.mode == "stdio": 71 x = packet.build() 72 sys.stdout.buffer.write(struct.pack("<L", len(x)) + x) 73 sys.stdout.buffer.flush() 74 return 75 assert self.mode == "iface" 76 sendp(packet, iface=self.iface, verbose=False)