def sniff(self, target=None, iface=None):
     def _process(pkt):
         match_ip = pkt.haslayer(IP) and (pkt[IP].src==target[0] or pkt[IP].dst==target[0]) if target else True
         match_port = pkt.haslayer(TCP) and (pkt[TCP].sport==target[1] or pkt[TCP].dport==target[1]) if len(target)==2 else True 
         if match_ip and match_port:
             self.capabilities.insert(pkt, client=False)
             events = self.capabilities.get_events()         # misuse get_events :/
             if events:
                 strconn = {'src':None,
                              'dst':None,
                              'sport':None,
                              'dport':None}
                 
                 if pkt.haslayer(IP):
                     strconn['src'] = pkt[IP].src
                     strconn['dst'] = pkt[IP].dst
                 if pkt.haslayer(TCP):
                     strconn['sport'] = pkt[TCP].sport
                     strconn['dport'] = pkt[TCP].dport
                     
                 print "Connection: %(src)s:%(sport)d <==> %(dst)s:%(dport)d"%strconn
                 print "* EVENT - " + "\n* EVENT - ".join(e[0] for e in events)
         return
     if iface:
         conf.iface=iface
     while True:
         bpf = None
         if len(target):
             bpf = "host %s"%target[0]
         if len(target)==2:
             bpf += " and tcp port %d"%target[1]
         sniff(filter=bpf,
                 prn=_process,
                 store=0,
                 timeout=3)
Example #2
0
	def __sniff_sessionkey_and_salt__(self,ip=None,port=None):
		'''
		To sniff the session key and the salt in an Oracle connection thanks to scapy
		'''
		def customAction(packet):
			global sessionKey, salt
			if packet[0].haslayer(IP)==True and packet[1].src == ip :
				#print packet.show()
				if packet[2].haslayer(scapyall.Raw)==True:
					raw = repr(packet[2].getlayer(scapyall.Raw).load)
					if "AUTH_SESSKEY" in raw and "AUTH_VFR_DATA" in raw:	
						sessionKey = re.findall(r"[0-9a-fA-F]{96}" ,raw[raw.index("AUTH_SESSKEY"):raw.index("AUTH_VFR_DATA")])
						if sessionKey != [] : sessionKey = sessionKey[0]
						try : authVFRindex = raw.index("AUTH_VFR_DATA")
						except : logging.warning("The following string doesn't contain AUTH_VFR_DATA: {0}".format(raw))
						else:
							try: authGloIndex = raw.index("AUTH_GLOBALLY_UNIQUE_DBID")
							except : logging.warning("The following string doesn't contain AUTH_GLOBALLY_UNIQUE_DBID: {0}".format(raw))
							else:
								salt = re.findall(r"[0-9a-fA-F]{22}" ,raw[authVFRindex:authGloIndex])
								if salt != [] : salt = salt[0][2:]
						finally:
							return True
			return False
		self.__resetSessionKeyValueAndSalt__()
		#print "Run with tcp and host {0} and port {1}".format(ip,port)
		scapyall.sniff(filter="tcp and host {0} and port {1}".format(ip,port), count=self.MAX_PACKET_TO_CAPTURE, timeout=self.TIMEOUT, stop_filter=customAction,store=False)
		return sessionKey, salt
Example #3
0
def main():
    ''' Main function '''
    global log, FTP_LOG, debugMode, consoleMode, printCookies, expr, LOGFILE

    log=logging.getLogger(APP_NAME)

    #if consoleMode:
    #    handler = logging.StreamHandler()
    #else:
    handler = logging.FileHandler(LOGFILE)

    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    log.addHandler(handler)

    if debugMode==False:
        log.setLevel(logging.INFO)
    else:
        log.setLevel(logging.DEBUG)
   
    printMessage("Listening on "+expr)

    if debugMode:
        printMessage("Debug mode activated")

    if consoleMode:
        printMessage("Console mode activated")
    else:
        daemonize()

    try:
        sniff(filter=expr, prn=http_monitor_callback, store=0)
    except KeyboardInterrupt:
        exit(0)
Example #4
0
	def __init__(self):
		# Parameters
		interface = 'mon0'
		freq = '2442 MHz' # Mhz (channel 7)
		
		#Shared Variables
		self.mac_list = [[]] 	# [time, mac addr, signal level]
		self.white_list = []	# whitelist of mac addr
		self.dt = 1 		# sample time in minutes

		# Init wifi
		print "Init wifi..."
		while(1):
			try:
				Wireless(interface).setMode('Monitor')
				Wireless(interface).setFrequency(freq)
				break
			except:
				os.system("sh wifi_setup.sh")
				return "Wifi Initialisation failed!"
		
		self.loadWhiteList()		

		# Init interrupt
		sniff(iface=interface, prn=self.handler, store=0)
Example #5
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--interface', '-i', default='mon0',
                        help='monitor mode enabled interface')
    args = parser.parse_args()
    sniff(iface=args.interface, prn=handle_packet)
Example #6
0
 def run(self):
     """Run the sniffer"""
     try:
         sniff(filter="arp", prn=self._arp_callback, store=False, stop_filter=self._stopper)
     except TypeError:
         print("Ok! This error likely happened because you are not using scapy version 2.2 or above")
         raise
