Example #1
0
class PacketDecoderEthernet:
    def __init__(self):
        self.decoder = EthDecoder()

    def decodePacket(self, packet):
        packet = self.decoder.decode(packet)
        while packet:
            yield packet
            packet = packet.child()
Example #2
0
class PacketDecoder:
  """decode a raw packet into a structure of transport layers
     using impacket lib
  """
  def __init__(self):
    self._decoder = EthDecoder()

  def decode_raw(self, raw_pkt):
    return self._decoder.decode(raw_pkt)
Example #3
0
    def packet_handler(self, header, packet):
        from impacket.ImpactDecoder import EthDecoder
        from binascii import b2a_hex
        decoder = EthDecoder()
        eth = decoder.decode(packet)
        if eth.child().child().child() is not None:
            data = eth.child().child().child()

            self.ui.prt.update(b2a_hex(data._PacketBuffer__bytes))
Example #4
0
class PacketDecoder:
    """decode a raw packet into a structure of transport layers
     using impacket lib
  """
    def __init__(self):
        self._decoder = EthDecoder()

    def decode_raw(self, raw_pkt):
        return self._decoder.decode(raw_pkt)
Example #5
0
class PacketDecoderEthernet(BasePacketDecoder):
    def __init__(self):
        BasePacketDecoder.__init__(self)
        self.decoder = EthDecoder()

    def decodePacket(self, packet):
        decoded_packet = self.decoder.decode(packet)
        next_layer_packet = decoded_packet.child()
        #pprint.pprint(dir(next_layer_packet))
        print(isinstance(next_layer_packet,IP))
Example #6
0
class PacketDecoderEthernet(BasePacketDecoder):
    def __init__(self):
        BasePacketDecoder.__init__(self)
        self.decoder = EthDecoder()

    def decodePacket(self, packet):
        decoded_packet = self.decoder.decode(packet)
        next_layer_packet = decoded_packet.child()
        #pprint.pprint(dir(next_layer_packet))
        print(isinstance(next_layer_packet,IP))
Example #7
0
    def packet_handler(self, header, packet):
        from impacket.ImpactDecoder import EthDecoder
        decoder = EthDecoder()
        eth = decoder.decode(packet)
        ip = eth.child()
        tcp = ip.child()
        data = tcp.child()

        from binascii import b2a_hex
        self.pkt_list.append(b2a_hex(data._PacketBuffer__bytes))
        sleep(0.5)
Example #8
0
class DHCPTool:
    def initialize(self):
        self.pcap = pcapy.open_live(pcapy.lookupdev(), -1, 1, 1)
        self.pcap.setfilter("port 67", 1, 0xffffff00)
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.connect(('192.168.1.1',67))
        self.decoder = EthDecoder()

    def targetRun(self):
        for i in range(1,254):
            self.sendDISCOVER('12345%c' % i, ip = '192.168.1.%d' % i)
            self.processPacketsForOneSecond()

    def finalize(self):
        self.pcap.close()
        Module.finalize(self)

    def processPacketsForOneSecond(self):
        t = time.time()
        while time.time()-t < 1:
            p = self.pcap.next()
            if p[1][2]:
                pp = self.decoder.decode(p[0])
                print pp

    def sendDHCP(self, type, chaddr, hostname = None, ip = None, xid = None,opts = []):
        p = DhcpPacket()

        opt = [('message-type',type)] + list(opts)

        if xid is None:
            xid = randint(0,0xffffffff)
        if ip:
            ip = structure.unpack('!L',socket.inet_aton(ip))[0]
            p['ciaddr'] = ip
            opt.append(('requested-ip',ip))

        if hostname is not None:
            for i in range(0,len(hostname),255):
                opt.append(('host-name',hostname[i:i+255]))

        p['op']     = p.BOOTREQUEST
        p['xid']    = xid
        p['chaddr'] = chaddr
        p['cookie'] = 0x63825363
        p['options'] = opt

        self.sock.send(str(p))

    def sendDISCOVER(self, chaddr, hostname = None, ip = None,xid = 0x12345678):
        print 'DHCPDISCOVER: %s' % ip
        self.sendDHCP(DhcpPacket.DHCPDISCOVER, chaddr, hostname, ip, xid)
Example #9
0
    def _packet_handler(self, packet):
        """
        decode ethernet packet and pass packets child to decoding function
        """
        decoder = EthDecoder()
        dpkt = decoder.decode(packet)
        self._decode_ether(dpkt)
        if dpkt.get_ether_type() == ETHERTYPE_IP:
            self._decode_ip(dpkt.child())
        if dpkt.get_ether_type() == ETHERTYPE_ARP:
            self._decode_arp(dpkt.child())

        return self.packet
    def read_packet(self, hdr, data):
        decoder = EthDecoder()
        ether = decoder.decode(data)
        ip = ether.child()
        tcp = ip.child()

        try:
            print ip.get_ip_src()
            print tcp.get_th_sport()
            print ip.get_ip_dst()
            print tcp.get_th_dport()

        except:
            print "error"
