Exemplo n.º 1
0
    def __init__(self,
                 promisc=True,
                 buffer_size=None,
                 read_timeout=100,
                 show_packets=False):
        self._pcap_t = None
        self._packets = None

        assert promisc in (True, False), "promisc must be either True or False"
        self._promisc = promisc

        self._buffer_size = buffer_size
        self._read_timeout = read_timeout

        assert show_packets in (
            True, False), "show_packets must be either True or False"
        self._show_packets = show_packets

        self._pcap_lock = threading.Lock()

        try:
            from impacket.ImpactDecoder import LinuxSLLDecoder
            self._decoder = LinuxSLLDecoder()
        except ImportError:
            self._decoder = None
Exemplo n.º 2
0
    def __init__(self, pcapObj, server_ports, ws_path, soap_request_handler,
                 server):
        # Query the type of the link and instantiate a decoder accordingly.
        datalink = pcapObj.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception('Datalink type not supported: %s' % (datalink, ))

        self.pcap = pcapObj
        self.server_ports = set(server_ports)
        self.ws_path = ws_path
        self.server = server
        self.soap_request_handler = soap_request_handler
        self.valid_http_methods = set(['GET', 'POST'])
        self._shortest_method_name = min(
            [len(x) for x in self.valid_http_methods])
        self._longest_method_name = max(
            [len(x) for x in self.valid_http_methods])
        Thread.__init__(self)
        self.packet_counter = 0
        self.connections = ConnectionManager()
        self.http_request_counter = Counter()
        self.soap_call_counter = Counter()
        self.server_conn = None
        self._needs_server_update = False
        self._last_server_update = 0
    def __init__(self, pcapObj):
        datalink = pcapObj.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Tipo de datalink não suportado: " % datalink)

        self.pcap = pcapObj
        Thread.__init__(self)
    def __init__(self, cap_stream):
        multiprocessing.Process.__init__(self)
        self.cap_stream = cap_stream
        self.datalink = cap_stream.datalink()

        if pcapy.DLT_EN10MB == self.datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == self.datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % self.datalink)
Exemplo n.º 5
0
    def __init__(self, pcapObj):
        # Query the type of the link and instantiate a decoder accordingly.
        datalink = pcapObj.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.pcap = pcapObj
        Thread.__init__(self)
Exemplo n.º 6
0
    def __init__(self, pcapObj=None, Interface=None):
        datalink = pcapObj.datalink()
        self.Interface = Interface
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Unsupported datalink type: " % datalink)

        self.pcap = pcapObj
        self.buffer_traffic = []
        Thread.__init__(self)
Exemplo n.º 7
0
    def __init__(self, pcapObj):
        """ Query the type of the link and instantiate a decoder accordingly. """
        datalink = pcapObj.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.pcap = pcapObj
        self.buffer = []  # init internal buffer
        self.quit = False  # quit thread?
        Thread.__init__(self)
Exemplo n.º 8
0
    def __init__(self, bridge, subnet, arptable):
        # Open interface for capturing.
        self.pcap = open_live(bridge.bridgename, 65536, 1, 100)

        # Query the type of the link and instantiate a decoder accordingly.
        datalink = self.pcap.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.bridge = bridge
        self.subnet = subnet
        self.arptable = arptable
        self.protocols = args.discovery_protos or self.protocols

        Thread.__init__(self)
Exemplo n.º 9
0
    def start(self):
        self.p = open_live(self.interface, 1600, 0, 100)
        ##         self.p.setnonblock(1)
        if self.filter:
            self.p.setfilter(self.filter)

        # Query the type of the link and instantiate a decoder accordingly.
        datalink = self.p.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        elif pcapy.DLT_LINUX_SLL == datalink:
            self.decoder = LinuxSLLDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.tk.after(POLL_PERIOD, self.poll)
        self.tk.after(REFRESH_PERIOD, self.timerDraw)
        self.tk.bind('q', self.quit)
        self.tk.mainloop()
Exemplo n.º 10
0
 def __init__(self, callback, dev='any', port=3333, ignoreIp=None):
     Thread.__init__(self)
     DEV = dev  # interface to listen on
     MAX_LEN = 1514  # max size of packet to capture
     PROMISCUOUS = 1  # promiscuous mode?
     READ_TIMEOUT = 100  # in milliseconds
     self.MAX_PKTS = -1  # number of packets to capture; -1 => no limit
     self.p = open_live(DEV, MAX_LEN, PROMISCUOUS, READ_TIMEOUT)
     myfilter = 'udp and port ' + str(port)
     if ignoreIp:
         myfilter += ' and not dst host ' + ignoreIp
     self.p.setfilter(myfilter)
     self.callback = callback
     self.packets = 0
     datalink = self.p.datalink()
     if pcapy.DLT_EN10MB == datalink:
         self.decoder = EthDecoder()
     elif pcapy.DLT_LINUX_SLL == datalink:
         self.decoder = LinuxSLLDecoder()
     else:
         raise Exception("Datalink type not supported: " % datalink)
Exemplo n.º 11
0
    print "    bytes = the approximate maximum size of the little files"
    print ""


if len(sys.argv) < 3:
    showUsage()
    sys.exit(1)

fileCount = 1
p = open_offline(sys.argv[1])