Example #7
0
    def run(self):
        if self.pcap:
            self.parse_pcap()
        else:

            shownMessage = False
            while not self.STOP_SNIFFING:
                if self.enable_monitor_mode:
                        self.iface=mm.enable_monitor_mode(self.iface)
                        if not self.iface:
                                if not shownMessage:
                                    logging.error("No suitable monitor interface available. Will check every 5 seconds, but not display this message again.")
                                    shownMessage = True
                                time.sleep(5)
                if not self.iface and self.enable_monitor_mode:
                    continue
                if not self.iface:
                    logging.info("No interface specified. Will sniff *all* interfaces.")
                else:
                    logging.info("Starting sniffing on interface '%s'"%self.iface)
                try:
                    self.ready_status = True
                    shownMessage = False
                    sniff(store=0, iface=self.iface, prn=self.packeteer, filter=self.bfilter,
                          stopperTimeout=1, stopper=self.stopperCheck)
                except Exception, e:
                    logging.error(("Scapy exception whilst sniffing. "
                                       "Will back off for 5 seconds, "
                                       "and try restart '%s' plugin") % __name__)
                    logging.error(e)
                    self.sniffErrors+=1
                if self.sniffErrors >3 :
                    logging.error("Restarting module '%s' after 5 failed attempts" %__file__)
                time.sleep(5)
Example #8
0
    def run(self):
        """
        Starts the kitchen.

        This blocks and will run forever.
        """
        # Start the chef poking thread.
        if self.chef_poke_interval is not None:
            self._logger.info(
                "{0}: Starting interval poker thread".format(self.name))

            interval_poker = Thread(
                target=self._poke_chefs,
                kwargs={'interval': self.chef_poke_interval}
            )

            interval_poker.start()
        else:
            self._logger.info(
                "{0}: Interval poker thread disabled".format(self.name))

        # Start the sniffer.
        self._logger.info("{0}: Starting sniffer thread".format(self.name))

        if self.interface == 'all':
            sniff(filter=self.filter, prn=self._process_packet, store=0)
        else:
            sniff(iface=self.interface, filter=self.filter,
                  prn=self._process_packet, store=0)
Example #9
0
 def _sniff(self):
     """ Wrapper for packet sniffing. """
     while True:
         if self._sniffing is False:
             return
         sniff(iface=self._wireless_interface, prn=self._process, filter=FILTER + self._mac_address, store=0,
               timeout=SNIFF_TIMEOUT)
Example #10
0
    def __sniff_sessionkey_and_salt__(self, ip=None, port=None):
        """
		To sniff the session key and the salt in an Oracle connection thanks to scapy
		"""

        def customAction(packet):
            global sessionKey, salt
            if packet[0].haslayer(IP) == True and packet[1].src == ip:
                # print packet.show()
                if packet[2].haslayer(scapyall.Raw) == True:
                    raw = repr(packet[2].getlayer(scapyall.Raw).load)
                    if "AUTH_SESSKEY" in raw and "AUTH_VFR_DATA" in raw:
                        sessionKey = re.findall(
                            r"[0-9a-fA-F]{96}", raw[raw.index("AUTH_SESSKEY") : raw.index("AUTH_VFR_DATA")]
                        )
                        if sessionKey != []:
                            sessionKey = sessionKey[0]
                        salt = re.findall(
                            r"[0-9a-fA-F]{22}", raw[raw.index("AUTH_VFR_DATA") : raw.index("AUTH_GLOBALLY_UNIQUE_DBID")]
                        )
                        if salt != []:
                            salt = salt[0][2:]
                        return True
            return False

        self.__resetSessionKeyValueAndSalt__()
        # print "Run with tcp and host {0} and port {1}".format(ip,port)
        scapyall.sniff(
            filter="tcp and host {0} and port {1}".format(ip, port),
            count=self.MAX_PACKET_TO_CAPTURE,
            timeout=self.TIMEOUT,
            stop_filter=customAction,
            store=False,
        )
        return sessionKey, salt
Example #11
0
  def __init__(self, listenInt, interface, freq, essid, psswd, ip, nm, discoverOnce=True):
    self.robotName = os.getenv('HOSTNAME')
    self.tolerance = 20
    self.x = 0
    self.y = 0
    self.client = WiFiTrilatClient()

    self.discoverOnce = discoverOnce

    rospy.init_node(self.robotName + "_wifitrilat_server")

    #self.rssiPub = rospy.Publisher('/' + self.robotName + '/WiFiRSSI', WiFiRSSIMsg, queue_size=10)
    self.service = rospy.Service("/" + self.robotName + "/WiFiTrilat", WiFiTrilat, self.handle_Trilat)

    self.listenInt = listenInt
    self.interface = interface
    #self.mac = mac.lower()
    self.freq = int(freq)

    self.msgs = []

    cli.execute_shell("ifconfig %s down" % self.listenInt)
    #self.wifi = Wireless(self.interface).setFrequency("%.3f" % (float(self.freq) / 1000))
    self.connectToNet(essid, psswd,ip, nm)
    cli.execute_shell("ifconfig %s up" % self.listenInt)

    self.purge = rospy.Timer(rospy.Duration(2), self.msgPurge)
    self.heartbeat = rospy.Timer(rospy.Duration(1), self.heartbeat_call)
    self.discoverTimer = rospy.Timer(rospy.Duration(20), self.findSelfPos)


    sniff(iface=self.listenInt, prn=self.handler, store=0)
    rospy.spin()
