예제 #1
0
 def __init__(self, device, snaplen, promisc, to_ms):
     # Normal pypcap module has no timeout parameter,
     # only the specially patched "scapy" variant has.                 
     if "scapy" in pcap.__version__.lower():
         self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms)
     else:
         self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1)                    
예제 #2
0
파일: fivlogic.py 프로젝트: gashero/pids
def initial_pcap(bpfstr,device=None):
    if device:
        pc=pcap.pcap(device)
    else:
        pc=pcap.pcap()
    pc.setfilter(bpfstr)
    return pc
예제 #3
0
    def run(self):  #设置的抓取时间里pcap一直抓包,各个队列累加数值,最后除以时间,即平均
        dict = {}
        for i in iplist:
            d = i.split('/')
            cmin, cmax = ipto(d[0], int(d[1]))
            dict[cmin] = cmax  #这里记录一个字典,key是ip段最小的的ip,value是最大的ip

        if self.eth == 'all':
            pc = pcap.pcap()
        else:
            pc = pcap.pcap(self.eth)
        for ptime, pdata in pc:
            #try:
            #    ip_type = socket.ntohs(struct.unpack("H",pdata[12:14])[0])  #
            #except:
            #     pass
            #if ip_type != 2048:
            #    continue
            s_uip = socket.ntohl(
                struct.unpack("I", pdata[14 + 12:14 + 16])[0])  #源ip的网络字节序
            #d_uip = socket.ntohl(struct.unpack("I",pdata[14+16:14+20])[0])  #目的ip的网络字节序
            bytes = socket.ntohs(struct.unpack(
                "H", pdata[14 + 2:14 + 4])[0]) + 14  #数据的字节数
            if self.check(dict, s_uip):
                self.bytes_out += bytes
                self.packets_out += 1
            else:
                self.bytes += bytes
                self.packets += 1
예제 #4
0
파일: pcapdnet.py 프로젝트: baarse/scapy-1
 def __init__(self,
              device,
              snaplen,
              promisc,
              to_ms,
              monitor=False):  # noqa: E501
     try:
         self.pcap = pcap.pcap(device,
                               snaplen,
                               promisc,
                               immediate=1,
                               timeout_ms=to_ms,
                               rfmon=monitor)  # noqa: E501
     except TypeError:
         try:
             if monitor:
                 warning(
                     "Your pypcap version is too old to support monitor mode, Please use pypcap 1.2.1+ !"
                 )  # noqa: E501
             self.pcap = pcap.pcap(
                 device,
                 snaplen,
                 promisc,
                 immediate=1,
                 timeout_ms=to_ms)  # noqa: E501
         except TypeError:
             # Even older pypcap versions do not support the timeout_ms argument  # noqa: E501
             self.pcap = pcap.pcap(device,
                                   snaplen,
                                   promisc,
                                   immediate=1)  # noqa: E501
예제 #5
0
def test_pcap_overwritten():

    for repetitions in range(1000):
        thread_pkts_a = PktsThread('test.pcap')
        thread_pkts_b = PktsThread('arp.pcap')
        thread_pkts_a.start()
        thread_pkts_b.start()
        thread_pkts_a.join()
        thread_pkts_b.join()
        packets_a = [x[1] for x in thread_pkts_a.pkts]
        packets_a_copy = [t[1] for t in pcap.pcap(relative_file('test.pcap'))]
        # debug only
        # if packets_a != packets_a_copy:
        #    import pdb; pdb.set_trace()
        packets_b = [x[1] for x in thread_pkts_b.pkts]
        packets_b_copy = [t[1] for t in pcap.pcap(relative_file('arp.pcap'))]

        # two pcaps to check cross-influence (overwriting)
        assert all(
            packets_a[i][:] == packets_a_copy[i][:]
            for i in range(len(packets_a))
        )
        assert all(
            packets_b[i][:] == packets_b_copy[i][:]
            for i in range(len(packets_b))
        )

        # single pcap to check if a single buffer isn't reused
        assert len(set(p[:] for p in packets_a)) > 1
        assert len(set(p[:] for p in packets_b)) > 1
예제 #6
0
 def __init__(self, device, snaplen, promisc, to_ms):
     try:
         self.pcap = pcap.pcap(
             device, snaplen, promisc, immediate=1, timeout_ms=to_ms)
     except TypeError:
         # Older pypcap versions do not support the timeout_ms
         # argument
         self.pcap = pcap.pcap(
             device, snaplen, promisc, immediate=1)
예제 #7
0
 def __init__(self, device, snaplen, promisc, to_ms, monitor=False):  # noqa: E501
     try:
         self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms, rfmon=monitor)  # noqa: E501
     except TypeError:
         try:
             if monitor:
                 warning("Your pypcap version is too old to support monitor mode, Please use pypcap 1.2.1+ !")  # noqa: E501
             self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1, timeout_ms=to_ms)  # noqa: E501
         except TypeError:
             # Even older pypcap versions do not support the timeout_ms argument  # noqa: E501
             self.pcap = pcap.pcap(device, snaplen, promisc, immediate=1)  # noqa: E501
예제 #8
0
    def run(self):
        if self.iface:
            pc = pcap.pcap(name=self.iface)
        else:
            pc = pcap.pcap()

        decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback,
                   pcap.DLT_NULL:dpkt.loopback.Loopback,
                   pcap.DLT_EN10MB:dpkt.ethernet.Ethernet } [pc.datalink()]

        print 'listening on %s: %s' % (pc.name, pc.filter)
        for ts, pkt in pc:
            self.process(ts, decode(pkt))
예제 #9
0
 def __init__(self, device, snaplen, promisc, to_ms):
     # Normal pypcap module has no timeout parameter,
     # only the specially patched "scapy" variant has.
     if "scapy" in pcap.__version__.lower():
         self.pcap = pcap.pcap(device,
                               snaplen,
                               promisc,
                               immediate=1,
                               timeout_ms=to_ms)
     else:
         self.pcap = pcap.pcap(device,
                               snaplen,
                               promisc,
                               immediate=1)
