Esempio n. 1
0
def EthDecoder2(hdr, data):
    eth = EthDecoder().decode(data)
    smpPack = eth.child()
    str1 = smpPack.__str__()

    print "SMP Received: "+str1
    return bytes11
Esempio n. 2
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))
Esempio n. 3
0
def EthDecoder1(hdr,data):
  eth = EthDecoder().decode(data)
  ip = eth.child()
  udp = ip.child()  
  
  nonce=udp.get_data_as_string()
  print "Received: "+nonce
  
  nonceMod = hex(int(nonce.encode("hex"), 16) + 1)[2:].decode("hex")  #nonce incremented
  
  sendReply(nonceMod)
Esempio n. 4
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)
Esempio n. 5
0
File: Pcap.py Progetto: vanzan/slave
        def recv_pkts(hdr, data):
            packet = EthDecoder().decode(data)
            packetChild = packet.child()
            sourceIp = packetChild.get_ip_src()
            if (sourceIp != self.getLocalIp()):
                try:
                    newIp = socket.gethostbyaddr(sourceIp)[0]
                    if (newIp != self.lastIp):
                        self.lastIp = newIp
                        print(newIp)

                    #from 20 to 20 save in a set in every 5 min and save to db
                except:
                    pass
Esempio n. 6
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)
Esempio n. 7
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()
Esempio n. 8
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))
Esempio n. 9
0
    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 
Esempio n. 10
0
def EthDecoder1(hdr,data):
    eth = EthDecoder().decode(data)
    sdsResp = eth.child()
    str1 = sdsResp.__str__()
    
    print str1
    
    port = str1[-9:-5] + str1[-4:]
    ttl = str1[-14:-10] 
    ethAddress = str1[-29:-25]+str1[-24:-20]+str1[-19:-15]
    sid1 = str1[25:29]+str1[30:34]+str1[35:39]+ str1[40:44]+str1[65:69] #sid in hex
    role1 = int(str1[70:74], 16)
    tid = str1[15:19]+str1[20:24]

    print port, ttl, ethAddress, sid1, role1, tid
    if int('0x'+ttl, 16) > 0 : #checks for ttl expiry before sending
      sock1 = socket.socket()
      for key in tab_smp.keys():
          if tab_smp[key] == (sid1, role1):
              sock1 = tab_smp[key][0]
              print sock1
              break

      smpPacket = SMP()
      smpPacket.set_plen(bytes11)
      smpPacket.set_dport(int('0x'+port, 16))
      smpPacket.set_sport(SPORT)
      smpPacket.contains(ImpactPacket.Data(buf1))

      ethsmp = ImpactPacket.Ethernet()

      ethsmp.set_ether_shost(ETH_MY_MAC)

      ethAdd1 = re.findall('..', ethAddress)
      ethAdd2 = tuple(int('0x'+i, 16) for i in ethAdd1)
      ethsmp.set_ether_dhost(ethAdd2)
      ethsmp.set_ether_type(ETH_SMP_TYPE)
      ethsmp.contains(smpPacket)
      sock1.send(ethsmp.get_packet())

      return bytes11
Esempio n. 11
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)
Esempio n. 12
0
def EthDecoder1(hdr,data):
    eth = EthDecoder().decode(data)
    sdsReq = eth.child()
    str1 = sdsReq.__str__()
    print len(str1)
    print str1
    print "1 "+str1[5:9]+" 2 "+str1[10:14]
    ver = str1[5:7]
    typ = str1[7:9]
    rlen = str1[10:14]
    tid1 = (str1[15:17], str1[17:19], str1[20:22], str1[22:24])
    tid = tuple(int('0x'+i, 16) for i in tid1)
    sid1 = str1[25:29]+str1[30:34]+str1[35:39]+ str1[40:44]+str1[65:69] #sid in hex
    sid4 = tuple(re.findall('..', sid1))
    sid2 = tuple(chr(int('0x'+i, 16)) for i in sid4) #hex->char
    sid3 = ''.join(sid2) #stringified
    
    sid = tuple(int('0x'+i, 16) for i in sid4) #hex->dec
    print ver, typ, rlen, tid, sid1, sid4, sid
    role = int(str1[70:74],16)
    print eth.get_ether_shost()

    ep = smp_ep()
    ep.serviceID = sid3
    ep.r = role
    res = directory_smp(ep)
    print res
    
    ethAddr = res[0]
    port = res[1]
    ttl = res[2]
    
    sdsResp1 = SDSResponse()
    sdsResp1.set_tid(tid)
    sdsResp1.set_sid(sid)
    sdsResp1.set_role(role)
    sdsResp1.set_ethAddress(ethAddr)
    sdsResp1.set_ttl(ttl)
    sdsResp1.set_port(port)

    ethResp = ImpactPacket.Ethernet()
    ethResp.set_ether_type(eth.get_ether_type())
    ethResp.set_ether_shost(eth.get_ether_dhost())
    ethResp.set_ether_dhost(eth.get_ether_shost())
    ethResp.contains(sdsResp1)
    s1 = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(ETH_SDS_TYPE))
    s1.bind(("eth0",0))
    s1.send(ethResp.get_packet())