Example #12
0
def main():
    if not len(sys.argv[1:]):
        usage()

	arp_watcher_db_file = "/Users/kenyadoit/Desktop/arpwatcher.db"
	ip_mac = {}

	#Save ARP table on shutdown
	def sig_int_handler(signum, frame):
		print "Got SIGINT.  Saving ARP dtabase..."
		try:
			f = open(arp_watcher_db_file, "w")

			for (ip, mac) in ip_mac.items():
				f.write(ip + " " + mac + "\n")

			f.close()
			print "Done."
		except IOError:
			print "Cannot write file.  YOU F****D IT UP AGAIN DUMMY " +_watcher_db_file
			sys.exit(1)

	def watch_arp(pkt):
		#got is-at pkt (ARP resposne)
		if pkt[ARP].op == 2:
			print pkt[ARP].hwsrc + " " + pkt[ARP].psrc

		#Remember new device
		if ip_mac.get(pkt[ARP].psrc) == None:
			print "Found new device " + \
				pkt[ARP].hwsc + " " + \
				pkt[ARP].psrc
			ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc

		#Known device but different IP
		elif ip_mac.get(pkt[ARP].psrc) and ip_mac[pkt[ARP].psrc] != pkt[ARP].hwsrc:
			print pkt[ARP].hwsrc + \
			" has got new ip " + \
			" (old " + ip_mac[pkt[ARP].psrc] + ")"
			ip_mac[pkt[ARP].psrc] = pkt[ARP].hwsrc

	signal(SIGINT, sig_int_handler)

	if len(sys.argv) < 2:
		print sys.argv[0] + " <iface>"
		sys.exit(0)

	try:
		fh = open(arp_watcher_db_file, "r")
	except IOError:
		print "Cannot read file " + arp_watcher_db_file
		sys.exit(1)

	for line in fh:
		line.chomp()
		(ip, mac) = line.split (" ")
		ip_mac[ip] = mac

	sniff(prn = watch_arp, filter="arp", iface=sys.argv[1], store= 0)
  def _load_testdata(self, file_path):
    packets = []
    def _add_packet(pkt):
      packets.append(pkt)

    path = '../testdata/dhcp/' + file_path
    sniff(prn=_add_packet, store=0, offline=path)
    return packets
Example #14
0
	def __call__(cls):
		from scapy.all import sniff
		try:
			sniff(iface=cls.iface, store=0, prn=cls._prn_)
		except KeyboardInterrupt as e:
			raise
		except Exception as e:
			print e
Example #15
0
 def _do_sniff(self, timeout=None, lfilter=None):
     lfilter = lfilter or (lambda packet: True)
     sniff(iface=self.interface,
           prn=lambda packet: self.packet_queue.put(packet),
           store=0,
           lfilter=lambda packet: lfilter(packet) and packet.haslayer(Dot11),
           stop_filter=lambda packet: self.stopped,
           timeout=timeout)
Example #16
0
 def run(self):
     """Starts sniffing for incoming ARP packets with scapy.
     Actions after receiving a packet ar defines via _packet_handler.
     """
     # the filter argument in scapy's sniff function seems to be applied too late
     # therefore some unwanted packets are processed (e.g. tcp packets of ssh session)
     # but it still decreases the number of packets that need to be processed by the lfilter function
     sniff(prn=self._packet_handler, filter=self._SNIFF_FILTER, lfilter=self._LFILTER, store=0, iface=self.interface)
Example #17
0
def main():
    running = True
    while running:
        try:
            filter = "tcp dst port 6969"
            sniff(filter = filter,prn=analyse,count=10,store=0)
        except KeyboardInterrupt:
            running = False
Example #18
0
    def start(self):
        printLogMsg(logging.INFO, "start", "start new sniffering for hostId: %s on mac address: %s" %(str(self.hostId), str(self.macAddress)))

        while True:
            try:
                scapy.sniff(store=0, filter="tcp", prn=self.checkPacketType, count=1)
            except ValueError:
                pass
Example #19
0
def main():
    args = parse_args()
    simpNetMon = SimpleNetworkMonitor(args.filename)
    if args.show_known:
        simpNetMon.show_known()
        return
    sniff(prn=simpNetMon.arp_monitor_callback, filter='arp',
          store=0, iface=args.interface)
Example #20
0
def _handle_sniffing():
    global _iface, _sniffer
    print_d("sniffer started")
    if _iface is None:
        raise RuntimeError("no monitoring interface specified yet. call set_interface() first")
    sniff(iface=_iface, store=0, stop_filter=_handle_packet)
    _sniffer = None
    print_d("sniffer stopped")
Example #21
0
    def traffic_sniffer(self):
        """ Sniff traffic with the given filter.
			If sniff_filter is not set, an exception is raised
		"""
        if self.sniff_filter is None:
            raise NotImplementedError, "sniff_filter not initialized!"

        sniff(filter=self.sniff_filter, store=0, prn=self.dump, stopper=self.stop_callback, stopperTimeout=3)
 def start_credential_sniffing(self):
     # TODO map packets to interface with threads
     try:
         sniff(  store       =   0,
                 prn         =   self.extract_credential_info,
                 stop_filter =   self._stop)
     except Exception as e:
         print "Error Occurred while sniffing."
         print str(e)
Example #23
0
 def run(self):
   # scapy - with config initialised
   #scapy.sendrecv.sniff(count=self.packetCount,timeout=self.timeout,store=0,filter=self.filterRules,prn=self.cbSSHPacket)
   from scapy.all import sniff
   log.info('Using L2listen = %s'%(scapy.config.conf.L2listen)) 
   # XXX TODO, define iface from saddr and daddr // scapy.all.read_routes()
   sniff(count=self.packetCount, timeout=self.timeout, store=0, filter=self.filterRules, prn=self.enqueue, iface='any')
   log.warning('============ SNIFF Terminated ====================')
   return
