def Pack_tcp_packet(ip_src,port_src,ip_dst,port_dst,mac_src,mac_dst,flags,**kwargs): tcp = TCP.TCP(ip_src,port_src,ip_dst,port_dst,"") if "urg" in flags: tcp.set_urg() if "ack" in flags: tcp.set_ack() if "psh" in flags: tcp.set_psh() if "rst" in flags: tcp.set_rst() if "syn" in flags: tcp.set_syn() if "fin" in flags: tcp.set_fin() if "acknowledgment_number" in kwargs: tcp.acknowledgment_number = kwargs["acknowledgment_number"] if "sequence_number" in kwargs: tcp.sequence_number = kwargs["sequence_number"] if "payload" in kwargs: tcp.payload= kwargs["payload"] tcp_header = tcp.Pack() ip = IP.IP(ip_src,ip_dst,tcp_header) ip_header = ip.Pack() mac_src = Convert_mac_address(mac_src) mac_dst = Convert_mac_address(mac_dst) ethernet = Ethernet.Ethernet(mac_src,mac_dst,0x0800,ip_header) packet = ethernet.Pack() return packet,tcp.sequence_number
def __init__(self, LL_options, interface_IP_addresses): # these options are not given yet but it could include error correction protocols, IEEE 802.11 MAC, etc. self.LL_options = LL_options self.interface_IP_addresses = interface_IP_addresses self.mac_protocols = list() self.mac_protocols_index = dict() if debug_flag_LL: print self.LL_options for (protocol, options) in self.LL_options: if protocol == 'Ethernet': interface_ID = options self.mac_protocols.append( Ethernet.Ethernet(interface_IP_addresses[interface_ID])) self.mac_protocols_index['Ethernet'] = interface_ID self.from_network_layer = dict() self.to_phy_layer = dict() self.from_phy_layer = dict() self.to_network_layer = dict() for (intf, mac) in interface_IP_addresses: self.from_network_layer[intf] = Queue() self.to_phy_layer[mac] = Queue() self.from_phy_layer[mac] = Queue() self.to_network_layer[intf] = Queue() self.current_frame_no = 0
def create_arp_packet(spa,tpa,SHA,THA,mac_src): SHA = Convert_mac_address(SHA) THA = SHA = Convert_mac_address(THA) arp = ARP.ARP(SHA,spa,THA,tpa) arp_header = arp.Pack() mac_dst = Convert_mac_address("ff:ff:ff:ff:ff:ff") ethernet= Ethernet.Ethernet(mac_src,mac_dst,0x0806,arp_header) packet = ethernet.Pack() return packet
def UnPack_tcp_packet(packet): tcp = None try: ethernet = Ethernet.Ethernet("","","","") ethernet_payload = ethernet.UnPack(packet) ip = IP.IP("","","") ip.UnPack(ethernet.Ethernet_payload) tcp = TCP.TCP("","","","","") tcp.UnPack(ip.payload) except Exception,e: return None
def main(): ## Define Variables ### totalbytes = 0 timestamp = time.time() totaltime = 0 totalrcvs = 0 INETX = False ## Find the current Host of the Analyzer ### operating_system = platform.system() HOST = socket.gethostbyname(socket.gethostname()) ## Windows and Linux(Raspberry Pi) Bind differently to a Socket ### if operating_system == 'Windows': conn = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) conn.bind((HOST, 0)) conn.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) conn.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) else: conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) conn.bind(('eth0', 0)) ## while True: if operating_system == 'Linux': raw_data, addr = conn.recvfrom(65535) ethernet_header = ethernet.Ethernet() ethernet_header.unpack(raw_data) ##socket for windows skips the Ethernet layer as this is not a requirement. ### if ethernet_header.eth_proto == 8 or operating_system == 'Windows': ip_header = ip.IP() ip_header.unpack(raw_data[14:]) if ip_header.protocol == 17 and ip_header.src_ip != '192.168.28.10': udp_header = udp.UDP() udp_header.unpack(raw_data[34:]) donestamp = time.time() data = len(raw_data) totalbytes += data totalrcvs += 1 totaltime = round((donestamp - timestamp), 0) rate = round( (((totalbytes * 8) / (donestamp - timestamp)) / 1000), 3) if hexConvert(udp_header.control) == '11000000': INETX = True inetx_header = inetx.INETX() inetx_header.unpack(raw_data[42:]) elif hexConvert(udp_header.control) != '11000000': iena_header = iena.IENA() iena_header.unpack(raw_data[42:]) ## publish contents of headers to MQTT ## if INETX == True: INETXpacket = { 'type': 'INETX', 'id': hexConvert(inetx_header.streamid), 'seq': inetx_header.sequence, 'src': ipv4(ip_header.src_ip), 'dst': ipv4(ip_header.dst_ip), 'size': udp_header.len, 'time': ptp(inetx_header.ptptime), 'BR': inetx_header.bitRate(), } packet_json = json.dumps(INETXpacket) ttl = json.dumps({ 'ttlBR': rate, 'pktNo': totalrcvs, 'drop': inetx_header.missedcount, }) client.publish("Packet", packet_json) client.publish("ttl", ttl) else: IENApacket = { 'type': 'IENA', 'id': hexConvert(iena_header.key), 'seq': iena_header.sequence, 'src': ipv4(ip_header.src_ip), 'dst': ipv4(ip_header.dst_ip), 'size': udp_header.len, 'time': unix(iena_header.timeHi, iena_header.timeLo), 'BR': iena_header.bitRate(), } packet_json = json.dumps(IENApacket) ttl = json.dumps({ 'ttlBR': rate, 'pktNo': totalrcvs, 'drop': iena_header.missedcount, }) client.publish("Packet", packet_json) client.publish("ttl", ttl)
import struct import socket import Ethernet from IPv4 import IPv4 from TCP import TCP from UDP import UDP from HTTP import HTTP sniffer = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3)) raw_data, add = sniffer.recvfrom(4096) eth = Ethernet.Ethernet(raw_data) print(eth.frame) print(eth.src_mac) print(eth.dest_mac) print(eth.proto) #ipv4 if eth.proto == 2048: packet = IPv4(eth.data) print(packet.dest_add) print(packet.src_add) print(packet.protocol) #TCP if packet.protocol == 6: tcp = TCP(packet.data) print(tcp.src_port) print(tcp.dest_port) print(tcp.ack) print(tcp.seq_no, ' ', tcp.ack_no)
def analyses_toute_les_trames(Liste_trames, fichier): """list [ tuple(list[octects], bool, int ,int) ] -> None Analyse toutes les trames recuperees """ length = len(Liste_trames) # nombre de trames recuperees # Parcours de toutes les trames recuperees for i in range(length): Trame, ok, ligne_erreur, taille = Liste_trames[i] print("\n********************* Analyse de la trame", i + 1, "******************** \n") # if la trame est errone en raison des offsets invalides if Trame == []: print( " \nLa trame", i, "est erronee car l'offset n'est pas dans l'ordre croissant\n") fichier.write("*\n!\n") continue # if il manque des octets dans la trame if not ok: print(" \nLa trame", i, "a rencontré une erreur à la ligne ", ligne_erreur, " de sa trame\n") fichier.write("*\n!\n") continue print(taille, " octets de donnees") # donne des noms differents a chaque trame et leurs composantes str_num = str(i) str_Ethernet = "Ethernet_" + str_num str_IP = "IP_" + str_num str_TCP = "TCP_" + str_num str_HTTP = "HTTP_" + str_num # Entete Ethernet dest_mac = Trame[:6] # Destination (Adresse MAC) src_mac = Trame[6:12] # Soruce (Adresse MAC) type_ethernet = Trame[12:14] # Type Ethernet str_Ethernet = Ethernet(dest_mac, src_mac, type_ethernet) str_Ethernet.affichage() str_Ethernet.affichage_bouton(fichier) # If la trame n'est pas IPv4 then aller à la trame suivante if not est_IPv4(Trame): print("Notre analyseur ne prend pas en compte le protocole 0x" + ''.join(Trame[12:14])) fichier.write("14 " + str(taille)) continue # Entete IPv4 version = Trame[14][0] # Version header_length_ip = Trame[14][1] # Header Length dsf = Trame[15] # Differentiated Sevices Field total_length = Trame[16:18] # Total Length id = Trame[18:20] # Identification flags_ip = Trame[20] # Flags offset = Trame[20:22] # Framgment offset ttl = Trame[22] # Time to live protocol = Trame[23] # Protocol checksum_ip = Trame[24:26] # Header Checksum src_ip = Trame[26:30] # Source IP dest_ip = Trame[30:34] # Destination IP options_ip = [] # Options IP str_IP = IP(version, header_length_ip, dsf, total_length, id, flags_ip, offset, ttl, protocol, checksum_ip, src_ip, dest_ip, options_ip) taille_options_IP = str_IP.taille_options_IP( ) # Recupere la taille des options IP si elles existent fin_IP = 34 + taille_options_IP # Recupere le dernier octect de l'entete IP str_IP.set_options(Trame[34:fin_IP]) # Affectation des options de IP str_IP.verification_checksum(Trame[14:fin_IP]) # Check le checksum str_IP.affichage() str_IP.affichage_bouton(fichier) # if la trame recuperee n'est pas de la taille de totale_length if not nombre_octects_exacts(taille, int(''.join(str_IP.total_length), 16)): print("La trame contient ", taille, "octets alors qu'elle devrait en contenir", int(''.join(str_IP.total_length), 16) + 14) continue # if la trame n'est pas TCP then aller à la trame suivante if not est_TCP(Trame): print("\nNotre analyseur ne prend pas en compte le protocole 0x" + ''.join(Trame[23])) fichier.write(str(fin_IP) + " " + str(taille) + "\n") continue # Entete TCP debut_TCP = fin_IP # premier octer du segment TCP src_port = Trame[debut_TCP:debut_TCP + 2] # Source Port dest_port = Trame[debut_TCP + 2:debut_TCP + 4] # Destination Port sequence = Trame[debut_TCP + 4:debut_TCP + 8] # Sequence number acknowledgment = Trame[debut_TCP + 8:debut_TCP + 12] # acknowledgment number header_length_tcp = Trame[debut_TCP + 12] # Header Length flags_tcp = Trame[debut_TCP + 12:debut_TCP + 14] # Flags window = Trame[debut_TCP + 14:debut_TCP + 16] # Window checksum_tcp = Trame[debut_TCP + 16:debut_TCP + 18] # Checksum urgent_pointer = Trame[debut_TCP + 18:debut_TCP + 20] # Urgent pointer options_tcp = [] # Options TCP_length = str( hex( int(''.join(str_IP.total_length), 16) - 20 - taille_options_IP)[2:].zfill(4)) # Taille du segment TCP str_TCP = TCP(src_port, dest_port, sequence, acknowledgment, header_length_tcp, flags_tcp, window, checksum_tcp, urgent_pointer, options_tcp) str_TCP.set_options(Trame[debut_TCP + 20:debut_TCP + 20 + str_TCP.taille_options_TCP()]) str_TCP.verification_checksum(src_ip + dest_ip + ["00"] + [protocol] + [TCP_length[0:2]] + [TCP_length[2:4]] + Trame[debut_TCP:]) # Check le checksum str_TCP.affichage() str_TCP.affichage_bouton(fichier, debut_TCP) taille_options_TCP = str_TCP.taille_options_TCP( ) # Recupère la taille des options TCP si elles existent fin_TCP = debut_TCP + 20 + taille_options_TCP # Recupere le dernier octect de l'entete IP # if pas de data then aller a la trame suivante if fin_TCP == taille: continue # if la trame n'est pas HTTP then aller à la trame suivante if not est_HTTP(Trame, src_port, dest_port): print( "\nNotre analyseur ne peut pas lire le contenu de ce segment (pas HTTP)" ) continue debut_HTTP = fin_TCP # Récupère le premier octet du segment HTTP str_HTTP = HTTP(Trame[debut_HTTP:]) str_HTTP.affichage() str_HTTP.affichage_bouton(fichier, debut_HTTP) return None
try: pcapFile = dpkt.pcap.Reader(file) serial_number = 0 sending_nodes_IP = {} dest_nodes_IP = {} sending_nodes_IP_w_values = {} arp_frames = [] arp_requests_without_pair_frames = [] arp_requests_without_pair_ip_frames = [] arp_printed_frames = {} dns_nad_udp = [] dns_nad_udp_ids = [] for ts, buf in pcapFile: eth = dpkt.ethernet.Ethernet(buf) serial_number += 1 type = Ethernet.ethernet11(buf) print( myColors.myColors.red + "Serial number No. {} ".format(serial_number) + myColors.myColors.ENDC) print(myColors.myColors.red + "Time stamp {}".format(ts) + myColors.myColors.ENDC) print(myColors.myColors.red + "The frame length in bytes provided by the pcap API {} B".format( len(buf)) + myColors.myColors.ENDC) if len(buf) <= 60: print( myColors.myColors.red + "The frame length in bytes provided by the pcap API 64 B" + myColors.myColors.ENDC) else: print(myColors.myColors.red + "The frame length in bytes provided by media {} B ".format( len(buf) + 4) + myColors.myColors.ENDC) print(myColors.myColors.red + "Frame type: {}".format(type)) print(myColors.myColors.red + "Destination Mac Address: ",