Esempio n. 13
0
    if (os.getuid() or os.geteuid()):
        print("Requires root access")
        exit(1)
    if not dev in pcapy.findalldevs():
        print("Bad interface " + dev)
        exit(1)
    pr = pcapy.open_live(dev, 65536, True, 0)
    if pr.datalink() != pcapy.DLT_EN10MB:
        print("Interface not Ethernet " + dev)


##############################
############ Main ############
##############################

decoder = EthDecoder()

check()
pcap = pcapy.open_live(dev, max_bytes, promiscuous, read_timeout)
dumper = pcap.dump_open(dump_file)
pcap.loop(packet_limit, write_packet)

pcap = pcapy.open_offline(dump_file)
pcap.loop(packet_limit, read_packet)
all_list = list(set([line.strip() for line in open(tmp_file, 'r')]))
file = open(black_file, "a+")
for ip in all_list:
    if ip not in white_list:
        print("%s is not in %s" % (ip, white_file))
        file.write(ip)
        file.write("\n")
    def sniffSlaac(self,buf):
        #f = open(self.location)
        #pcap = dpkt.pcap.Reader(f)
        #checker = ICMP6.ICMP6.protocol
        #listOfMessages = []
        #i = 1
        #for ts, buf in pcap:
            eth = EthDecoder().decode(buf)
            ethChild = eth.child()
            ethChild2 = ethChild.child()

            try:
                #print ethChild2
                if ethChild2.get_ip_protocol_number() == 58:
                    destination_MAC_address = []
                    source_MAC_address = []
                    destination_MAC_address = eth.get_ether_dhost()
                    source_MAC_address = eth.get_ether_shost()
                    source_MAC_address_final = ""
                    destination_MAC_address_final = ""
                    override_flag= False
                    router_flag = False

                    x = 0

                    for x in range(6):
                        temp_decimal = source_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        source_MAC_address_final = source_MAC_address_final + temp_hex[2:] + ":"
                        temp_decimal = destination_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        destination_MAC_address_final = destination_MAC_address_final + temp_hex[2:] + ":"

                    source_MAC_address_final = source_MAC_address_final[:-1].zfill(2)
                    destination_MAC_address_final = destination_MAC_address_final[:-1]
                    target_link_layer_address = ""

                    packetData = (ethChild2.get_originating_packet_data())
                    packetHex = []
                    for data in packetData:
                        packetHex.append(hex(data))
                    # print packetHex
                    source_link_layer_address = ""
                    target_address = ""
                    ip_source_address = ethChild.get_source_address()
                    ip_destination_address = ethChild.get_destination_address()
                    ndp_message_number = ethChild2.get_type()
                    x = 0
                    #print packetHex
                    contains_source, offset = self.check_ipv6_options(packetHex)

                    if str(ndp_message_number) == "134":  #Router Advertisement
                        if str(contains_source) == "true-source":
                            for x in range(6):
                                source_link_layer_address = source_link_layer_address + packetHex[x + offset + 1][
                                                                                        2:].zfill(2) + ":"
                            target_address = "n/a"
                            source_link_layer_address = source_link_layer_address[:-1]
                            target_link_layer_address = "n/a"
                            #print "*****************************************************************************************"
                            #print source_link_layer_address
                            #print "*****************************************************************************************"
                        else:
                            source_link_layer_address = "n/a"


                    elif str(ndp_message_number) == "135":  #Neighbor Solicitation
                        for x in range(16):
                            target_address = target_address + packetHex[x][2:].zfill(2)
                            if (x > 0):
                                if x % 2 != 0:
                                    target_address = target_address + ":"
                        target_address = target_address[:-1]
                        target_link_layer_address = "n/a"
                        if str(contains_source) == "true-source":
                            for x in range(6):
                                source_link_layer_address = source_link_layer_address + packetHex[x + offset + 1][
                                                                                        2:].zfill(2) + ":"
                            source_link_layer_address = source_link_layer_address[:-1]
                            #print "*****************************************************************************************"
                            #print source_link_layer_address
                            #print "*****************************************************************************************"
                        else:
                            source_link_layer_address = "n/a"

                    elif str(ndp_message_number) == "136":  #Neighbor Advertisement

                        #print ethChild2.get_router_flag() #sample code to get router flag of NA
                        #print ethChild2.get_override_flag()
                        #router_flag = ethChild2.get_router_flag()
                        #if router_flag == False:
                        #   print "if else of flag worked"
                        if str(contains_source) == "true-target" and hex(ethChild2.child().get_bytes()[0:1][0]) == "0xa0":
                            for x in range(6):
                                target_link_layer_address = target_link_layer_address + packetHex[1 + offset + x][
                                                                                        2:].zfill(2) + ":"
                            target_link_layer_address = target_link_layer_address[:-1]

                        else:
                            target_link_layer_address = "n/a"


                        for x in range(16):
                            target_address = target_address + packetHex[x][2:].zfill(2)
                            if (x > 0):
                                if x % 2 != 0:
                                    target_address = target_address + ":"
                        target_address = target_address[:-1]
                        override_flag = ethChild2.get_override_flag()
                        router_flag = ethChild2.get_router_flag()

                    message_details = SLAAC_Message.SLAAC_Message(ndp_message_number, source_link_layer_address,
                                                                  ip_source_address, ip_destination_address,
                                                                  source_MAC_address_final,
                                                                  destination_MAC_address_final, target_address,
                                                                  target_link_layer_address,override_flag,router_flag)

                    #detection_module.detect_rogue_advertisement(message_details)
                    #print "-----------Packet Details----------"
                    #print "NDP Message Type %s" % message_details.get_ndp_message_number()
                    #print "Source Link Layer Address: %s" % message_details.get_source_link_layer_address()
                    #print "Source IPv6 Address %s " % message_details.get_ip_source_address()
                    #print "Destination IPv6 Address %s" % message_details.get_ip_destination_address()
                    #print "Source MAC Address %s" % message_details.get_source_MAC_address()
                    #print "Destination MAC Address %s" % message_details.get_destination_MAC_address()
                    #print "Target Address %s" % message_details.get_target_address()
                    #print "Target Link Layer Address %s" % message_details.get_target_link_layer_address()
                    #print "Override Flag %s" %message_details.get_override_flag()
                    #print "Router Flag %s" %message_details.get_router_flag()
                    #print "----------------END----------------"

                    #detect_module = Detection()


                    #if message_details.get_ndp_message_number()=="134": #Last Hop Router Attack
                    #    detect_module.detect_rogue_advertisement(message_details)
                    #elif message_details.get_ndp_message_number()=="135":#Dos in DAD
                    #    detect_module.detect_dos_dad(message_details)
                    #elif message_details.get_ndp_message_number()=="136": #Neigbor Spoofing
                    #    if ethChild2.get_router_flag()=="false":
                    #        detect_module.detect_neighbor_spoofing((message_details))


                    #listOfMessages.append(message_details)


            except:
               # x = 1
                 print "Packet Discarded"