def main():
    args = command_parser()
    interface = args.interface
    host = args.host
    port = int(args.port)
    filter_str = "tcp and port {} and host {}".format(port, host)
    print("[*] Beginning sniff")
    conf.verb = 0
    sniff(iface=interface, store=0, filter=filter_str, prn=handle_packet)
def main():
    from sys import argv
    if len(argv) < 2:
        print "Usage receiver.py [host number]"
        return

    iface = "h%s-eth0" % (argv[1], )
    print "Listen on %s" % (iface, )
    sniff(iface = iface, prn = lambda x: handle_pkt(x))
Example #26
0
def debug(iface, pkt_type, pkt_subtype):
    print "DEBUG", pkt_type, pkt_subtype
    sniff(
        iface = iface,
        count = 1,
        prn = lambda pkt: pkt.show(),
        lfilter = lambda pkt: pkt.haslayer(Dot11)
            and pkt[Dot11].type == pkt_type
            and pkt[Dot11].subtype == pkt_subtype
    )
Example #27
0
 def run(self):
     try:
         Wireless(self.interface).setFrequency("%.3f" % (float(self.freq)/1000))
     except IOError:
         print >>sys.stderr, traceback.format_exc()
         print >>sys.stderr, "meh"
         return
     self.hist = []
     #print >>sys.stderr, "looking for %s on %s chan: %s (%s)" % (self.mac, self.interface, chanmap[self.freq[0]+self.freq[2:5]], self.freq)
     sniff(iface=self.interface, prn=self.handler, store=0)
Example #28
0
 def sniff(self):
     try:
         sniff(*self.args, **self.kwargs)
     except Exception as e:
         if not self._once:
             print 'Exception on thread:', repr(e), '\n', self.args, '\n', self.kwargs, '\n\n'
             print 'Since I didn\'t have a single success you should probably be reminded to use sudo'
             raise
     self.stop()
     self.queue.put(None)  # make sure things have an iteration after thread stops
Example #29
0
    def runIds(self, mrules = False):
        try:
            if not mrules:
                from rules import rules
                mrules = rules

            self.realRules = mrules

            for rule in mrules:
                self.rules.append(re.compile(rule["data"], re.IGNORECASE))
                
            if snortSupport:
                try:
                    snortRuleParser = CSnortRuleParser()
                    snortRuleParser.parse("oracle.rules")
                
                    for rule in snortRuleParser.rules:

                        if rule.pcre != "" or len(rule.contents) > 0:

                            try:
                                if rule.pcre != "":
                                    data = rule.pcre
                                else:
                                    continue # Ignore. At the moment there is no good support for content and content! rules
                                    data = ".*" + rule.contents[0] + ".*"

                                p = re.compile(data, re.IGNORECASE)

                                arule = {}
                                arule["data"] = data
                                arule["name"] = rule.msg
                                arule["description"] = rule.msg
                                arule["type"] = rule.classtype
                                arule["attack"] = rule.msg
                                arule["tip"] = ""
                                arule["ids"] = ""
                                arule["default_port"] = ""

                                self.rules.append(p)
                                self.realRules.append(arule)
                            except:
                                print "Rule does not compile:", sys.exc_info()[1]
                except:
                    #
                    # Ignore the exception, we can continue anyway
                    #
                    print "Snort:", sys.exc_info()[1]
        except:
            print "Can't read rules.py file. No rules."
            print sys.exc_info()[1]
            return

        print "Running Intrusion Detection System ... "
        scapy.sniff(iface = self.iface, filter = self.filter, prn= self.checkRule)
Example #30
0
def sniff_packets(interface):
    scapy.sniff(iface=interface, store=False, prn=packet_sniffed)
Example #31
0
def sniff(interface):
    scapy.sniff(iface=interface, store=False, prn=analyze_packet)
from scapy.all import sniff
from scapy.all import wrpcap
from scapy.arch.windows import show_interfaces
import os
import livepredict
import pyshark
# cap = pyshark.LiveCapture(interface='ethernet',output_file='data.pcap')
# cap.set_debug()
# cap.sniff(timeout=20)
# show_interfaces()
pkts = sniff(timeout=15,iface="Npcap Loopback Adapter")
# pkts = sniff(timeout=15,iface="Realtek PCIe GbE Family Controller")
os.chdir(os.getcwd()+'/livepcap')
wrpcap('data.pcap',pkts)
os.chdir('..')
os.chdir('C:/Users/user/Desktop/prj/cicflowmeter-4/CICFlowMeter-4.0/bin')
os.system("cfm.bat \"C:/Users/user/Desktop/prj/livepcap\" \"C:/Users/user/Desktop/prj/livedata\"")
os.chdir('C:/Users/user/Desktop/prj')
livepredict.predict()
def main():
    iface = 'eth0'
    print "sniffing on %s" % iface
    sys.stdout.flush()
    sniff(filter="udp and port 4321", iface=iface, prn=lambda x: handle_pkt(x))
def sniff(interface):

	scapy.sniff(iface = interface, store = False, prn = process_sniffed_packet,filter = "port 80" or "port 443")
def main():
    bind_layers(GTP_U_Header, dl_pdu_session, E=1)
    #sniff(iface=["eth1","eth2"], prn=lambda x: x.sniffed_on+": "+x.summary())
    #sniff(iface=["eth1","eth2"], prn=lambda x: updownlink(x))
    sniff(iface="eth1", prn=lambda x: updownlink(x))