예제 #10
0
 def __init__(self, input_device, snaplen=2000, filter_rules=None):
     # check if the devname is an interface or not.
     if input_device in pcap.findalldevs():
         self._pc = pcap.pcap(input_device, snaplen, immediate=True)
     else:
         self._pc = pcap.pcap(input_device, timeout_ms=0)
     # set filter.
     self._pc.setfilter(filter_rules)
     dprint("dloff:", self._pc.dloff)
     dprint("fd:", self._pc.fd)
     dprint("filter:", self._pc.filter)
     dprint("name:", self._pc.name)
     dprint("snaplen:", self._pc.snaplen)
     dprint("nb_blk:", self._pc.getnonblock())
예제 #11
0
    def run(self):
        if self.iface:
            pc = pcap.pcap(name=self.iface)
        else:
            pc = pcap.pcap()

        decode = {
            pcap.DLT_LOOP: dpkt.loopback.Loopback,
            pcap.DLT_NULL: dpkt.loopback.Loopback,
            pcap.DLT_EN10MB: dpkt.ethernet.Ethernet
        }[pc.datalink()]

        print 'listening on %s: %s' % (pc.name, pc.filter)
        for ts, pkt in pc:
            self.process(ts, decode(pkt))
예제 #12
0
파일: rtbm.py 프로젝트: gnvo/rtbm
	def __init__( self, direction ):
		threading.Thread.__init__( self )
		self.direction = direction
		self.pc = pcap.pcap(iface, 65535, False)
		self.pc.setdirection(direction);
		self.pc.setfilter("proto 6 or 17")
		self.counter = Counter()
예제 #13
0
	def __init__(self, opts):
		print opts
		self.opts = opts
		self.pc = pcap.pcap()
		self.uniq = set()
		if self.opts.load_record:
			try:
				f = open(self.opts.record_file, 'r')
				print 'loading md5s...'
				for l in f.readlines():
					ss = l.split('\t')
					if len(ss)<4:
						continue
					ip = ss[1]
					host = ss[2]
					cookie = ss[4]
					src = ip + host + cookie
					md5s = hashlib.md5(src).hexdigest().upper()
					if not md5s in self.uniq:
						self.uniq.add(md5s)
					if not l:
						break
				f.close()
				print 'loaded %d md5s'%len(self.uniq)
			except:
				pass
		self.log = open(self.opts.record_file, 'a+')
		if self.opts.port:
			self.pc.setfilter('tcp dst port %s'%self.opts.port)
		else:
			self.pc.setfilter('tcp')
예제 #14
0
파일: test.py 프로젝트: vaporize93/pypcap
 def test_pcap_errors(self):
     p = pcap.pcap('test.pcap')
     try:
         print(p.stats())
     except OSError:
         pass
     assert p.geterr() != '', 'pcap_geterr'
예제 #15
0
def capPkt(filters, ports):
    pc = pcap.pcap()
    pc.setfilter(filters)
    for ts, pkt in pc:
        eth = dpkt.ethernet.Ethernet(pkt)
        ports["cap"] = eth.data.data.sport
        return
예제 #16
0
 def run_capture(self):
     """
         capture the data and save it in a queue (running by a thread)
         :return:
     """
     with self.guard():
         while not self.need_quit:
             recv_count = 0
             cap = pcap.pcap(self.wdev)
             for packet in cap:
                 if self.need_quit:
                     break
                 # log('start capture loop')
                 if packet is None:
                     continue
                 timestamp, rtpacket = packet
                 result = parse_packet(rtpacket)
                 if result is None:
                     # log('failed to parse the packet')
                     continue
                 signal, client_mac = result
                 with self.lock_signals:
                     que = self.signals[client_mac]
                     que.append((timestamp, signal))
                 recv_count += 1
예제 #17
0
	def __iter__ (self):
		pc = pcap.pcap(self.interface,promisc=self.promiscuous)
		pc.setfilter('tcp and port 25')
		decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback,
		           pcap.DLT_NULL:dpkt.loopback.Loopback,
		           pcap.DLT_EN10MB:dpkt.ethernet.Ethernet }[pc.datalink()]

		print 'listening on %s: %s' % (pc.name, pc.filter)

		for timestamp, pkt in pc:
			if self.expire and timestamp > self.expire:
				break
			ip = decode(pkt).ip
			tcp = ip.tcp
			sip = 0
			dip = 0
			for c in [ord(c) for c in ip.src]:
				sip <<= 8
				sip += c
			for c in [ord(c) for c in ip.dst]:
				dip <<= 8
				dip += c
			sport = int(tcp.sport)
			dport = int(tcp.dport)
			data = str(tcp.data)
			yield (sip,sport),(dip,dport),data
예제 #18
0
파일: test.py 프로젝트: junshoong/pypcap
 def test_pcap_errors(self):
     p = pcap.pcap('test.pcap')
     try:
         print(p.stats())
     except OSError:
         pass
     assert p.geterr() != '', 'pcap_geterr'
예제 #19
0
    def classificar_protocol(self, protocols):
        #nPkts=0
        for ts, pkt in pcap.pcap('test-capture.pcap'):
            #nPkts += 1
            
            eth = dpkt.ethernet.Ethernet(pkt) #extraindo dados do pacote
            ip = eth.data
            if isinstance(ip,dpkt.ip.IP):
                    transp = ip.data
                    if isinstance(transp,dpkt.tcp.TCP):
                        app = transp.data.lower()
                        self.get_protocol_trans_tcp(app,eth,ts)
                    elif isinstance(transp,dpkt.udp.UDP):
                        app = transp.data.lower()
                        self.get_protocol_trans_udp(app,eth,ts)
                            
            else:
                    self.cNonIP += 1
                    tupla = "unknown","sem info"
                    self.modifier_tupla(tupla)

            #if (nPkts == self.maxPkts):
                    #break
            
        for p in self.cnt.items():
            print(p[0]+" Pkts:"+str(p[1]))
        print("Non IP Pkts:"+str(self.cNonIP))