Esempio n. 15
0
def EthDecoder1(hdr, data):
    eth = EthDecoder().decode(data)
    ip = eth.child()
    udp = ip.child()

    print "Received: " + udp.get_data_as_string()
Esempio n. 16
0
#!/usr/bin/python
#coding:utf-8
import sys
import re
import getopt
import pcapy
from impacket.ImpactDecoder import EthDecoder, IPDecoder, TCPDecoder

#Interface to sniff on
dev = "eth0"

# Pcap filter
filter = "tcp"

# Decoder for all layers
eth_dec = EthDecoder()
ip_dec = IPDecoder()
tcp_dec = TCPDecoder()

# Patterns that match usernames and passwords
pattern = re.compile(
    r"""(?P<found>(USER|USERNAME|PASS|
		     PASSWORD|LOGIN|BENUTZER|PASSWORT|AUTH|
		     ACCESS|ACCESS_?KEY|SESSION|
		     SESSION_?KEY|TOKEN)[=:\s].+)\b""", re.MULTILINE | re.IGNORECASE)


# This function will be called for every packet, decode it and
# try to find a username or password in it
def handle_packet(hdr, data):
    eth_pkt = eth_dec.decode(data)
Esempio n. 17
0
 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()
Esempio n. 18
0
	for interface in toListen:
		try:
			print interface
			s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
			s.bind((interface, 0x0800))
			sockets.append(s)
			listening.append(interface)
		except socket.error:
			print "Ignoring unknown interface:", interface
			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()