Example #36
0
 def run(self):
     sniff(iface=self.iface, prn=lambda x: self.handler(x, self.iface))
Example #37
0
def sniff(interface):
    # scapy.sniff(iface=interface, store=False, prn=processSniffedPacket, filter="udp")
    scapy.sniff(iface=interface, store=False, prn=processSniffedPacket)
Example #38
0
def child(pipeout):
    def search(search_key):
        for k in features:
            for v in features[k]:
                if search_key in v:
                    return k
        return None

    def is_http(packet):
        packet = str(packet)
        return "HTTP" in packet and any(method in packet for method in methods)

    def filter_packets(load):
        # filters the payload on basis of only the attributes required to us
        lv = load.split('\r\n')
        for i in lv:
            p = i.find(':')
            if p != -1:
                key = i[:p]
                value = i[p + 1:]
                # provide numerical value to content-type
                if key == 'Content-Type':
                    # eval converts string to preexisting variable name
                    try:
                        dictionary[key] = str(eval(search(key)).index(value) + 1)
                    except ValueError as ex:
                        dictionary[key] = str(int(math.log10(len(value))))
                        pass
                elif key == 'Host':
                    try:
                        dictionary[key] = str(eval(search(key)).index(value) + 1)
                    except ValueError as ex:
                        dictionary[key] = str(int(math.log10(len(value))))
                        pass
                elif key in attributes:
                    dictionary[key] = str(value)
                # assign default value
                for k in attributes:
                    if k not in dictionary:
                        dictionary[k] = str('10000')
                # calculation of Payload
                if dictionary['Method'] == '0':
                    try:
                        start = load.index('?')
                        end = load.index('HTTP/')
                        dictionary['Payload'] = str(len(load[start:end - 2]))
                    except ValueError:
                        return ""
                else:
                    dictionary['Payload'] = dictionary['Content-Length']

        feature_keys = ['Host', 'Payload', 'Content-Type', 'Content-Length', 'Method']
        values = [dictionary.get(feature) for feature in feature_keys]
        os.write(pipeout, str(values) + 'a')

    def start_sniff(packet):
        if is_http(packet):
            for att in methods:
                if att in str(packet):
                    dictionary['Method'] = str(methods.index(att) + 1)
            filter_packets(packet.load)

    sniff(prn=start_sniff)
Example #39
0
def main():
    ifaces = filter(lambda i: 'eth' in i, os.listdir('/sys/class/net/'))
    iface = ifaces[0]
    sys.stdout.flush()
    sniff(iface=iface, prn=lambda x: handle_pkt(x))
Example #40
0
                hasher[fields].append(packet.getlayer(scapy.DNSRR)[i].rdata)
                i -= 1

        if count == 10:
            #	print("Renewing hash")
            hasher = {}
            count = 0


def hostfile_parser(hostfile):
    host = dict()
    with open(hostfile, 'r') as file:
        for line in file:
            ip, sep, domain = line.partition(" ")
            host[ip] = domain
    return host


if __name__ == "__main__":
    cmdLineOptions = "i:r:"
    options, bpf = getopt.getopt(sys.argv[1:], cmdLineOptions)
    dev = ni.gateways()['default'][ni.AF_INET][1]
    filter = " ".join(bpf)  #+= str(bpf)
    for op in options:
        if "-i" in op[0]:
            dev = op[1]
            scapy.sniff(iface=dev, filter=filter, prn=handle)
        elif "-r" in op[0]:
            tracefile = op[1]
            scapy.sniff(offline=tracefile, filter=filter, prn=handle)
Example #41
0
def main():
    args = parse_args()

    if os.getuid() != 0:
        print(
            "This program requires RAW sockets and must be started as \"root\".",
            file=sys.stderr)
        sys.exit(1)

    # Formatting and pointing all messages to standard error (or a file) at the root logger level
    # ensures everything gets a timestamp and doesn't get lost in some console that nobody reads...
    format = logging.Formatter("%(asctime)s: %(levelname)s: %(message)s")
    handler = logging.handlers.WatchedFileHandler(
        args.log) if args.log else logging.StreamHandler(sys.stderr)
    handler.setFormatter(format)
    logging.getLogger().addHandler(handler)

    # Leaving the root logger with the default level, and setting it in our own logging hierarchy
    # instead, prevents accidental triggering of third-party logging, just like $DEITY intended...
    log.setLevel(logging.DEBUG if args.verbose else logging.INFO)

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGQUIT, signal_handler)

    trigger = args.trigger.encode("utf-8") if args.trigger else None

    if args.text:  # ...text and file arguments are mutually exclusive.
        payload = args.text.encode("utf-8")
    elif args.filename:
        try:
            with open(args.filename, "rb") as f:
                payload = f.read()
        except OSError as e:
            log.error(str(e))
            sys.exit(1)
    else:
        payload = None  # ...just echo back what the requestor sent.

    if payload:
        # We don't modify the response payloads, not even to filter out blank/empty lines...
        payload = payload.replace(
            b"\r\n", b"\n").split(b"\n") if args.randomize else [payload]

        if any(len(p) > MAX_ICMP_PAYLOAD_SIZE for p in payload):
            log.error("Custom ICMP payload(s) must not exceed %d bytes!",
                      MAX_ICMP_PAYLOAD_SIZE)
            sys.exit(1)

    # Be quiet and don't use promiscuous mode, ever...
    scapy.config.conf.verb = 0
    scapy.config.conf.promisc = False
    scapy.config.conf.sniff_promisc = False

    if args.iface:  # ...use this network interface instead of the default.
        scapy.config.conf.iface = args.iface

    # Resolving the default route's MAC address after dropping privileges isn't allowed,
    # preventing ICMP replies from reaching their destination. Of course, obtaining it once
    # at startup assumes it won't ever change while we're running. We'll be fine, though...
    gw_ip = scapy.config.conf.route.route("0.0.0.0")[2]
    gw_mac = scapy.layers.l2.getmacbyip(gw_ip)
    gw = {"ip": gw_ip, "mac": gw_mac}

    # We need to create the sending socket before dropping root privileges...
    raw_socket = scapy.config.conf.L3socket(iface=scapy.config.conf.iface)
    capture_cb = lambda packet: send_icmp_echo_reply(
        raw_socket, gw, packet, payload, trigger, fuzzy_match=args.fuzzy)
    started_cb = lambda: drop_privileges(args.user, args.group)

    log.info("Starting capture on %s...", scapy.config.conf.iface)

    # Using a BPF filter reduces CPU usage considerably but needs elevated
    # privileges (because scapy uses "tcpdump" for filtering). These privileges
    # must be dropped immediately after capture has started for better security...
    sniff(filter="icmp and icmp[icmptype] == 8",
          prn=capture_cb,
          started_callback=started_cb,
          store=0)