예제 #20
0
    def capture(self):
        f = open("filter.txt","r")
        filter = f.readlines()[1]
        print filter
        filter = "host 10.0.0.135 and not arp and not ip dst or src 61.142.238.88"
        pc=pcap.pcap()    #注,参数可为网卡名,如eth0
        pc.setfilter(filter)    #设置监听过滤器
        for ptime,pdata in pc:
            p=Ethernet(pdata)
            try:
                recv_len=len(pdata)
                if recv_len == 102 and pdata[42]== chr(02) and pdata[101] == chr(03):
                    print struct.unpack('>I',pdata[49:53])[0]
                    print '登陆了'
                elif recv_len == 55:
                    print struct.unpack('>I',pdata[49:53])[0]
                    print '登陆了'

                #sStr1 = p.data.data.data
                srcip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.src)))
                ip='%d.%d.%d.%d'%tuple(map(ord,list(p.data.dst)))

                print '========================================================='
                print 'time = ',formattime(ptime)
                print p.data.__class__.__name__ #maybe is IP
                print p.data.data.__class__.__name__    #maybe is TCP
                print '%s------->%s,PORT:%d' %(srcip,ip,p.data.data.dport)
                print 'data = ',sStr1

            except:
                pass
예제 #21
0
def sniff(args):
	custfind = []
	for cmd in args.cmdhex:
		custfind.append(cmd.decode('hex'))
	seen = {}
	pc = pcap.pcap()
	pc.setfilter('udp and port ' + str(int(args.port)))
	for ts, pkt in pc:
		packet = dpkt.ethernet.Ethernet(pkt)
		pdat = str(packet.data)[28:]
		phead = str(packet.data)[0:27]
		if args.nmac or not str(phead[0:6]) in args.macs:
			if args.dpings and len(str(packet.data)) == 57 and pdat[0:3] == '\x0d\x02\x00':
				parseping(packet, 'ping request', args)

			if args.dpingreps and len(str(packet.data)) == 57 and pdat[0:3] == '\x0c\x02\x00':
				parseping(packet, 'ping response', args)
			
			if args.dconnect1 and pdat[0:3] == '\x01\x02\x00':
				parsepacket(packet, 'connect1',  args)

			if args.ddata and pdat[0:2] == '\x06\x02':
				parsepacket(packet, 'data', args)
			
			if len(custfind) and pdat[0] in custfind:
				parsepacket(packet, 'Cx'+pdat[0].encode('hex'), args)
예제 #22
0
파일: test_pcap.py 프로젝트: minggLu/pypcap
 def test_pcap_errors(self):
     p = pcap.pcap("test.pcap")
     try:
         print p.stats()
     except OSError:
         pass
     assert p.geterr() != "", "pcap_geterr"
예제 #23
0
    def iniciarColeta(self,arquivo = None,timeMaximo = 45): #Se nao haver nenhum arquivo e nenhum tempo de funcionamento especificado o default eh de 60 segundos
        try:
            self.abrirArquivoLog()
            ini = time.time()
            maxi = 1
            for ts, pkt in pcap.pcap(arquivo):

                atual = time.time()
                if atual - ini > timeMaximo:
                    break

                enl = dpkt.ethernet.Ethernet(pkt) #extraindo dados do pacote
                print "Pacote %i. Data Link Layer = Ethernet" %(maxi)
                #self.__arq.write(...)
                red = enl.data

                if type(red) != type (""): 
                    self.classificarRede(red)  
                    transp = red.data

                    if type(transp) != type (""):            
                        self.classificarTransporte(transp)
                        app = transp.data
                        self.classificarApp(app)

                maxi +=1
            self.fecharArquivoLog()
        except(KeyboardInterrupt, SystemExit):
            self.fecharArquivoLog()                

        self.fecharArquivoLog()
예제 #24
0
def analyze(s):
    ips = {}
    pc = pcap.pcap(optdict["-i"])
    proto = "tcp"
    if "-u" in optdict:
        proto += " or udp"
    pc.setfilter(proto)
    t = time.time()

    try:
        for ts, pkt in pc:
            eth = dpkt.ethernet.Ethernet(pkt)
            if hasattr(eth, "ip6"):
                continue
            ip = eth.data
            logging.info(
                "%s:%d -> %s:%d" % (socket.inet_ntoa(ip.src), ip.data.dport, socket.inet_ntoa(ip.dst), ip.data.sport)
            )
            inaddr = ipfilter(ip)
            if inaddr is None:
                continue
            ips.setdefault(inaddr, IpStatus(inaddr))
            ips[inaddr].add(eth)

            if optdict["-k"] and time.time() - t > optdict["-k"]:
                break
    except KeyboardInterrupt:
        pass

    for v in ips.values():
        v.detect(s)
    s.flush()
예제 #25
0
 def __init__(self, args):
     GLHack.__init__(self, args)
     glutInit()
     self.initGL()
     self.pcap = pcap.pcap()
     self.pcap.setnonblock()
     self.frames = 0
예제 #26
0
파일: api.py 프로젝트: stamak/fuel-web
    def get_probe_frames(self, iface, vlan=False):
        if iface not in self.neighbours:
            self.neighbours[iface] = {}
        """
        We do not use scapy filtering because it is slow. Instead we use
        python binding to extreamely fast libpcap library to filter out
        probing packages.
        """
        pc = pcap.pcap(iface)
        filter_string = 'udp and dst port {0}'.format(self.config['dport'])
        if vlan:
            filter_string = 'vlan and {0}'.format(filter_string)
        pc.setfilter(filter_string)

        def fltr(p):
            try:
                received_msg = str(p[scapy.UDP].payload)[:p[scapy.UDP].len]
                decoded_msg = received_msg.decode()
                return decoded_msg.startswith(self.config["cookie"])
            except Exception as e:
                self.logger.debug("Error while filtering packet: %s", str(e))
                return False

        pprn = functools.partial(self.fprn, iface=iface)
        try:
            while True:
                ts, pkt = pc.next()
                p = scapy.Ether(pkt)
                if fltr(p):
                    pprn(p)
        except (KeyboardInterrupt, SystemExit):
            pass