Example #11
0
def parse_all_ips():
    decoder = EthDecoder()

    all_src_ip = list()
    all_dst_ip = list()

    for pcap in [open_offline(AttackPacket), open_offline(NormalPacket)]:
        while True:
            _, data = pcap.next()
            if _ is None:
                break
            else:
                ip = decoder.decode(data).child()
                try:
                    all_src_ip.append(ip.get_ip_src())
                except AttributeError:
                    print 1
                all_dst_ip.append(ip.get_ip_dst())
    return all_src_ip, all_dst_ip
Example #12
0
class Decoder(object):
    def __init__(self, pcap):
        # Query the type of the link and instantiate a decoder accordingly.
        datalink = pcap.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        else:
            raise Exception("Datalink type not supported: " % datalink)

        self.pcap = pcap

    def start(self):
        self.pcap.loop(0, self.packetHandler)

    def packetHandler(self, hdr, data):
        p = self.decoder.decode(data)
        ip = p.child()
        tcp = ip.child()
        src = (ip.get_ip_src(), tcp.get_th_sport())
        dst = (ip.get_ip_dst(), tcp.get_th_dport())
        return (p, ip, tcp, src, dst)

    def report(self):
        raise Exception("Not implemented")
Example #13
0
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:
                pass
            capSize += bytes
            pktCount += 1
            d.dump(hdr, data)
        fileCount += 1
        print "%s is %d bytes with %d packets" % (filename, capSize, pktCount)
    except:
        break
Example #14
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()
Example #15
0
			continue
	if len(toListen) == 0:
		print "There are no interfaces available."
		sys.exit(0)
	print "Listening on interfaces:", listening

decoder = EthDecoder()
while len(sockets) > 0:
    ready = select(sockets, [], [])[0]
    for s in ready:
        packet = s.recvfrom(4096)[0]
        if 0 == len(packet):
		sockets.remove(s)
		s.close()
        else:
	    l1 = decoder.decode(packet)
            if isinstance(l1, Ethernet):
                print 'Eth',
                l2 = l1.child()
                if isinstance(l2,IP):
                    print "IP",
                    l3=l2.child()
                    if isinstance(l3,TCP):
                        print "TCP"
                    elif isinstance(l3,UDP):
                        print "UDP"
                    elif isinstance(l3,ICMP):
                        print "IMCP"
                    else :
                        print "No TCP or UDP or ICMP"
		elif isinstance(l2,ARP):
Example #16
0
class PacketMonitor(object):

    def __init__(self, pcap):
        self.usage = {}

        # Query the type of the link and instantiate a decoder accordingly.
        datalink = pcap.datalink()
        if pcapy.DLT_EN10MB == datalink:
            self.decoder = EthDecoder()
        else:
            raise Exception('Unsupported datalink type:' % datalink)

        self.pcap = pcap 
    

    def _update_usage(self, packet):
        empty_stats = { 'up' : 0, 'down' : 0 }

        has_ip_src = packet.ip_src is not None
        has_ip_dst = packet.ip_dst is not None
        
        if has_ip_src and not self.usage.has_key(packet.ip_src):
            self.usage[packet.ip_src] = empty_stats
        if has_ip_dst and not self.usage.has_key(packet.ip_dst):
            self.usage[packet.ip_dst] = empty_stats
      
        if has_ip_src:
            self.usage[packet.ip_src]['up'] += packet.size

        if has_ip_dst:
            self.usage[packet.ip_dst]['down'] += packet.size


    def is_private_ipv4(self, ip):
        # regex pattern from http://stackoverflow.com/a/2814102/615740
        private_ipv4_pattern = ("(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)"
                                "|(^172\.3[0-1]\.)|(^192\.168\.)")

        return re.match(private_ipv4_pattern, ip)


    def print_usage(self, max_results=0, show_private=True):
        ips = self.usage.keys()
        key = lambda ip: self.usage[ip]['up'] + self.usage[ip]['down']
        ips.sort(reverse=True, key=key)
        
        i = 0
        for ip in ips:
            is_private = self.is_private_ipv4(ip)

            if max_results != 0 and i == max_results:
                break

            up_kb = self.usage[ip]['up'] / 1024
            down_kb = self.usage[ip]['down'] / 1024

            if show_private and is_private:
                print "%32s:\tup %d Kb down %d Kb" % (ip, up_kb, down_kb)
            elif not show_private and not is_private:
                print "%32s:\tup %d Kb down %d Kb" % (ip, up_kb, down_kb)
            else:
                continue

            i += 1


    def print_local_usage(self, max_results=5):
        return self.print_usage(max_results=max_results, show_private=True)


    def print_remote_usage(self, max_results=5):
        return self.print_usage(max_results=max_results, show_private=False)


    def __call__(self, hdr, data):
        packet = PacketWrapper(self.decoder.decode(data))
        self._update_usage(packet)

        print "Local:"
        self.print_local_usage(max_results=5)
        print "\nRemote:"
        self.print_remote_usage(max_results=5)
        print ""