def sniff(interface):
    scapy.sniff(iface=interface, store = False , prn = process_sniffed_packet )
Example #43
0
    # Display
    print("{} ({}) - {}".format(MAC, vendor, ", ".join(SSID)))


# Definition of the packets to found and manipulate
def handle_packet(packet):
    if packet.haslayer(Dot11):
        # We take care only to probe requests frames (subtype = 4)
        if packet.type == 0 and packet.subtype == 4:
            # Discard frames without SSID
            if packet.info != "":
                # Check if the client is known or not
                if packet.addr2 in listClients:
                    # Check if the SSID of this client is known or not
                    if packet.info not in mapClients[packet.addr2]:
                        # Add the new SSID and display it
                        mapClients[packet.addr2].add(packet.info)
                        #print("Adding a SSID to a MAC client")
                        myPrint(packet.addr2, mapClients[packet.addr2])
                else:
                    # Add the new client and his SSID
                    listClients.append(packet.addr2)
                    mapClients[packet.addr2] = {packet.info}
                    #print("Adding a MAC client")
                    myPrint(packet.addr2, mapClients[packet.addr2])


# Launch the sniffer
sniff(iface="wlan0mon", prn=handle_packet)
Example #44
0
 def _sniff(e):
     a = scapy.sniff(filter="tcp",
                     prn=parse,
                     stop_filter=lambda p: e.is_set())
def threadListen():
    sniff(filter="icmp", count=0, prn=handleTraffic)
Example #46
0
def main():
    global iface
    print("start to sniff!!\n")
    sniff(iface=iface, prn=lambda x: handle_pkt(x))
Example #47
0
def main():
    # The filter can be change to sniff at the moment it focuses on mail server ports FTP port 21
    # store 0 makes sure scapy doesn't keep the packets in memory.
    sniff(filter='tcp port 110 or tcp port 25 or tcp port 143',
          prn=packet_callback,
          store=0)
Example #48
0
 def listen(self):
     sniff(prn=self.process)
Example #49
0
def extract_from_pcap(path, fields):
    """
    Search in pcap-file for specified information

    path: Path to pcap file
    fields: Array of fields that should be extracted

    If a field is not found, FieldNotFoundError is raised
    """
    results = dict()
    for field in fields:
        if not isinstance(field, WifiInfo):
            raise TypeError("Invalid field")

        subtypes = set()

        if field == WifiInfo.BSSID:
            from scapy.all import Dot11Beacon, Dot11ProbeResp, Dot11AssoReq, Dot11ReassoReq, Dot11, sniff
            subtypes.add('beacon')
            bpf_filter = " or ".join(
                [f"wlan type mgt subtype {subtype}" for subtype in subtypes])
            packets = sniff(offline=path, filter=bpf_filter)
            try:
                for packet in packets:
                    if packet.haslayer(Dot11Beacon):
                        if hasattr(packet[Dot11], 'addr3'):
                            results[field] = packet[Dot11].addr3
                            break
                else:  # magic
                    raise FieldNotFoundError("Could not find field [BSSID]")
            except Exception:
                raise FieldNotFoundError("Could not find field [BSSID]")
        elif field == WifiInfo.ESSID:
            from scapy.all import Dot11Beacon, Dot11ReassoReq, Dot11AssoReq, Dot11, sniff, Dot11Elt
            subtypes.add('beacon')
            subtypes.add('assoc-req')
            subtypes.add('reassoc-req')
            bpf_filter = " or ".join(
                [f"wlan type mgt subtype {subtype}" for subtype in subtypes])
            packets = sniff(offline=path, filter=bpf_filter)
            try:
                for packet in packets:
                    if packet.haslayer(Dot11Elt) and hasattr(
                            packet[Dot11Elt], 'info'):
                        results[field] = packet[Dot11Elt].info.decode('utf-8')
                        break
                else:  # magic
                    raise FieldNotFoundError("Could not find field [ESSID]")
            except Exception:
                raise FieldNotFoundError("Could not find field [ESSID]")
        elif field == WifiInfo.ENCRYPTION:
            from scapy.all import Dot11Beacon, sniff
            subtypes.add('beacon')
            bpf_filter = " or ".join(
                [f"wlan type mgt subtype {subtype}" for subtype in subtypes])
            packets = sniff(offline=path, filter=bpf_filter)
            try:
                for packet in packets:
                    if packet.haslayer(Dot11Beacon) and hasattr(
                            packet[Dot11Beacon], 'network_stats'):
                        stats = packet[Dot11Beacon].network_stats()
                        if 'crypto' in stats:
                            results[field] = stats[
                                'crypto']  # set with encryption types
                            break
                else:  # magic
                    raise FieldNotFoundError(
                        "Could not find field [ENCRYPTION]")
            except Exception:
                raise FieldNotFoundError("Could not find field [ENCRYPTION]")
        elif field == WifiInfo.CHANNEL:
            from scapy.all import sniff, RadioTap
            from pwnagotchi.mesh.wifi import freq_to_channel
            packets = sniff(offline=path, count=1)
            try:
                results[field] = freq_to_channel(
                    packets[0][RadioTap].ChannelFrequency)
            except Exception:
                raise FieldNotFoundError("Could not find field [CHANNEL]")
        elif field == WifiInfo.RSSI:
            from scapy.all import sniff, RadioTap
            from pwnagotchi.mesh.wifi import freq_to_channel
            packets = sniff(offline=path, count=1)
            try:
                results[field] = packets[0][RadioTap].dBm_AntSignal
            except Exception:
                raise FieldNotFoundError("Could not find field [RSSI]")

    return results