예제 #27
0
def get_udp_from_dev(network='10.168.103.0', port='14550'):
    devs = pcap.findalldevs()
    pc = None
    for dev in devs:
        try:
            t = inet_to_str(pcap.lookupnet(bytearray(dev, 'utf-8'))[0])
        except Exception as e:
            print(e)
        if t == network:
            pc = pcap.pcap(dev)
    if not pc:
        return False

    pc.setfilter('udp')  #设置监听过滤器,这里指定port 'udp port 54915'
    for ts, buf in pc:
        eth = dpkt.ethernet.Ethernet(buf)
        if not isinstance(eth.data, dpkt.ip.IP):
            print('Non IP Packet type not supported %s\n' %
                  eth.data.__class__.__name__)
            continue
        ip = eth.data
        if isinstance(ip.data, dpkt.udp.UDP):
            udp = ip.data
            print('[+] Src:', udp.sport, ' --> Dst:', udp.dport)

        do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)
        more_fragments = bool(ip.off & dpkt.ip.IP_MF)
        fragment_offset = ip.off & dpkt.ip.IP_OFFMASK
        print('Timestamp: ', str(datetime.datetime.utcfromtimestamp(ts)))
        print('Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst),
              eth.type)
        print ('IP: %s -> %s   (len=%d ttl=%d DF=%d MF=%d offset=%d)' % \
(inet_to_str(ip.src),inet_to_str(ip.dst), ip.len, ip.ttl, do_not_fragment, more_fragments,fragment_offset))
예제 #28
0
파일: carver.py 프로젝트: rc1405/Minerva
 def carve_pcap_file(self, options, count, thres_time, pcap_file, out_file, out_pcap):
     protocols = {
         'TCP': 'tcp and (host %s and port %i) and (host %s and port %i)' % (options['src_ip'], options['src_port'], options['dest_ip'], options['dest_port']),
         6: 'tcp and (host %s and port %i) and (host %s and port %i)' % (options['src_ip'], options['src_port'], options['dest_ip'], options['dest_port']),
         'UDP': 'udp and (host %s and port %i) and (host %s and port %i)' % (options['src_ip'], options['src_port'], options['dest_ip'], options['dest_port']),
         17: 'udp and (host %s and port %i) and (host %s and port %i)' % (options['src_ip'], options['src_port'], options['dest_ip'], options['dest_port']),
         'ICMP': 'ICMP and host %s and host %s' % (options['src_ip'], options['dest_ip']),
         1: 'ICMP and host %s and host %s' % (options['src_ip'], options['dest_ip']),
     }
     if not options['proto'] in protocols.keys():
         raise("Protocol %s not supported" % str(options['proto']))
     event_time = int(options['event_time'])
     max_packets = int(self.config['max_packets'])
     max_size = int(self.config['max_size']) * 1024 * 1024
     write_pcap = out_pcap.writepkt
     pcap_size = out_file.tell
     open_pcap_file = pcap.pcap(pcap_file)
     open_pcap_file.setfilter(protocols[options['proto']])
     for ts, pkt in open_pcap_file:
         if ts < int(event_time):
             continue
         if ts > int(thres_time):
             return 'END', count
         write_pcap(pkt, ts=ts)
         count = count + 1
         if count == max_packets:
             return 'END', count
         if int(pcap_size()) >= max_size:
             return 'END', count
     return 'CONTINUE', count
예제 #29
0
def test_pcap_errors():
    p = pcap.pcap(relative_file('test.pcap'))
    try:
        print p.stats()
    except OSError:
        pass
    assert p.geterr() != '', 'pcap_geterr'
예제 #30
0
    def start_pcap(self):
        (self.dpktfh, self.dpktfile) = tempfile.mkstemp()
        if self.debug:
            print "Starting pcap capture, saving in file", self.dpktfile
        self.pid_pcap = os.fork()
        if self.pid_pcap == 0:
            # Child, reads pcap, outputs to a file in dpkt format
            pc = 0
            try:
                pc = pcap.pcap(self.interface)
            except:
                print >> sys.stderr, "Cannot run packet filter, aborting"
                sys.exit(1)

            # filter on our dedciated subnets
            pc.setfilter('net 192.18.0.0/15 and net 192.0.2.0/24')
            for ts, pkt in pc:
                lp = dpkt.loopback.Loopback(pkt)
                ip = dpkt.ip.IP(str(lp.data))
                os.write(self.dpktfh, "SRC=" + dnet.ip_ntoa(ip.src) + "\n")
                os.write(self.dpktfh, "DST=" + dnet.ip_ntoa(ip.dst) + "\n")
                os.write(self.dpktfh, "ID=%d\n" % ip.id)
                os.write(self.dpktfh, "TTL=%d\n" % ip.ttl)
                os.write(self.dpktfh, "DATA=" + ` ip.data ` + "\n")
                os.write(self.dpktfh, "\n")
            exit
            # Parent returns
        return 0
예제 #31
0
    def classificar_protocol(self, protocols):
        maxPkts = 100
        nPkts=0
        cnt = {"bittorrent":0,"dhcp":0,"http":0,"ssdp":0,"ssh":0,"ssl":0,"noClass":0}
        #contadores
        cNonIP = 0
        cNonIP = 0
        
        for ts, pkt in pcap.pcap():
            nPkts += 1
            
            eth = dpkt.ethernet.Ethernet(pkt) #extraindo dados do pacote
            ip = eth.data
            if isinstance(ip,dpkt.ip.IP):
                    transp = ip.data
                    if isinstance(transp,dpkt.tcp.TCP) or isinstance(transp,dpkt.udp.UDP):
                            app = transp.data.lower()
                            found = False
                            for p in protocols.items():
                                    if p[1].search(app):
                                            tupla = (len(app),ts,eth,ip,app)
                                            self.enviar_pkt(tupla)
                                            cnt[p[0]] += 1
                                            found = True
                            if (not found):
                                    cnt["noClass"] += 1
            else:
                    cNonIP += 1

            if (nPkts == maxPkts):
                   break
            
        for p in cnt.items():
            print(p[0]+" Pkts:"+str(p[1]))
        print("Non IP Pkts:"+str(cNonIP))