Example #17
0
        def CaptureCB(interface):

            if interface not in self.m_Captures:
                self.m_Captures[interface] = pcapy.open_live(
                    interface, 65536, 1, 0)
                decoder = EthDecoder()

                logline = "[START]"
                while 1:
                    self.AddLogLine("[" + str(datetime.now()) + "]" + logline)

                    if self.m_PrintStdout:
                        svc.logger.info(logline)

                    (header, payload) = self.m_Captures[interface].next()
                    packet_size = len(payload)
                    packet = decoder.decode(payload)

                    logline = interface.rjust(
                        6) + " : " + CaptureContextObject.PrettySize(
                            packet_size).ljust(7) + " "

                    source_mac = self.GetMAC(packet.get_ether_dhost())
                    destination_mac = self.GetMAC(packet.get_ether_shost())

                    AddMachine(source_mac)
                    AddMachine(destination_mac)

                    TXMachine(source_mac, packet_size)
                    RXMachine(destination_mac, packet_size)

                    logline += source_mac + " => " + destination_mac.ljust(18)

                    if type(packet.child()) == eap.EAPOL:
                        if packet.child().packet_type == eap.EAPOL.EAPOL_KEY:
                            if source_mac not in self.m_Cache[interface][
                                    'EAPOL']:
                                self.m_Cache[interface]['EAPOL'].append(
                                    source_mac)
                            logline += "[EAPOL] " + source_mac
                        continue

                    if type(packet.child()) == ImpactPacket.ARP:
                        logline += "[ARP]"
                        continue

                    version = 'IPv6' if type(
                        packet.child()) == IP6.IP6 else 'IPv4'

                    if type(packet.child()) == ImpactPacket.IP or type(
                            packet.child()) == IP6.IP6:
                        ip = packet.child()

                        logline += "[" + version + "]"

                        source_ip = ip.get_ip_src(
                        ) if version is 'IPv4' else ip.get_ip_src().as_string(
                        )
                        destination_ip = ip.get_ip_dst(
                        ) if version is 'IPv4' else ip.get_ip_dst().as_string(
                        )

                        AddIP(source_ip, version)
                        AddIP(destination_ip, version)
                        AddContact(source_ip, destination_ip)

                        self.Whois(source_ip)
                        self.Whois(destination_ip)

                        sourceName = self.GetIPDescription(source_ip)
                        destinationName = self.GetIPDescription(destination_ip)

                        logline += source_ip.rjust(25)
                        logline += " => "
                        logline += destination_ip.ljust(25)

                        if type(ip.child()) == ImpactPacket.UDP:
                            logline += "[UDP]"
                            udp = ip.child()
                            sport = udp.get_uh_sport()
                            dport = udp.get_uh_dport()
                            logline += str(sport).rjust(6) + " => " + str(
                                dport).ljust(6)
                            if dport in (67, 68) and sport in (67, 68):
                                d = dhcp.BootpPacket(udp.child().get_packet())
                                off = len(d.getData())
                                if udp.child().get_packet(
                                )[off:off +
                                  4] == dhcp.DhcpPacket.MAGIC_NUMBER.to_bytes(
                                      4, 'big'):
                                    requestType = self.GetDHCPRequestType(
                                        udp.child().get_packet()[off + 6])
                                    logline += "[" + requestType + "]"
                                    self.m_Cache[interface]['DHCP'][
                                        source_mac] = requestType

                        if type(ip.child()) == ImpactPacket.TCP:
                            logline += "[TCP]"
                            tcp = ip.child()
                            logline += str(
                                tcp.get_th_sport()).rjust(6) + " => " + str(
                                    tcp.get_th_dport()).ljust(6)
                        if type(ip.child()) == ImpactPacket.ICMP:
                            logline += "[ICMP]"
                            icmp = ip.child()
                            logline += "[" + icmp.get_type_name(
                                icmp.get_icmp_type()) + "]"
                            continue
                        if type(ip.child()) == ICMP6.ICMP6:
                            logline += "[ICMP6]"
                            continue
                        if type(ip.child()) == ImpactPacket.IGMP:
                            logline += "[IGMP]"
                            continue

                        if len(sourceName):
                            logline += " <= (" + sourceName + ")"

                        if len(destinationName):
                            logline += " => (" + destinationName + ")"

                    if not self.m_Commands[interface].empty():
                        del self.m_Commands[interface]
                        del self.m_Captures[interface]
                        del self.m_Threads[interface]
                        break