def sniff(interface):
    print("Sniffing on: ", interface)
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
		imsitracker.sqlite_file(options.sqlite)

	imsitracker.show_all_tmsi=options.show_all_tmsi
	imsi_to_track=""
	if options.imsi:
		imsi="9"+options.imsi.replace(" ", "")
		imsi_to_track_len=len(imsi)
		if imsi_to_track_len%2 == 0 and imsi_to_track_len > 0 and imsi_to_track_len <17:
			for i in range(0, imsi_to_track_len-1, 2):
				imsi_to_track+=chr(int(imsi[i+1])*16+int(imsi[i]))
			imsi_to_track_len=len(imsi_to_track)
		else:
			print("Wrong size for the IMSI to track!")
			print("Valid sizes :")
			print("123456789101112")
			print("1234567891011")
			print("12345678910")
			print("123456789")
			print("1234567")
			print("12345")
			print("123")
			exit(1)
	imsitracker.track_this_imsi(imsi_to_track)
	if options.sniff:
		from scapy.all import sniff, UDP
		imsitracker.header()
		sniff(iface=options.iface, filter="port {} and not icmp and udp".format(options.port), prn=find_imsi_from_pkg, store=0)
	else:
		imsitracker.header()
		udpserver(port=options.port, prn=find_imsi)
Example #52
0
            # spoof the packet.
            if site_in_list:

                # Create a spoofed packet
                spf_resp = IP(
                    src=DNS_SERVER_IP, dst=pkt[IP].src) / UDP() / DNS(an=DNSRR(
                        rrname=pkt[DNSQR].qname, ttl=299, rdata='127.0.0.1'))

                # Print for demo purposes
                print(
                    "******************** SITE IN BANNED LIST *****************"
                )
                print(
                    "****************** SPOOFED PACKET BELOW ******************"
                )
                spf_resp.show()

                # Send spoofed packet
                send(spf_resp, verbose=2, iface=IFACE)

                return f"Spoofed DNS Response Sent: {pkt[IP].src}"

            else:
                # Send the real response packet
                return forward_dns(pkt)

    return get_response


sniff(filter=BPF_FILTER, prn=dns_responder(DNS_SERVER_IP), iface=IFACE)
Example #53
0
def sniff(interface):
    scapy.sniff(
        iface=interface, store=False, prn=process_sniffed_packet
    )  #prn is for call back function at every packet sniff function captures it will call process_sniffed_packet
Example #54
0
 def run(self):
     ''' to sniff tcp packets on the desired interface'''
     sniff(iface=self.interface, filter='tcp', prn=self.sniff_urls)
Example #55
0
import scapy.all as spy
import Wireshark_utils as WsU

print("Scapy is Imported")

rd_packets = spy.rdpcap("example_network_traffic.pcap")
print(len(rd_packets))
for one in rd_packets:
    p = WsU.get_show_data(one)
    for i in p:
        print(i)
spy.hexdump(rd_packets[0])

print("Start Sniffing")
packets = spy.sniff(filter="", timeout=10)
for i in packets:
    print(i.summary())
print(len(packets))
Example #56
0
        print "\nDecoded message is:"
        print processcookies(cookies)
      break


if __name__ == '__main__':
  import sys

  if len(sys.argv) == 2 and sys.argv[1] == "-s":
    ## Standalone sniffing mode
    from scapy.all import sniff

    print "Entering standalone sniffing mode"
    print "Warning! Can not send responses in this mode!"

    sniff(filter="tcp and dst port 80", prn=standalone_process)
  elif len(sys.argv) == 2 and sys.argv[1] == "-h":
    ## Usage message

    print "Client: cookiemonster.py [server] [message]"
    print "Server: cookiemonster.py -s"
  elif len(sys.argv) == 3:
    ## Client mode
    import urllib2

    print "Sending message to " + sys.argv[1] + "..."

    l = 0
    while l < len(sys.argv[2]):
      orig = sys.argv[2][l:l+33]
      l += 33