예제 #32
0
def main():
    opts, args = getopt.getopt(sys.argv[1:], 'i:hln')
    name = None
    use_loop = False
    timestamp_in_ns = False
    for o, a in opts:
        if o == '-i':
            name = a
        elif o == '-l':
            use_loop = True
        elif o == '-n':
            timestamp_in_ns = True
        else:
            usage()

    pc = pcap.pcap(name, timeout_ms=50, timestamp_in_ns=timestamp_in_ns)
    pc.setfilter(' '.join(args))
    decode = {
        pcap.DLT_LOOP: dpkt.loopback.Loopback,
        pcap.DLT_NULL: dpkt.loopback.Loopback,
        pcap.DLT_EN10MB: dpkt.ethernet.Ethernet
    }[pc.datalink()]

    print('listening on %s: %s' % (pc.name, pc.filter))
    try:
        if use_loop:
            loop(pc, decode)
        else:
            iter(pc, decode)
    except KeyboardInterrupt:
        nrecv, ndrop, nifdrop = pc.stats()
        print('\n%d packets received by filter' % nrecv)
        print('%d packets dropped by kernel' % ndrop)
예제 #33
0
    def __iter__(self):
        pc = pcap.pcap(self.interface, promisc=self.promiscuous)
        pc.setfilter('tcp and port 25')
        decode = {
            pcap.DLT_LOOP: dpkt.loopback.Loopback,
            pcap.DLT_NULL: dpkt.loopback.Loopback,
            pcap.DLT_EN10MB: dpkt.ethernet.Ethernet
        }[pc.datalink()]

        print 'listening on %s: %s' % (pc.name, pc.filter)

        for timestamp, pkt in pc:
            if self.expire and timestamp > self.expire:
                break
            ip = decode(pkt).ip
            tcp = ip.tcp
            sip = 0
            dip = 0
            for c in [ord(c) for c in ip.src]:
                sip <<= 8
                sip += c
            for c in [ord(c) for c in ip.dst]:
                dip <<= 8
                dip += c
            sport = int(tcp.sport)
            dport = int(tcp.dport)
            data = str(tcp.data)
            yield (sip, sport), (dip, dport), data
예제 #34
0
파일: arp.py 프로젝트: BenjaminUJun/slick
def loop(ifname, pflag, cnt, out, tflag, vflag):
    try:
        if ifname is None:
            ifname = pcap.pcap_lookupdev()
        if tflag is False:
            out.write("Starting ARP packet capture on `%s':\n" % ifname)
            out.write(
                "[PCAP library version is: `%s']\n" % pcap.pcap_lib_version()
                )
        p = pcap.pcap(ifname, pcap.PCAP_SNAPLEN_DFLT, pflag)
        if p.datalink() != pcap.DLT_EN10MB:
            raise pcap.error, "`%s' is not an ethernet device" % ifname
        bpfp = p.compile(
            'arp and arp[0:2] = %d and arp[2:2] = %d' %
            (ARP.HARDWARE_ETHER, ARP.PROTOCOL_IP))
        p.setfilter(bpfp)
        if tflag is True:
            pd = p.dump_fopen(out)
            p.loop(cnt, pcap.pcap_dump, pd)
        else:
            p.loop(cnt, process_pkt, (out, vflag))
        sys.exit(0)
    except KeyboardInterrupt:
        p.breakloop()
        if tflag is False:
            out.write('\n\n<< Exiting on keyboard interrupt >>\n')
        sys.exit(0)
    except pcap.error, msg:
        out.write('%s: fatal error: %s\n' %
                  (os.path.basename(sys.argv[0]), msg)
                  )
        sys.exit(1)
예제 #35
0
 def run_capture(self):
     """
         capture the data and save it in a queue (running by a thread)
         :return:
     """
     with self.guard():
         while not self.need_quit:
             recv_count = 0
             cap = pcap.pcap(self.wdev)
             for packet in cap:
                 if self.need_quit:
                     break
                 # log('start capture loop')
                 if packet is None:
                     continue
                 timestamp, rtpacket = packet
                 result = parse_packet(rtpacket)
                 if result is None:
                     # log('failed to parse the packet')
                     continue
                 signal, client_mac = result
                 with self.lock_signals:
                     que = self.signals[client_mac]
                     que.append((timestamp, signal))
                 recv_count += 1
예제 #36
0
 def load(self):
     """Load pcap file
     """
     pc = pcap.pcap(self.filename)
     for ts, pkt in pc:
         p = dpkt.ethernet.Ethernet(pkt)
         self.packets.append((ts, p.pack()))
예제 #37
0
def main(argv):
    """
    Запускается сниффер и полученыые пакеты передаются в очередь RubbitMQ
    :param argv: В качестве аргументов принимает название интерфейса,
    который необходимо прослушивать
    """
    try:
        opts, args = getopt.getopt(argv, "hi:", ["interface="])
    except getopt.GetoptError:
        print 'dns-sniffer.py -i <interface>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'dns-sniffer.py -i <interface>'
            sys.exit()
        elif opt in ("-i", "--interface"):
            interface = arg
    pc = pcap.pcap(name=interface)
    pc.setfilter('udp src port 53')

    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    channel.queue_declare(queue='dns')


    for ts, pkt in pc:
        channel.basic_publish(exchange='', routing_key='dns', body=pkt)
    connection.close()