Esempio n. 19
0
def EthDecoder1(hdr, data):
    eth = EthDecoder().decode(data)
    ip = eth.child()
    udp = ip.child()

    print "Received: " + udp.get_data_as_string()
Esempio n. 20
0
    def __init__(self, args):

        if os.name == "nt":
            self.platform_is_windows = True
            self.iface = "\\Device\\NPF_{EDB20D9F-1750-46D6-ADE7-76940B8DF917}"
            self.my_ip = "10.0.2.15"
        else:
            self.platform_is_windows = False
            self.iface = pcapy.findalldevs()[0]
            self.my_ip = ni.ifaddresses(self.iface)[2][0]['addr']

        if 'sync_server_ip' in args:
            # is not none
            self.sync_server_ip = socket.gethostbyname(args['sync_server_ip'])
        if 'sync_server_port' in args:
            # is not none
            self.sync_server_port = str(args['sync_server_port'])

        self.metric_conf = {"sync_server_port": 0,
                            "desktop_client": None,  # syncronization service name
                            "decoder": EthDecoder(),  # packet decoder
                            "max_bytes": 0,  # maximum bytes ?
                            "promiscuous": False,
                            # not capture all the network traffice only the trafice toward current host
                            "read_timeout": 0,  # in milliseconds
                            "interface": None,
                            "traffic_flow_dict": {},
                            "packet_index": 0,
                            "transport_dict": {},
                            "network_dict": {},
                            "traffic_flow_dict": {},
                            "ip2hostname_cache": {},  #
                            "packet_limit": 0,
                            "register": None}

        self.metric_prev = {
            "idx": -1,
            "epoch": self.get_epoch_ms(),
            "total_up": {
                "c": 0,
                "size": 0
            },
            "total_down": {
                "c": 0,
                "size": 0
            },
            "data_up": {
                "c": 0,
                "size": 0
            },
            "data_down": {

                "c": 0,
                "size": 0
            },
            "meta_up": {

                "c": 0,
                "size": 0
            },
            "meta_down": {

                "c": 0,
                "size": 0
            },
            "comp_up": {

                "c": 0,
                "size": 0
            },
            "comp_down": {

                "c": 0,
                "size": 0
            },
            "misc_up": {

                "c": 0,
                "size": 0
            },
            "misc_down": {

                "c": 0,
                "size": 0
            }}

        self.metric_curr = {
            "idx": -1,
            "epoch": self.get_epoch_ms(),
            "total_up": {
                "c": 0,
                "size": 0
            },
            "total_down": {
                "c": 0,
                "size": 0
            },
            "data_up": {
                "c": 0,
                "size": 0
            },
            "data_down": {

                "c": 0,
                "size": 0
            },
            "meta_up": {

                "c": 0,
                "size": 0
            },
            "meta_down": {

                "c": 0,
                "size": 0
            },
            "comp_up": {

                "c": 0,
                "size": 0
            },
            "comp_down": {

                "c": 0,
                "size": 0
            },
            "misc_up": {

                "c": 0,
                "size": 0
            },
            "misc_down": {

                "c": 0,
                "size": 0
            }}

        self.traffic_port = {
            "server_in_port": {
                # {port: hit}
            },
            "client_in_port": {

            },
            "server_out_port": {
                # {port: hit}
            },
            "client_out_port": {

            }
        }

        self.capture_filter_ips = []
        self.capture_filter_ports = []

        self.is_root()
        self.decoder = EthDecoder()     # packet decoder

        self.live_capture = pcapy.open_live(
            self.iface,
            args['max_bytes'],
            args['promiscuous'],
            args['read_timeout']
        )

        self.packet_limit = args['packet_limit']  # -1

        self.ip2hostname_cache = {}    #
        self.traffic_flow_dict = {}    #
        self.capture_thread = None
        self.packet_index = 0  # index of the captured packet