datalink = p.datalink()
if DLT_EN10MB == datalink:
    decoder = EthDecoder()
elif DLT_LINUX_SLL == datalink:
    decoder = LinuxSLLDecoder()
else:
    raise Exception("Datalink type not supported: " % datalink)

while 1:
    try:
        (hdr, data) = p.next()
        filename = "%s_%d.cap" % (sys.argv[2], fileCount)
        pktCount = 0
        capSize = 0
        d = p.dump_open(filename)
        while capSize < int(sys.argv[3]):
            pkt = decoder.decode(data)
            try:
                bytes = len(pkt.get_packet())
            except:
Exemplo n.º 12
0
  def run(self):
    global maxcount
    global maxbytes
    global history
    global persistant
    global running
    global last_dump
    
    flows = {}
    count = 0

    # Arguments here are:
    #   device
    #   snaplen (maximum number of bytes to capture _per_packet_)
    #   promiscious mode (1 for true)
    #   timeout (in milliseconds)
    cap = pcapy.open_live(FLAGS.i, 1500, 1, 1000)

    # We get layer 1 packets. Therefore we need to use the right decoder.
    datalink = cap.datalink()
    if pcapy.DLT_EN10MB == datalink:
      decoder = EthDecoder()
    elif pcapy.DLT_LINUX_SLL == datalink:
      decoder = LinuxSLLDecoder()
    else:
      print '%s Datalink type not supported: ' %(datetime.datetime.now(),
                                                 datalink)
      sys.exit(1)

    # Read packets -- header contains information about the data from pcap,
    # payload is the actual packet as a string
    (header, payload) = cap.next()
    while header:
      count += 1
      if FLAGS.verbose:
        print ('%s captured %d bytes, truncated to %d bytes'
               %(datetime.datetime.now(), header.getlen(), header.getcaplen()))

      try:
        # The link level packet contains a payload 
        l = decoder.decode(payload)
        p = l.child()
        key = None

        if p.ethertype == 0x800:
          # This is an IP packet
          ip = p.child()
          ips = [p.get_ip_src(), p.get_ip_dst()]
          ips.sort()

          if ip.protocol == 1:
            # ICMP
            if FLAGS.verbose:
              print ('  ICMP: %s -> %s type %s'
                     %(p.get_ip_src(), p.get_ip_dst(),
                       ip.get_type_name(ip.get_icmp_type())))

            key = 'ICMP %s' % repr(ips)

          elif ip.protocol == 6:
            # TCP
            if FLAGS.verbose:
              print '  TCP: %s:%d -> %s:%d' %(p.get_ip_src(),
                                              ip.get_th_sport(),
                                              p.get_ip_dst(),
                                              ip.get_th_dport())

            ports = [ip.get_th_sport(), ip.get_th_dport()]
            ports.sort()
            key = 'TCP %s %s' %(repr(ips), repr(ports))

          elif ip.protocol == 17:
            # UDP
            if FLAGS.verbose:
              print '  UDP: %s:%d -> %s:%d' %(p.get_ip_src(),
                                              ip.get_uh_sport(),
                                              p.get_ip_dst(),
                                              ip.get_uh_dport())

            ports = [ip.get_uh_sport(), ip.get_uh_dport()]
            ports.sort()
            key = 'TCP %s %s' %(repr(ips), repr(ports))

          elif ip.protocol:
            print '%s Unknown IP protocol %s' %(datetime.datetime.now(),
                                                ip.protocol)

          if key:
            flows.setdefault(key, (0, 0, 0, 0))
            (a_count, a_bytes, b_count, b_bytes) = flows[key]
            if ips == [p.get_ip_src(), p.get_ip_dst()]:
              a_count += 1
              a_bytes += header.getlen()
            else:
              b_count += 1
              b_bytes += header.getlen()
            flows[key] = (a_count, a_bytes, b_count, b_bytes)

        else:
          print '%s Unknown ethertype %x' %(datetime.datetime.now(),
                                            p.ethertype)

      except impacket.ImpactPacket.ImpactPacketException, e:
        print '%s Sniffer skipped packet: %s' %(datetime.datetime.now(), e)

      self.data_lock.acquire()
      if time.time() - last_dump > 30:
        # Recalibrate maximums
        maxcount = 100
        maxbytes = 100
        for flow in flows:
          (acount, abytes, bcount, bbytes) = flows[flow]
          if acount > maxcount:
            maxcount = acount
          if bcount > maxcount:
            maxcount = bcount
          if abytes > maxbytes:
            maxbytes = abytes
          if bbytes > maxbytes:
            maxbytes = bbytes

        # Append to history
        history.append(flows)
        history = history[-30:]

        # Write to persistant history as well
        persistant.setdefault('history', {})
        persistant['history'][time.time()] = flows
        persistant.sync()
        
        if len(persistant['history']) > 29:
          print '%s Committing suicide' % datetime.datetime.now()
          persistant.close()
          running = False
          raise SystemExit()
        
        print ('%s Sniffer captured %d packets in the last 30 seconds'
               %(datetime.datetime.now(), count))
        count = 0
        flows = {}
        last_dump = time.time()

      self.data_lock.release()
      del header
      del payload
      (header, payload) = cap.next()