예제 #38
0
def sniff(local, iface):
	print '**Note: Lister.py will only show new unique connections.'
	connections = []
	pc = pcap.pcap(iface, immediate=True)
	pc.setfilter('tcp')
	for dual in pc:
		if(dual ==None):
			continue

		ts = dual[0]
		pkt = dual[1]
		try:
			eth = dpkt.ethernet.Ethernet(pkt)
			ip = eth.data
			srcIp = socket.inet_ntoa(ip.src)
			dstIp = socket.inet_ntoa(ip.dst)
			if dstIp == local :
				tcp=ip.data
				port = tcp.dport
				if tcp.flags == 2 :
					line = "Connection from  " + srcIp + " to port " + str(port) 
					if line not in connections:
						connections.append(line)
						print line
		except:
			pass
예제 #39
0
def test_pcap_dispatch():
    def __cnt_handler(ts, pkt, d):
        d['cnt'] += 1
    p = pcap.pcap(relative_file('test.pcap'))
    d = {'cnt': 0}
    n = p.dispatch(-1, __cnt_handler, d)
    assert n == 0
    assert d['cnt'] == 6

    def __bad_handler(ts, pkt):
        raise NotImplementedError
    p = pcap.pcap(relative_file('test.pcap'))
    try:
        p.dispatch(-1, __bad_handler)
    except NotImplementedError:
        pass
예제 #40
0
        def response_to(ack):
            """Daemon function used to intercept responses from the hijacked session"""
            pcap_filter = 'src host %s and src port %s and dst host %s and dst port %s and tcp' % (
                str_dst_ip, str_dst_port, str_src_ip, str_src_port)
            sock = socket(PF_PACKET, SOCK_RAW)
            sock.bind((self.dev, dpkt.ethernet.ETH_TYPE_ARP))
            packets = pcap.pcap(self.dev)
            packets.setfilter(pcap_filter)
            eth = None
            for _, pkt in packets:
                eth = dpkt.ethernet.Ethernet(pkt)
                ip_packet = eth.data
                tcp = ip_packet.data
                if tcp.seq == ack:
                    seq = tcp.ack
                    if len(tcp.data) > 0:
                        ack += len(tcp.data)
                        tcp_layer = dpkt.tcp.TCP(sport=src_port,
                                                 dport=dst_port,
                                                 seq=seq,
                                                 ack=ack)
                        # build ip layer
                        ip_layer = dpkt.ip.IP(src=src_ip,
                                              dst=dst_ip,
                                              data=tcp_layer)
                        # build ethernet layer
                        eth_layer = dpkt.ethernet.Ethernet(dst=eth.dst,
                                                           src=eth.src,
                                                           type=eth.type,
                                                           data=ip_layer)

                        sock.send(str(eth_layer))
                        sys.stdout.write(tcp.data)
예제 #41
0
def capture_pcap(q: Queue):
    import pcap
    import scapy
    from scapy.layers.l2 import Ether
    from scapy.all import load_layer
    load_layer('inet')
    s = pcap.pcap('eno1', promisc=True, immediate=True)
    s.setfilter('udp portrange 16900-17100')

    def raw_to_dict(data):
        ue = Ether(data)
        ip = ue.payload

        if ip.version != 4:
            return

        if ip.proto != 17:
            return
        udp = ip.payload
        if udp.len == 0:
            return
        if not isinstance(udp.payload, scapy.packet.Raw):
            return
        payload = udp.load
        return {
            'incoming': ip.dst.startswith('192.168.'),
            'data': payload,
            'src_port': udp.sport,
            'dst_port': udp.dport,
        }

    for t, data in s:
        dct = raw_to_dict(data)
        if data:
            q.put_nowait(dct)
예제 #42
0
def capture_test(q, duration, expect_host):
    end_time = datetime.now() + timedelta(seconds=duration)
    pc = pcap.pcap()
    pc.setfilter('tcp port 80')

    for ptime, pdata in pc:
        if datetime.now() >= end_time:
            return
        p = dpkt.ethernet.Ethernet(pdata)
        if p.data.__class__.__name__ == 'IP':
            ip = '%d.%d.%d.%d' % tuple(map(ord, list(p.data.dst)))
            if p.data.data.__class__.__name__ == 'TCP' or p.data.data.__class__.__name__ == 'HTTP':
                # if p.data.data.dport==80:
                #     s =  p.data.data
                #     sStr1 = s.data
                #     host = get_host(sStr1)
                #     print s.ack
                #     print sStr1
                #     if host == expect_host:
                #        q.put(analysis(sStr1))
                if p.data.data.sport == 80:
                    t = p.data.data
                    #print dir(t)
                    #print t.ack
                    print t.data
예제 #43
0
    def sniffer(self, appendPacketModel):
        print("Started. " + self.dev)
        self.packet_count = 0
        sniffer = pcap.pcap(name=self.dev,
                            promisc=True,
                            immediate=True,
                            timeout_ms=50)
        addr = lambda pkt, offset: '.'.join(
            str(pkt[i]) for i in range(offset, offset + 4))

        for ts, pkt in sniffer:
            if (self.sniffer_status == False):
                print("Stop.")
                break

            self.packet_count += 1
            packet = network_sniffer.Packet(sniffer, pkt)
            data = packet.parse()
            # data['id'] = self.packet_count

            appendPacketModel({
                'source': '10.162.31.142',
                'destination': '151.101.74.49',
                'length': 52,
                'id': 1
            })

            print(data)
예제 #44
0
def main(domainlist, interface, regexp):
    """
    Capture positive DNS answers on an interface.
    Collect unique domain names following the regular expression to a text
    file, one record per line.
    """
    readset(domainlist)
    domainre = re.compile(regexp)
    pc = pcap.pcap(name=interface, promisc=False)
    pc.setfilter("udp src port 53")
    if interface == "any":
        frame = dpkt.sll.SLL()  # Linux cooked frame
    else:
        frame = dpkt.ethernet.Ethernet()
    dnsmessage = dpkt.dns.DNS()
    for ts, pkt in pc:
        frame.unpack(pkt)
        try:
            dnsmessage.unpack(frame.data.data.data)
            if dnsmessage.rcode == dpkt.dns.DNS_RCODE_NOERR and \
               dnsmessage.an:
                register_name(domainre, dnsmessage.an[0].name)
        except (KeyboardInterrupt, IOError):
            raise
        except (ValueError, IndexError, dpkt.UnpackError, struct.error):
            pass