Esempio n. 21
0
 def getDecoder(self, interfaceType):
     if interfaceType == 0:
         return EthDecoder()
     else:
         return Dot11WPA2Decoder()
Esempio n. 22
0
# -*- coding: utf-8 -*-
"""
:Module: batman
:Synapsis: pcap parser for TCP/IP business
:Author: JP
"""

import sys
from impacket.ImpactDecoder import EthDecoder
from impacket.ImpactPacket import IP, TCP
from pcapy import open_offline, open_live
from numpy import array, sum, mean, std

_ethdecoder = EthDecoder()  # Ethereal (Layer 2) decoder

_pkts = []
_win_size = 100  # number of packets in a window (constant)
_last_ts = None


def is_SYN_only(tcp_flags):
    """
    Checks whether a TCP header has only the SYN flag set.
    
    Parameters
    ----------
    tcp_flags : int
       TCP flag 

    """
    return tcp_flags & ((1 << 6) - 1) == 2
Esempio n. 23
0
 def __init__(self):
     self.decoder = EthDecoder()
Esempio n. 24
0
    def activateLearningMode(self):
        f = open(self.location)
        pcap = dpkt.pcap.Reader(f)
        checker = ICMP6.ICMP6.protocol
        listOfMessages = []
        for ts, buf in pcap:
            eth = EthDecoder().decode(buf)
            ethChild = eth.child()
            ethChild2 = ethChild.child()

            try:
                #print ethChild2
                if ethChild2.get_ip_protocol_number() == 58:
                    destination_MAC_address = []
                    source_MAC_address = []
                    destination_MAC_address = eth.get_ether_dhost()
                    source_MAC_address = eth.get_ether_shost()
                    source_MAC_address_final = ""
                    destination_MAC_address_final = ""
                    override_flag = False
                    router_flag = False
                    x = 0

                    for x in range(6):
                        temp_decimal = source_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        source_MAC_address_final = source_MAC_address_final + temp_hex[
                            2:] + ":"
                        temp_decimal = destination_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        destination_MAC_address_final = destination_MAC_address_final + temp_hex[
                            2:] + ":"

                    source_MAC_address_final = source_MAC_address_final[:
                                                                        -1].zfill(
                                                                            2)
                    destination_MAC_address_final = destination_MAC_address_final[:
                                                                                  -1]
                    target_link_layer_address = ""

                    packetData = (ethChild2.get_originating_packet_data())
                    packetHex = []
                    for data in packetData:
                        packetHex.append(hex(data))
                    # print packetHex
                    source_link_layer_address = ""
                    target_address = ""
                    ip_source_address = ethChild.get_source_address()
                    ip_destination_address = ethChild.get_destination_address()
                    ndp_message_number = ethChild2.get_type()
                    x = 0
                    #print packetHex
                    contains_source, offset = self.check_ipv6_options(
                        packetHex)
                    if str(ndp_message_number) == "134":  #Router Advertisement
                        if str(contains_source) == "true-source":
                            for x in range(6):
                                source_link_layer_address = source_link_layer_address + packetHex[
                                    x + offset + 1][2:].zfill(2) + ":"
                            target_address = "n/a"
                            source_link_layer_address = source_link_layer_address[:
                                                                                  -1]
                            target_link_layer_address = "n/a"
                            #print "*****************************************************************************************"
                            #print source_link_layer_address
                            #print "*****************************************************************************************"
                        else:
                            source_link_layer_address = "n/a"

                    message_details = SLAAC_Message.SLAAC_Message(
                        ndp_message_number, source_link_layer_address,
                        ip_source_address, ip_destination_address,
                        source_MAC_address_final,
                        destination_MAC_address_final, target_address,
                        target_link_layer_address, override_flag, router_flag)

                    #  print "-----------Packet Details----------"
                    #  print "NDP Message Type %s" % message_details.get_ndp_message_number()
                    #  print "Source Link Layer Address: %s" % message_details.get_source_link_layer_address()
                    #  print "Source IPv6 Address %s " % message_details.get_ip_source_address()
                    # print "Destination IPv6 Address %s" % message_details.get_ip_destination_address()
                    # print "Source MAC Address %s" % message_details.get_source_MAC_address()
                    # print "Destination MAC Address %s" % message_details.get_destination_MAC_address()
                    #  print "Target Address %s" % message_details.get_target_address()
                    # print "Target Link Layer Address %s" % message_details.get_target_link_layer_address()
                    # print "Override Flag %s" %message_details.get_override_flag()
                    #   print "Router Flag %s" %message_details.get_router_flag()
                    # print "----------------END----------------"

                    listOfMessages.append(message_details)

            except:
                x = 1
                #print "Packet Discarded"
                #print "fail"

        return listOfMessages