Example #57
0
 def sniff(self):
     # start sniffing for probe requests
     logging.info("Sniff starting...")
     sniff(iface=self.iface, prn=self.sniffCallback)
def sniff(interface):
    # iface: interface
    # store: store packets
    # prn: callback function
    scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
Example #59
0
def main():
    parser = optparse.OptionParser()
    parser.add_option('--tun-addr',
                      dest='taddr',
                      help='set tunnel local address')
    parser.add_option('--tun-dstaddr',
                      dest='tdstaddr',
                      help='set tunnel destination address')
    parser.add_option('--tun-netmask',
                      default='255.255.255.0',
                      dest='tmask',
                      help='set tunnel netmask')
    parser.add_option('--tun-mtu',
                      type='int',
                      default=1500,
                      dest='tmtu',
                      help='set tunnel MTU')
    parser.add_option('--local-addr',
                      default='0.0.0.0',
                      dest='laddr',
                      help='set local address [%default]')
    parser.add_option('--remote-addr',
                      dest='raddr',
                      help='set remote address [%default]')
    parser.add_option('--role',
                      default='client',
                      dest='role',
                      help='set role client or server [%default]')
    parser.add_option('--password',
                      default='password',
                      dest='password',
                      help='set password used to encrypt [%default]')
    opt, args = parser.parse_args()
    ntpPort = 123
    if not (opt.taddr and opt.tdstaddr):
        parser.print_help()
        return 1
    # The client has to specify a remote address
    if opt.role == "client" and not opt.raddr:
        parser.print_help()
        return 1
    try:
        ntpFieldLength = b'\x00\x12'
        ntpFieldTypeRequest = b'\xFF\x00'
        ntpFieldTypeResponse = b'\x00\xFF'
        padding = b'\xFF' * 16

        if (opt.role == "client"):
            # Send tunnel request
            ntpHeader = bytes(
                NTP(leap=3,
                    version=4,
                    mode=3,
                    stratum=0,
                    poll=3,
                    precision=250,
                    delay=1,
                    dispersion=1,
                    id="",
                    ref=0,
                    orig=0,
                    recv=0,
                    sent=None))

            # Build encapsulated packet
            encapsulatedPacket = IP(dst=opt.raddr, src=opt.laddr)/UDP(sport=ntpPort,dport=ntpPort)/ \
                                  (ntpHeader +
                                  ntpFieldTypeRequest +
                                  ntpFieldLength +
                                  padding)
            print("Sending tunnel request to %s." % (opt.raddr))
            send(encapsulatedPacket)

            # Wait for tunnel response coming in
            print("Waiting for reply.")
            while True:
                # Wait for tunnel request coming in
                packet = sniff(filter="udp port 123", count=1)

                # Check if it is a tunnel request
                if packet[0]["IP"]["UDP"]["NTP"][
                        "Raw"].load[:2] == ntpFieldTypeResponse:
                    break

            # Set up tunnel
            print("Set up tunnel.")
            server = TunnelServer(opt.taddr, opt.tdstaddr, opt.tmask, opt.tmtu,
                                  opt.laddr, ntpPort, opt.raddr, ntpPort,
                                  opt.role, opt.password)

        else:
            print("Waiting for request.")
            requestAddress = None
            while requestAddress == None:
                # Wait for tunnel request coming in
                packet = sniff(filter="udp port 123", count=1)

                # Check if it is a tunnel request
                if packet[0]["IP"]["UDP"]["NTP"][
                        "Raw"].load[:2] == ntpFieldTypeRequest:
                    requestAddress = packet[0]["IP"].src
                    print("Got request from %s." % (requestAddress))
                    break

            # We need to sleep for a second here to wait for the sniffer
            # to start at the client side.
            sleep(1)

            # Send response to requestAddress
            ntpHeader = bytes(
                NTP(leap=0,
                    version=4,
                    mode=4,
                    stratum=2,
                    poll=3,
                    precision=236,
                    delay=(0.1 * random.random()),
                    dispersion=(0.002 + 0.001 * random.random()),
                    id=opt.laddr,
                    ref=None,
                    orig=None,
                    recv=None,
                    sent=None))

            # Build encapsulated packet
            encapsulatedPacket = IP(dst=requestAddress, src=opt.laddr) / UDP(
                sport=ntpPort,
                dport=ntpPort) / (ntpHeader + ntpFieldTypeResponse +
                                  ntpFieldLength + padding)
            print("Sending response to %s." % (requestAddress))
            send(encapsulatedPacket)

            # Set up tunnel
            print("Set up tunnel.")
            server = TunnelServer(opt.taddr, opt.tdstaddr, opt.tmask, opt.tmtu,
                                  opt.laddr, ntpPort, requestAddress, ntpPort,
                                  opt.role, opt.password)
    except (pytun.Error, socket.error) as e:
        print >> sys.stderr, str(e)
        return 1
    server.run()
    return 0
Example #60
-1
 def sniff(self):
         if self.options.pcap_file == 'None':
                 self.logger.info("Using network interface: %s" % (self.options.listen_interface))
                 try:
                         scapy.sniff(iface = self.options.listen_interface, prn = self.pkt_callback, lfilter = self.pkt_check, filter = self.options.filter, store = 0)
                 except socket.error, e:
                         self.logger.error("Sniffer error on %s: %s" % (self.options.listen_interface, e))