예제 #45
0
파일: sniff.py 프로젝트: umitproject/zion
    def start(self, device):
        """
        """
        capture = pcap.pcap(device)
        capture.setfilter(self.filter)
        number = 0
        result = []
        
        for timestamp, packet in capture:
            p = Packet(timestamp, packet, capture.datalink())
            p.disassemble()
            
            self.packets.append(p)
            number += 1

            if len(self.fields):
                s = []
                for f in self.fields:
                    s.append(str(p.get_field(f)))
                #print '(%f)' % p.get_timestamp(),', '.join(s)
                result.append((p.get_timestamp(),s))
            else:
                print '\n', p

            if number == self.amount:
                break

        return result
예제 #46
0
 def __init__(self, direction):
     threading.Thread.__init__(self)
     self.direction = direction
     self.pc = pcap.pcap(iface, 65535, False)
     self.pc.setdirection(direction)
     self.pc.setfilter("proto 6 or 17")
     self.counter = Counter()
예제 #47
0
def analyze(s):
    ips = {}
    pc = pcap.pcap(optdict['-i'])
    proto = 'tcp'
    if '-u' in optdict: proto += ' or udp'
    pc.setfilter(proto)
    t = time.time()

    try:
        for ts, pkt in pc:
            eth = dpkt.ethernet.Ethernet(pkt)
            if hasattr(eth, 'ip6'): continue
            ip = eth.data
            logging.info('%s:%d -> %s:%d' %
                         (socket.inet_ntoa(ip.src), ip.data.dport,
                          socket.inet_ntoa(ip.dst), ip.data.sport))
            inaddr = ipfilter(ip)
            if inaddr is None: continue
            ips.setdefault(inaddr, IpStatus(inaddr))
            ips[inaddr].add(eth)

            if optdict['-k'] and time.time() - t > optdict['-k']: break
    except KeyboardInterrupt:
        pass

    for v in ips.values():
        v.detect(s)
    s.flush()
예제 #48
0
def sniff(args):
    custfind = []
    for cmd in args.cmdhex:
        custfind.append(cmd.decode('hex'))
    seen = {}
    pc = pcap.pcap()
    pc.setfilter('udp and port ' + str(int(args.port)))
    for ts, pkt in pc:
        packet = dpkt.ethernet.Ethernet(pkt)
        pdat = str(packet.data)[28:]
        phead = str(packet.data)[0:27]
        if args.nmac or not str(phead[0:6]) in args.macs:
            if args.dpings and len(str(
                    packet.data)) == 57 and pdat[0:3] == '\x0d\x02\x00':
                parseping(packet, 'ping request', args)

            if args.dpingreps and len(str(
                    packet.data)) == 57 and pdat[0:3] == '\x0c\x02\x00':
                parseping(packet, 'ping response', args)

            if args.dconnect1 and pdat[0:3] == '\x01\x02\x00':
                parsepacket(packet, 'connect1', args)

            if args.ddata and pdat[0:2] == '\x06\x02':
                parsepacket(packet, 'data', args)

            if len(custfind) and pdat[0] in custfind:
                parsepacket(packet, 'Cx' + pdat[0].encode('hex'), args)
예제 #49
0
def send_periodically(infection_reply, interval_in_second=20):
    pcap_handle = pcap.pcap(timeout_ms=0)
    pcap_handle.setfilter('arp')
    while True:
        pcap_handle.sendpacket(infection_reply.as_bytes())
        print '[<+] Periodical packet sent'
        time.sleep(interval_in_second)
예제 #50
0
파일: test.py 프로젝트: vaporize93/pypcap
 def test_pcap_dispatch(self):
     def __cnt_handler(ts, pkt, d):
         d['cnt'] += 1
     p = pcap.pcap('test.pcap')
     d = { 'cnt':0 }
     n = p.dispatch(-1, __cnt_handler, d)
     assert n == 0
     assert d['cnt'] == 6
     
     def __bad_handler(ts, pkt):
         raise NotImplementedError
     p = pcap.pcap('test.pcap')
     try:
         p.dispatch(-1, __bad_handler)
     except NotImplementedError:
         pass
예제 #51
0
파일: decode.py 프로젝트: caar2000/Dshell
def decode_live(out, options, decoder, decoder_args, decoder_options):
    # set decoder options
    initDecoderOptions(decoder, out, options, decoder_args, decoder_options)

    if 'preModule' in dir(decoder):
        decoder.preModule()

    # give the interface name to the decoder
    decoder.input_file = options.interface
    stats = None
    if options.verbose:
        log('Attempting to listen on %s' % options.interface)
    try:

        if not pcap:
            raise NotImplementedError("raw capture support not implemented")
        decoder.capture = pcap.pcap(options.interface, 65535, True)
        if decoder.filter:
            decoder.capture.setfilter(decoder.filter)
        while not options.count or decoder.count < options.count:
            # use dispatch so we can handle signals
            decoder.capture.dispatch(1, decoder.decode)
    except KeyboardInterrupt:
        pass
    except Exception as exc:
        log(str(exc), level=logging.ERROR)

    if 'cleanConnectionStore' in dir(decoder):
        decoder.cleanConnectionStore()

    if 'postModule' in dir(decoder):
        decoder.postModule()
예제 #52
0
 def __init__(self, filename):
     
     # Read 24-bytes pcap header
     try:
         self.f = pcap.pcapObject(filename)
     except:
         self.f = pcap.pcap(filename)