Esempio n. 25
0
 def __init__(self):
     BasePacketDecoder.__init__(self)
     self.decoder = EthDecoder()
    def activateLearningMode(self):
        f = open(self.location)
        pcap = dpkt.pcap.Reader(f)
        checker = ICMP6.ICMP6.protocol
        listOfMessages = []
        for ts, buf in pcap:
            eth = EthDecoder().decode(buf)
            ethChild = eth.child()
            ethChild2 = ethChild.child()

            try:
                #print ethChild2
                if ethChild2.get_ip_protocol_number() == 58:
                    destination_MAC_address = []
                    source_MAC_address = []
                    destination_MAC_address = eth.get_ether_dhost()
                    source_MAC_address = eth.get_ether_shost()
                    source_MAC_address_final = ""
                    destination_MAC_address_final = ""
                    override_flag = False
                    router_flag = False
                    x = 0

                    for x in range(6):
                        temp_decimal = source_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        source_MAC_address_final = source_MAC_address_final + temp_hex[2:] + ":"
                        temp_decimal = destination_MAC_address[x]
                        temp_hex = hex(temp_decimal)
                        destination_MAC_address_final = destination_MAC_address_final + temp_hex[2:] + ":"

                    source_MAC_address_final = source_MAC_address_final[:-1].zfill(2)
                    destination_MAC_address_final = destination_MAC_address_final[:-1]
                    target_link_layer_address = ""

                    packetData = (ethChild2.get_originating_packet_data())
                    packetHex = []
                    for data in packetData:
                        packetHex.append(hex(data))
                    # print packetHex
                    source_link_layer_address = ""
                    target_address = ""
                    ip_source_address = ethChild.get_source_address()
                    ip_destination_address = ethChild.get_destination_address()
                    ndp_message_number = ethChild2.get_type()
                    x = 0
                    #print packetHex
                    contains_source, offset = self.check_ipv6_options(packetHex)
                    if str(ndp_message_number) == "134":  #Router Advertisement
                        if str(contains_source) == "true-source":
                            for x in range(6):
                                source_link_layer_address = source_link_layer_address + packetHex[x + offset + 1][
                                                                                        2:].zfill(2) + ":"
                            target_address = "n/a"
                            source_link_layer_address = source_link_layer_address[:-1]
                            target_link_layer_address = "n/a"
                            #print "*****************************************************************************************"
                            #print source_link_layer_address
                            #print "*****************************************************************************************"
                        else:
                            source_link_layer_address = "n/a"



                    message_details = SLAAC_Message.SLAAC_Message(ndp_message_number, source_link_layer_address,
                                                                  ip_source_address, ip_destination_address,
                                                                  source_MAC_address_final,
                                                                  destination_MAC_address_final, target_address,
                                                                  target_link_layer_address,override_flag,router_flag)


                  #  print "-----------Packet Details----------"
                  #  print "NDP Message Type %s" % message_details.get_ndp_message_number()
                  #  print "Source Link Layer Address: %s" % message_details.get_source_link_layer_address()
                  #  print "Source IPv6 Address %s " % message_details.get_ip_source_address()
                   # print "Destination IPv6 Address %s" % message_details.get_ip_destination_address()
                   # print "Source MAC Address %s" % message_details.get_source_MAC_address()
                   # print "Destination MAC Address %s" % message_details.get_destination_MAC_address()
                  #  print "Target Address %s" % message_details.get_target_address()
                   # print "Target Link Layer Address %s" % message_details.get_target_link_layer_address()
                   # print "Override Flag %s" %message_details.get_override_flag()
                 #   print "Router Flag %s" %message_details.get_router_flag()
                   # print "----------------END----------------"

                    listOfMessages.append(message_details)


            except:
                x = 1
                 #print "Packet Discarded"
                #print "fail"

        return listOfMessages
Esempio n. 27
0
src = sys.argv[1]
dst = sys.argv[2]

# Create a new IP packet and set its source and destination addresses.

ip = IP6.IP6()
ip.set_source_address(src)
ip.set_destination_address(dst)
ip.set_traffic_class(0)
ip.set_flow_label(0)
ip.set_hop_limit(64)

f = open('Packets/MyNigga.s0i0.pcap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
    eth = EthDecoder().decode(buf).child().child().child()
    icmp6 = ICMP6Decoder().decode(buf)
    icmp6Child = icmp6.child()
    checker = icmp6Child.child()

print eth

icmpv6 = ICMP6.ICMP6()
icmpv6.set_type(135)
icmpv6.contains(eth)

# Open a raw socket. Special permissions are usually required.
s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_ICMPV6)

payload = "A" * 156
Esempio n. 28
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 ""
Esempio n. 29
0
 def __init__(self):
     BasePacketDecoder.__init__(self)
     self.decoder = EthDecoder()
Esempio n. 30
0
    def sniffSlaac(self, buf):
        #f = open(self.location)
        #pcap = dpkt.pcap.Reader(f)
        #checker = ICMP6.ICMP6.protocol
        #listOfMessages = []
        #i = 1
        #for ts, buf in pcap:
        eth = EthDecoder().decode(buf)
        ethChild = eth.child()
        ethChild2 = ethChild.child()

        try:
            #print ethChild2
            if ethChild2.get_ip_protocol_number() == 58:
                destination_MAC_address = []
                source_MAC_address = []
                destination_MAC_address = eth.get_ether_dhost()
                source_MAC_address = eth.get_ether_shost()
                source_MAC_address_final = ""
                destination_MAC_address_final = ""
                override_flag = False
                router_flag = False

                x = 0

                for x in range(6):
                    temp_decimal = source_MAC_address[x]
                    temp_hex = hex(temp_decimal)
                    source_MAC_address_final = source_MAC_address_final + temp_hex[
                        2:] + ":"
                    temp_decimal = destination_MAC_address[x]
                    temp_hex = hex(temp_decimal)
                    destination_MAC_address_final = destination_MAC_address_final + temp_hex[
                        2:] + ":"

                source_MAC_address_final = source_MAC_address_final[:-1].zfill(
                    2)
                destination_MAC_address_final = destination_MAC_address_final[:
                                                                              -1]
                target_link_layer_address = ""

                packetData = (ethChild2.get_originating_packet_data())
                packetHex = []
                for data in packetData:
                    packetHex.append(hex(data))
                # print packetHex
                source_link_layer_address = ""
                target_address = ""
                ip_source_address = ethChild.get_source_address()
                ip_destination_address = ethChild.get_destination_address()
                ndp_message_number = ethChild2.get_type()
                x = 0
                #print packetHex
                contains_source, offset = self.check_ipv6_options(packetHex)

                if str(ndp_message_number) == "134":  #Router Advertisement
                    if str(contains_source) == "true-source":
                        for x in range(6):
                            source_link_layer_address = source_link_layer_address + packetHex[
                                x + offset + 1][2:].zfill(2) + ":"
                        target_address = "n/a"
                        source_link_layer_address = source_link_layer_address[:
                                                                              -1]
                        target_link_layer_address = "n/a"
                        #print "*****************************************************************************************"
                        #print source_link_layer_address
                        #print "*****************************************************************************************"
                    else:
                        source_link_layer_address = "n/a"

                elif str(ndp_message_number) == "135":  #Neighbor Solicitation
                    for x in range(16):
                        target_address = target_address + packetHex[x][
                            2:].zfill(2)
                        if (x > 0):
                            if x % 2 != 0:
                                target_address = target_address + ":"
                    target_address = target_address[:-1]
                    target_link_layer_address = "n/a"
                    if str(contains_source) == "true-source":
                        for x in range(6):
                            source_link_layer_address = source_link_layer_address + packetHex[
                                x + offset + 1][2:].zfill(2) + ":"
                        source_link_layer_address = source_link_layer_address[:
                                                                              -1]
                        #print "*****************************************************************************************"
                        #print source_link_layer_address
                        #print "*****************************************************************************************"
                    else:
                        source_link_layer_address = "n/a"

                elif str(ndp_message_number) == "136":  #Neighbor Advertisement

                    #print ethChild2.get_router_flag() #sample code to get router flag of NA
                    #print ethChild2.get_override_flag()
                    #router_flag = ethChild2.get_router_flag()
                    #if router_flag == False:
                    #   print "if else of flag worked"
                    if str(contains_source) == "true-target" and hex(
                            ethChild2.child().get_bytes()[0:1][0]) == "0xa0":
                        for x in range(6):
                            target_link_layer_address = target_link_layer_address + packetHex[
                                1 + offset + x][2:].zfill(2) + ":"
                        target_link_layer_address = target_link_layer_address[:
                                                                              -1]

                    else:
                        target_link_layer_address = "n/a"

                    for x in range(16):
                        target_address = target_address + packetHex[x][
                            2:].zfill(2)
                        if (x > 0):
                            if x % 2 != 0:
                                target_address = target_address + ":"
                    target_address = target_address[:-1]
                    override_flag = ethChild2.get_override_flag()
                    router_flag = ethChild2.get_router_flag()

                message_details = SLAAC_Message.SLAAC_Message(
                    ndp_message_number, source_link_layer_address,
                    ip_source_address, ip_destination_address,
                    source_MAC_address_final, destination_MAC_address_final,
                    target_address, target_link_layer_address, override_flag,
                    router_flag)

                #detection_module.detect_rogue_advertisement(message_details)
                #print "-----------Packet Details----------"
                #print "NDP Message Type %s" % message_details.get_ndp_message_number()
                #print "Source Link Layer Address: %s" % message_details.get_source_link_layer_address()
                #print "Source IPv6 Address %s " % message_details.get_ip_source_address()
                #print "Destination IPv6 Address %s" % message_details.get_ip_destination_address()
                #print "Source MAC Address %s" % message_details.get_source_MAC_address()
                #print "Destination MAC Address %s" % message_details.get_destination_MAC_address()
                #print "Target Address %s" % message_details.get_target_address()
                #print "Target Link Layer Address %s" % message_details.get_target_link_layer_address()
                #print "Override Flag %s" %message_details.get_override_flag()
                #print "Router Flag %s" %message_details.get_router_flag()
                #print "----------------END----------------"

                #detect_module = Detection()

                #if message_details.get_ndp_message_number()=="134": #Last Hop Router Attack
                #    detect_module.detect_rogue_advertisement(message_details)
                #elif message_details.get_ndp_message_number()=="135":#Dos in DAD
                #    detect_module.detect_dos_dad(message_details)
                #elif message_details.get_ndp_message_number()=="136": #Neigbor Spoofing
                #    if ethChild2.get_router_flag()=="false":
                #        detect_module.detect_neighbor_spoofing((message_details))

                #listOfMessages.append(message_details)

        except:
            # x = 1
            print "Packet Discarded"
Esempio n. 31
0
def print_packet(packet_header, packet_data):

    decoded_packet = EthDecoder().decode(packet_data)
    print decoded_packet