예제 #53
0
def captureData(iface, save=False):
    pkt = pcap.pcap(iface, promisc=True, immediate=True, timeout_ms=50)
    # filter method
    filters = {
        'DNS': 'udp port 53',
        'HTTP': 'tcp port 80'
    }
    # pkt.setfilter(filters['HTTP'])

    if save:
        pcap_filepath = 'pkts/pkts_{}.pcap'.format(time.strftime("%Y%m%d-%H%M%S",
            time.localtime()))
        pcap_file = open(pcap_filepath, 'wb')
        writer = dpkt.pcap.Writer(pcap_file)
    print('Start capture...')
    try:
        pkts_count = 0
        for ptime, pdata in pkt:
            if save:
                writer.writepkt(pdata, ptime)
            # anlysisData(pdata)
            printRawPkt(ptime, pdata)
            pkts_count += 1
    except KeyboardInterrupt as e:
        if save:
            writer.close()
            pcap_file.close()
            if not pkts_count:
                os.remove(pcap_filepath)
        print('%d packets received'%(pkts_count))
예제 #54
0
파일: regress.py 프로젝트: Azaraf/Honeyd
    def start_pcap(self):
        (self.dpktfh, self.dpktfile) = tempfile.mkstemp()
        if self.debug:
            print "Starting pcap capture, saving in file", self.dpktfile
        self.pid_pcap = os.fork()
        if self.pid_pcap == 0:
            # Child, reads pcap, outputs to a file in dpkt format
            pc = 0
            try:
                pc = pcap.pcap(self.interface)
            except:
                print >> sys.stderr, "Cannot run packet filter, aborting"
                sys.exit(1)

            # filter on our dedciated subnets
            pc.setfilter("net 192.18.0.0/15 and net 192.0.2.0/24")
            for ts, pkt in pc:
                eth = dpkt.ethernet.Ethernet(pkt)
                ip = eth.data

                os.write(self.dpktfh, "SRC=" + dnet.ip_ntoa(ip.src) + "\n")
                os.write(self.dpktfh, "DST=" + dnet.ip_ntoa(ip.dst) + "\n")
                os.write(self.dpktfh, "ID=%d\n" % ip.id)
                os.write(self.dpktfh, "TTL=%d\n" % ip.ttl)
                os.write(self.dpktfh, "DATA=" + ` ip.data ` + "\n")
                os.write(self.dpktfh, "\n")
            exit
            # Parent returns
        return 0
예제 #55
0
파일: dataplane.py 프로젝트: InCNTRE/oftest
 def interface_open(self, interface_name):
     """
     Open a PCAP interface.
     """
     self.pcap = pcap.pcap(interface_name)
     self.pcap.setnonblock()
     return self.pcap.fileno()
예제 #56
0
 def live_sniff(self, start):
     try:
         log.info("Starting sniffing at {};".format(time.strftime('%x-%X')))
         pc = pcap.pcap(name=self.iname, promisc=True, immediate=True)
         count = 0
         pkts = []
         fp = open('pkt.pcap', 'wb')
         st = start
         wt = dpkt.pcap.Writer(fp)
         for t, p in pc:
             count += 1
             pkts.append((t, p))
             wt.writepkt(p, t)
             if time.time() - st > self.timeout:
                 fp.flush()
                 fp.close()
                 wt.close()
                 break
         log.info("Done sniffing at {};".format(time.strftime('%x-%X')))
         with open('pkt.pcap') as fp:
             pkts = dpkt.pcap.Reader(fp)
             self.pkt_analyzer(pkts)
         return True
     except Exception as e:
         print("Error sniffing interface {}; Error:{}".format(
             self.iname, str(e)))
         log.exception("Error sniffing interface {}; Error:{}".format(
             self.iname, str(e)))
         exit(1)
예제 #57
0
def decode_live(out, options, decoder, decoder_args, decoder_options):
    # set decoder options
    initDecoderOptions(decoder, out, options, decoder_args, decoder_options)

    if 'preModule' in dir(decoder):
        decoder.preModule()

    # give the interface name to the decoder
    decoder.input_file = options.interface
    stats = None
    if options.verbose:
        log('Attempting to listen on %s' % options.interface)
    try:

        if not pcap:
            raise NotImplementedError("raw capture support not implemented")
        decoder.capture = pcap.pcap(options.interface, 65535, True)
        if decoder.filter:
            decoder.capture.setfilter(decoder.filter)
        while not options.count or decoder.count < options.count:
            # use dispatch so we can handle signals
            decoder.capture.dispatch(1, decoder.decode)
    except KeyboardInterrupt:
        pass
    except Exception as exc:
        log(str(exc), level=logging.ERROR)

    if 'cleanConnectionStore' in dir(decoder):
        decoder.cleanConnectionStore()

    if 'postModule' in dir(decoder):
        decoder.postModule()
예제 #58
0
def decode_file(fname):
    """Given the name of a pcap file, open it, decode the contents and yield each packet."""
    if _debug: decode_file._debug("decode_file %r", fname)

    if not pcap:
        raise RuntimeError("failed to import pcap")

    # create a pcap object, reading from the file
    p = pcap.pcap(fname)

    # loop through the packets
    for i, (timestamp, data) in enumerate(p):
        try:
            pkt = decode_packet(data)
            if not pkt:
                continue
        except Exception as err:
            if _debug:
                decode_file._debug("    - exception decoding packet %d: %r",
                                   i + 1, err)
            continue

        # save the packet number (as viewed in Wireshark) and timestamp
        pkt._number = i + 1
        pkt._timestamp = timestamp

        yield pkt
예제 #59
0
파일: rtbm.py 프로젝트: wrouesnel/rtbm
 def __init__( self, iface ):
     super(Capture, self).__init__()
     self.pc = pcap.pcap(iface, 65535, False)
     #self.pc.setdirection(direction);
     self.pc.setfilter("proto 6 or 17")
     self.incomingcounter = PacketCounter()
     self.outgoingcounter = PacketCounter()