def __decodeLayer4(self, ipProtocolNum, l3Payload): """Internal method that parses the specified header and extracts layer4 related proprieties.""" if ipProtocolNum == Packets.UDP.protocol: l4Proto = "UDP" l4Decoder = Decoders.UDPDecoder() layer4 = l4Decoder.decode(l3Payload) l4SrcPort = layer4.get_uh_sport() l4DstPort = layer4.get_uh_dport() l4Payload = layer4.get_data_as_string() return (l4Proto, l4SrcPort, l4DstPort, l4Payload) elif ipProtocolNum == Packets.TCP.protocol: l4Proto = "TCP" l4Decoder = Decoders.TCPDecoder() layer4 = l4Decoder.decode(l3Payload) l4SrcPort = layer4.get_th_sport() l4DstPort = layer4.get_th_dport() l4Payload = layer4.get_data_as_string() return (l4Proto, l4SrcPort, l4DstPort, l4Payload) else: warnMessage = _( "Cannot import one of the provided packets since " + "its layer 4 is unsupported (Only UDP and TCP " + "are currently supported, packet IP protocol " + "number = {0})").format(ipProtocolNum) self._logger.warn(warnMessage) raise NetzobImportException("PCAP", warnMessage, self.INVALID_LAYER4)
def decodeLayer2(self, header, payload): def formatMacAddress(arrayMac): return ":".join("{0:0>2}".format(hex(b)[2:]) for b in arrayMac.tolist()) if self.datalink == pcapy.DLT_EN10MB: l2Decoder = Decoders.EthDecoder() l2Proto = "Ethernet" layer2 = l2Decoder.decode(payload) l2SrcAddr = formatMacAddress(layer2.get_ether_shost()) l2DstAddr = formatMacAddress(layer2.get_ether_dhost()) l2Payload = payload[layer2.get_header_size():] etherType = layer2.get_ether_type() elif self.datalink == pcapy.DLT_LINUX_SLL: l2Decoder = Decoders.LinuxSLLDecoder() l2Proto = "Linux SLL" layer2 = l2Decoder.decode(payload) l2SrcAddr = layer2.get_addr() l2DstAddr = None l2Payload = payload[layer2.get_header_size():] etherType = layer2.get_ether_type() elif self.datalink == PCAPImporter.PROTOCOL201: l2Proto = "Protocol 201" hdr = payload.encode('hex')[0:8] if hdr[6:] == "01": l2SrcAddr = "Received" else: l2SrcAddr = "Sent" l2DstAddr = None l2Payload = payload[8:] etherType = payload[4:6] return (l2Proto, l2SrcAddr, l2DstAddr, l2Payload, etherType)
def pcap_to_object(pcap_file, obj_file): """Create a Python serialized graph object. Read the pcap file given in parameter, extracts source and destination IP and write a serialized graph object. """ reader = pcapy.open_offline(pcap_file) print reader.datalink() print pcapy.DLT_LINUX_SLL eth_decoder = Decoders.EthDecoder() sll_decoder = Decoders.LinuxSLLDecoder() ip_decoder = Decoders.IPDecoder() dic_ip = ip_dict() tts_min = 1000 tts_max = 2000 if options.verbose: print "Reading pcap file..." while True: try: (header, payload) = reader.next() if True: #tts_min <= header.getts()[0] <= tts_max: #ethernet = eth_decoder.decode(payload) sll = sll_decoder.decode(payload) if sll.get_ether_type() == Packets.IP.ethertype: #ip = ip_decoder.decode(payload[ethernet.get_header_size():]) ip_src = sll.child().get_ip_src() ip_dst = sll.child().get_ip_dst() dic_ip[ip_src][ip_dst] += 1 except Packets.ImpactPacketException, e: print e except:
def decodeLayer4(self, ipProtocolNum, l3Payload): if ipProtocolNum == Packets.UDP.protocol: l4Proto = "UDP" l4Decoder = Decoders.UDPDecoder() layer4 = l4Decoder.decode(l3Payload) l4SrcPort = layer4.get_uh_sport() l4DstPort = layer4.get_uh_dport() l4Payload = layer4.get_data_as_string() return (l4Proto, l4SrcPort, l4DstPort, l4Payload) elif ipProtocolNum == Packets.TCP.protocol: l4Proto = "TCP" l4Decoder = Decoders.TCPDecoder() layer4 = l4Decoder.decode(l3Payload) l4SrcPort = layer4.get_th_sport() l4DstPort = layer4.get_th_dport() l4Payload = layer4.get_data_as_string() return (l4Proto, l4SrcPort, l4DstPort, l4Payload) else: warnMessage = _( "Cannot import one of the provided packets since " + "its layer 4 is unsupported (Only UDP and TCP " + "are currently supported, packet IP protocol " + "number = {0})").format(ipProtocolNum) self.log.warn(warnMessage) raise NetzobImportException("PCAP", warnMessage, WARNING, self.INVALID_LAYER4)
def __init__(self, iface, mac_address): self.devices = dict() self.pd = pcapy.open_live(iface, helpers.PCAP_SNAPLEN, helpers.PCAP_PROMISCOUS, helpers.PCAP_TIMEOUT) bpf_filter = "(type mgt subtype probe-resp) and (wlan addr1 %s)" % mac_address self.pd.setfilter(bpf_filter) datalink = self.pd.datalink() if datalink == helpers.PCAP_DLT_IEEE802_11: self.decoder = ImpactDecoder.Dot11Decoder() elif datalink == helpers.PCAP_DLT_IEEE802_11_RADIOTAP: self.decoder = ImpactDecoder.RadioTapDecoder() else: raise Exception("Invalid datalink.") self.run()
def __init__(self, name, personality, ethernet, actions, services, binds): """Function initializes a network device Args: name : name of the device personality : nmap personality of the device ethernet : ethernet address of the device actions : default actions of the device for packets of certain protocols services : detailed actions for protocols and port numbers binds : ip addresses the devices """ logger.debug('Creating device %s on IPs %s', name, binds) self.name = name self.personality = personality self.mac = ethernet try: self.ethernet = [int(i, 16) for i in self.mac.split(':')] except BaseException: logger.exception('Exception: MAC conversion for device %s failed: %s', self.name, self.mac) sys.exit(1) self.ethernet = tuple(self.ethernet) self.action_dictionary = actions self.service_list = services self.bind_list = binds self.protocol_mapping = ( ('icmp', 1, ICMPHandler()), # IP_PROTO_ICMP ('tcp', 6, TCPHandler()), # IP_PROTO_TCP ('udp', 17, UDPHandler()) # IP_PROTO_UDP ) self.metadata = { 'ip_id': 0, # IP ID 'ip_id_delta': 0, 'cip_id': 0, # CLOSED IP ID 'cip_id_delta': 0, 'icmp_id': 0, # ICMP ID 'icmp_id_delta': 0, 'tcp_isn': 0, # TCP ISN 'tcp_isn_delta': 0, 'tcp_isn_gcd': 0, 'tcp_isn_dev': 0, 'tcp_ts': 0, # TCP TS 'tcp_ts_delta': 0 } self.ip_id_generator() self.tcp_isn_generator() self.tcp_ts_generator() # script can return IP()/ICMP() -> see impacket bug #4870 self.decoder = ImpactDecoder.IPDecoder() self.decoder_icmp = ImpactDecoder.IPDecoderForICMP()
def parse_packet(self, header, frame): # pcap语法分析 datalink = self.pcap.datalink() if datalink == pcapy.DLT_EN10MB: decoder = ImpactDecoder.EthDecoder() elif datalink == pcapy.DLT_LINUX_SLL: decoder = ImpactDecoder.LinuxSLLDecoder() else: raise Exception("Datalink not supported") ether = decoder.decode(frame) # 每个数据包的数据 ts = float(str(header.getts()[0]) + "." + str(header.getts()[1])) # packet的时间戳 self.last_timestamp = ts if ether.get_ether_type() == ImpactPacket.IP.ethertype: (id, tcp_tuple) = generate_id(ether) if id == False: return (rev_id, tcp_tuple) = generate_reverse_id(ether) # print("Buffer", self.tcp_buffer) # print(threading.current_thread().name + "in",) self.acquire_lock("parse") # print(threading.current_thread().name + "out") if id in self.tcp_buffer: tcp_stream = self.tcp_buffer[id] to_server = True # print("[fwd] ID: " + id + ";" + str(ts)) elif rev_id in self.tcp_buffer: tcp_stream = self.tcp_buffer[rev_id] to_server = False # print("[rev] ID: " + id + ";" + str(ts)) else: # 读到的数据包属于新的一个流 # a new stream has appeared tcp_stream = TcpStream(id, ts, self) self.tcp_buffer[id] = tcp_stream to_server = True packet = ether.child() segment = packet.child() tcp_stream.start() # print("[new] ID: " + id + ";" + str(ts)) tcp_stream.add_packet(ts, to_server, ether) # 数据包加到tcp流中 # if tcp_stream.state in end_states: # tcp_stream.finish() # self.move_stream(tcp_stream.id) self.packet_counter += 1 self.release_lock("parse")
def parse_packet(self, header, frame): decoder = ImpactDecoder.EthDecoder() ether = decoder.decode(frame) ready_indices = [] if ether.get_ether_type() == ImpactPacket.IP.ethertype: self.lock.acquire() for i in range(0, len(self.connection_list)): buffered_packets = self.connection_list[i] if buffered_packets.add_frame( ether): #if there's an existing flow self.lock.release() if len(ready_indices) > 0: self.move_ready_packets(ready_indices) return if buffered_packets.ready: ready_indices.append(i) buffered_packets = BufferedPackets(header, ether) self.connection_list.append(buffered_packets) self.lock.release() if len(ready_indices) > 0: self.move_ready_packets(ready_indices)
def __decodeLayer3(self, etherType, l2Payload): """Internal method that parses the specified header and extracts layer3 related proprieties.""" if etherType == Packets.IP.ethertype: l3Proto = "IP" l3Decoder = Decoders.IPDecoder() layer3 = l3Decoder.decode(l2Payload) paddingSize = len(l2Payload) - layer3.get_ip_len() l3SrcAddr = layer3.get_ip_src() l3DstAddr = layer3.get_ip_dst() l3Payload = l2Payload[layer3.get_header_size():] if paddingSize > 0 and len(l3Payload) > paddingSize: l3Payload = l3Payload[:len(l3Payload) - paddingSize] ipProtocolNum = layer3.get_ip_p() return (l3Proto, l3SrcAddr, l3DstAddr, l3Payload, ipProtocolNum) else: warnMessage = _( "Cannot import one of the provided packets since " + "its layer 3 is unsupported (Only IP is " + "currently supported, packet ethernet " + "type = {0})").format(etherType) self._logger.warn(warnMessage) raise NetzobImportException("PCAP", warnMessage, self.INVALID_LAYER3)
def collector(self, buffer): try: decoder = ImpactDecoder.EthDecoder() packet = decoder.decode(buffer) if packet.get_ether_type() == ImpactPacket.IP.ethertype: ip = packet.child() if ip and ip.get_ip_p() == ImpactPacket.UDP.protocol: udppacket = ip.child() data = udppacket.get_data_as_string() payload = self.decoder(data) if payload: self.logger.debug( '%s got a payload from %s' % (self.__class__.__name__, ip.get_ip_src())) # print '%s got a payload from %s' % (self.__class__.__name__, ip.get_ip_src()) result = payload result['Source Host'] = ip.get_ip_src() result['Protocol Subtype'] = 'Port' result['Subtype'] = str(udppacket.get_uh_dport()) return result else: return except Exception as e: # If the decoding fails, it just wasn't meant to be. pass return
def test_decoding_simple_destination_options(self): destination_options_binary_packet = [ 0x2b, 0x01, 0x01, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] d = ImpactDecoder.DestinationOptionsDecoder() parsed_packet = d.decode(destination_options_binary_packet) next_header = parsed_packet.get_next_header() header_extension_length = parsed_packet.get_header_extension_length() options = parsed_packet.get_options() self.assertEqual(1, len(options), "Simple Destination Options Parsing - Wrong Quantity of Options") padn_option = options[0] padn_option_type = padn_option.get_option_type() padn_option_length = padn_option.get_option_length() self.assertEqual(parsed_packet.get_header_type(), 60, "Simple Destination Options Parsing - Incorrect packet") self.assertEqual(next_header, 43, "Simple Destination Options Parsing - Incorrect next header value") self.assertEqual(header_extension_length, 1, "Simple Destination Options Parsing - Incorrect size") self.assertEqual(padn_option_type, 1, "Simple Destination Options Parsing - Incorrect option type") self.assertEqual(padn_option_length, 12, "Simple Destination Options Parsing - Incorrect option size")
def test_decoding_multi_option_destination_options(self): destination_options_binary_packet = [ 0x3a, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00] d = ImpactDecoder.DestinationOptionsDecoder() parsed_packet = d.decode(destination_options_binary_packet) next_header = parsed_packet.get_next_header() header_extension_length = parsed_packet.get_header_extension_length() options = parsed_packet.get_options() self.assertEqual(2, len(options), "Destination Options with multiple options parsing - Wrong Quantity of Options") pad1_option = options[0] pad1_option_type = pad1_option.get_option_type() padn_option = options[1] padn_option_type = padn_option.get_option_type() padn_option_length = padn_option.get_option_length() self.assertEqual(parsed_packet.get_header_type(), 60, "Destination Options with multiple options parsing - Incorrect packet") self.assertEqual(next_header, 58, "Destination Options with multiple options parsing - Incorrect next header value") self.assertEqual(header_extension_length, 0, "Destination Options with multiple options parsing - Incorrect size") self.assertEqual(pad1_option_type, 0, "Destination Options with multiple options parsing - Incorrect option type") self.assertEqual(padn_option_type, 1, "Destination Options with multiple options parsing - Incorrect option type") self.assertEqual(padn_option_length, 3, "Destination Options with multiple options parsing - Incorrect option size")
def test_decoding_extension_header_from_string(self): hop_by_hop_binary_packet = b'\x2b\x01\x01\x0C\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' d = ImpactDecoder.HopByHopDecoder() parsed_packet = d.decode(hop_by_hop_binary_packet) next_header = parsed_packet.get_next_header() header_extension_length = parsed_packet.get_header_extension_length() options = parsed_packet.get_options() self.assertEqual( 1, len(options), "Simple Hop By Hop Parsing - Wrong Quantity of Options") padn_option = options[0] padn_option_type = padn_option.get_option_type() padn_option_length = padn_option.get_option_length() self.assertEqual(parsed_packet.get_header_type(), 0, "Simple Hop By Hop Parsing - Incorrect packet") self.assertEqual( next_header, 43, "Simple Hop By Hop Parsing - Incorrect next header value") self.assertEqual(header_extension_length, 1, "Simple Hop By Hop Parsing - Incorrect size") self.assertEqual(padn_option_type, 1, "Simple Hop By Hop Parsing - Incorrect option type") self.assertEqual(padn_option_length, 12, "Simple Hop By Hop Parsing - Incorrect option size")
def parse(models, header, packet): length_groups = [500, 1500] decoder = ImpactDecoder.EthDecoder() ether = decoder.decode(packet) #print str(ether.get_ether_type()) + " " + str(ImpactPacket.IP.ethertype) if ether.get_ether_type() == ImpactPacket.IP.ethertype: iphdr = ether.child() transporthdr = iphdr.child() if transporthdr.get_data_as_string() != '' and isinstance(transporthdr, ImpactPacket.TCP): s_addr = iphdr.get_ip_src() d_addr = iphdr.get_ip_dst() s_port = transporthdr.get_th_sport() d_port = transporthdr.get_th_dport() d_length = transporthdr.get_size() payload = transporthdr.get_data_as_string() grams = get_byte_freq(payload, d_length) group_length = length_groups[len(length_groups)-1] for i in range(0, len(length_groups) - 1): if d_length <= length_groups[i]: group_length = length_groups[i] group = str(d_port) + "-" + str(group_length) if group in models: models[group].add_grams(grams) else: models[group] = PaylModel(d_port, group_length) models[group].add_grams(grams)
def collector(self, buffer): """ The collector method for OFTGPacket plugin is responsible for analyzing collected packet data for OFTG-Ninja payloads. The collector method MUST use the decoder() method to analyze extracted data. :return: Dict, as returned by decoder() """ try: decoder = ImpactDecoder.EthDecoder() packet = decoder.decode(buffer) if packet.get_ether_type() == ImpactPacket.IP.ethertype: ip = packet.child() if ip and ip.get_ip_p() == ImpactPacket.ICMP.protocol: icmppacket = ip.child() data = icmppacket.get_data_as_string() result = self.decoder(data) if result: # self.logger.debug('%s got a payload from %s' % (self.__class__.__name__, ip.get_ip_src())) result['Source Host'] = ip.get_ip_src() result['Protocol Subtype'] = 'ICMP Type' result['Subtype'] = str(icmppacket.get_icmp_type()) return result else: return else: return except Exception as e: raise return
def test_decoding_simple_routing_options(self): routing_options_binary_packet = [ 0x3a, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00 ] d = ImpactDecoder.RoutingOptionsDecoder() parsed_packet = d.decode(routing_options_binary_packet) next_header = parsed_packet.get_next_header() header_extension_length = parsed_packet.get_header_extension_length() routing_type = parsed_packet.get_routing_type() segments_left = parsed_packet.get_segments_left() options = parsed_packet.get_options() self.assertEqual(parsed_packet.get_header_type(), 43, "Simple Routing Options Parsing - Incorrect packet") self.assertEqual( next_header, 58, "Simple Routing Options Parsing - Incorrect next header value") self.assertEqual(header_extension_length, 0, "Simple Routing Options Parsing - Incorrect size") self.assertEqual( routing_type, 0, "Simple Routing Options Parsing - Incorrect routing type") self.assertEqual( segments_left, 10, "Simple Routing Options Parsing - Incorrect quantity of segments left size" ) self.assertEqual( 0, len(options), "Simple Routing Options Parsing - Wrong Quantity of Options")
def isIP(p): ether_packet = ImpactDecoder.EthDecoder().decode(p) eth_type = hex(ether_packet.get_ether_type()) if getNameProtocolEthernet(eth_type) == "IPv4": return True else: return False
def create_test_sock(pcap_filename): rospy.sleep(0.1) import pcapy from StringIO import StringIO from impacket import ImpactDecoder body_list = [] cap = pcapy.open_offline(pcap_filename) decoder = ImpactDecoder.EthDecoder() while True: header, payload = cap.next() if not header: break udp = decoder.decode(payload).child().child() body_list.append(udp.child().get_packet()) data_io = StringIO(''.join(body_list)) class MockSocket(object): def recv(self, byte_count): rospy.sleep(0.0001) data = data_io.read(byte_count) if data == "": rospy.signal_shutdown("Test completed.") return data def settimeout(self, timeout): pass return MockSocket()
def work(): libdivert = MacDivert() decoder = ImpactDecoder.IPDecoder() with DivertHandle(libdivert, 0, "ip from any to any via en0") as fid: pcap = fid.open_pcap('sniff.pcap') # register stop loop signal signal(SIGINT, lambda x, y: fid.close()) while not fid.closed: try: packet = fid.read(timeout=0.5) except: continue if packet.valid: if packet.proc: proc_str = '%s: %d\t' % \ (packet.proc.comm, packet.proc.pid) else: proc_str = 'Unknown process\t' if fid.is_inbound(packet.sockaddr): direct_str = 'inbound' elif fid.is_outbound(packet.sockaddr): direct_str = 'outbound' else: direct_str = 'impossible packet!' print proc_str + direct_str print decoder.decode(packet.ip_data) if packet.valid and not fid.closed: # re-inject the packet fid.write(packet) # save the packet into sniff.pcap pcap.write(packet)
def test_decoding(self): '''Test IP6 Packet decoding.''' d = ImpactDecoder.IP6Decoder() parsed_packet = d.decode(self.binary_packet) protocol_version = parsed_packet.get_protocol_version() traffic_class = parsed_packet.get_traffic_class() flow_label = parsed_packet.get_flow_label() payload_length = parsed_packet.get_payload_length() next_header = parsed_packet.get_next_header() hop_limit = parsed_packet.get_hop_limit() source_address = parsed_packet.get_source_address() destination_address = parsed_packet.get_destination_address() self.assertEquals(protocol_version, 6, "IP6 parsing - Incorrect protocol version") self.assertEquals(traffic_class, 72, "IP6 parsing - Incorrect traffic class") self.assertEquals(flow_label, 148997, "IP6 parsing - Incorrect flow label") self.assertEquals(payload_length, 1500, "IP6 parsing - Incorrect payload length") self.assertEquals(next_header, 17, "IP6 parsing - Incorrect next header") self.assertEquals(hop_limit, 1, "IP6 parsing - Incorrect hop limit") self.assertEquals(source_address.as_string(), "FE80::78F8:89D1:30FF:256B", "IP6 parsing - Incorrect source address") self.assertEquals(destination_address.as_string(), "FF02::1:3", "IP6 parsing - Incorrect destination address")
def test_decoding_multi_option_hop_by_hop(self): hop_by_hop_binary_packet = [ 0x3a, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00] d = ImpactDecoder.HopByHopDecoder() parsed_packet = d.decode(hop_by_hop_binary_packet) next_header = parsed_packet.get_next_header() header_extension_length = parsed_packet.get_header_extension_length() options = parsed_packet.get_options() self.assertEquals(2, len(options), "Simple Hop By Hop Parsing - Wrong Quantity of Options") pad1_option = options[0] pad1_option_type = pad1_option.get_option_type() padn_option = options[1] padn_option_type = padn_option.get_option_type() padn_option_length = padn_option.get_option_length() self.assertEquals(parsed_packet.get_header_type(), 0, "Hop By Hop with multiple options parsing - Incorrect packet") self.assertEquals(next_header, 58, "Hop By Hop with multiple options parsing - Incorrect next header value") self.assertEquals(header_extension_length, 0, "Hop By Hop with multiple options parsing - Incorrect size") self.assertEquals(pad1_option_type, 0, "Hop By Hop with multiple options parsing - Incorrect option type") self.assertEquals(padn_option_type, 1, "Hop By Hop with multiple options parsing - Incorrect option type") self.assertEquals(padn_option_length, 3, "Hop By Hop with multiple options parsing - Incorrect option size")
def __init__(self, interface, network, default, elements, loggers, tunnels): """Function initialized the dipatcher Args: interface : name of the network interface to listen network : networkx graph representation of the network default : default template elements : elements of the network loggers : instances of the logger modules tunnels : tunnel configuration """ self.interface = interface self.mac = netifaces.ifaddresses( self.interface)[netifaces.AF_LINK][0]['addr'] self.network = network try: post('http://localhost:8080/network', json=dumps(json_graph.node_link_data(self.network))) except: logger.exception('Exception: Cannot connect to local server.') self.default = default self.devices, self.routes, self.externals = elements self.hpfeeds, self.dblogger = loggers self.tunnels = tunnels self.packet_queue = dict() self.entry_points = list() self.unreach_list = list() self.pcapy_object = pcapy.open_live(self.interface, 65535, 1, 10) self.decoder = ImpactDecoder.EthDecoder() self.ip_decoder = ImpactDecoder.IPDecoder() self.ip_icmp_decoder = ImpactDecoder.IPDecoderForICMP() self.mac_set = set([self.mac]) for d in self.devices: if len(d.mac): self.mac_set.add(d.mac) for r in self.routes: if r.entry: self.entry_points.append(r) self.unreach_list.extend(r.unreach_list) logger.info('Started dispatcher listening on interface %s', self.interface) while True: try: (hdr, pkt) = self.pcapy_object.next() self.callback(hdr, pkt) except KeyboardInterrupt: return
def __init__(self, iface): self.devices = dict() self.pd = pcapy.open_live(iface, helpers.PCAP_SNAPLEN, helpers.PCAP_PROMISCOUS, helpers.PCAP_TIMEOUT) # Filter Action frames with an specific BSSID Address bpf_filter = "wlan[0] = 0xd0 and wlan addr3 00:25:00:ff:94:73" self.pd.setfilter(bpf_filter) datalink = self.pd.datalink() if datalink == helpers.PCAP_DLT_IEEE802_11: self.decoder = ImpactDecoder.Dot11Decoder() elif datalink == helpers.PCAP_DLT_IEEE802_11_RADIOTAP: self.decoder = ImpactDecoder.RadioTapDecoder() else: raise Exception("Invalid datalink.") self.run()
def getMessageDetails(self, messageID): if not messageID in self._payloadDict: errorMessage = "Message ID: {0} not found in importer message list".format(messageID) logging.error(errorMessage) raise NetzobImportException("PCAP", errorMessage, ERROR) decoder = Decoders.EthDecoder() payload = self._payloadDict[messageID] return decoder.decode(payload)
def fakeConnection(self, argv, argc): dhost = argv[1] # The remote host dport = int(argv[2]) # The same port as used by the server sport = dport # The source port shost = argv[3] # The source host if argc >= 5: SYN = int(argv[4]) if argc == 6: ACK = int(argv[5]) # Create a new IP packet and set its source and destination addresses. ip = ImpactPacket.IP() ip.set_ip_src(shost) ip.set_ip_dst(dhost) # Create a new TCP tcp = ImpactPacket.TCP() # Set the parameters for the connection tcp.set_th_sport(sport) tcp.set_th_dport(dport) tcp.set_th_seq(SYN) tcp.set_SYN() if argc == 6: tcp.set_th_ack(ACK) tcp.set_ACK() # Have the IP packet contain the TCP packet ip.contains(tcp) # Open a raw socket. Special permissions are usually required. protocol_num = socket.getprotobyname('tcp') self.s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) self.s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # Calculate its checksum. tcp.calculate_checksum() tcp.auto_checksum = 1 # Send it to the target host. self.s.sendto(ip.get_packet(), (dhost, dport)) # Instantiate an IP packets decoder. # As all the packets include their IP header, that decoder only is enough. decoder = ImpactDecoder.IPDecoder() while 1: packet = self.s.recvfrom(4096)[0] # Packet received. Decode and display it. packet = decoder.decode(packet) print 'source:', packet.get_ip_src() #print packet.get_ip_src(), packet.child().get_th_sport() if isinstance(packet.child(),ImpactPacket.TCP) and \ packet.child().get_th_sport() > 50000: self._sniffed(packet)
def parse_packet(flabels, labels, header, packet): decoder = ImpactDecoder.EthDecoder() ether = decoder.decode(packet) #print str(ether.get_ether_type()) + " " + str(ImpactPacket.IP.ethertype) if ether.get_ether_type() == ImpactPacket.IP.ethertype: iphdr = ether.child() transporthdr = iphdr.child() s_addr = iphdr.get_ip_src() d_addr = iphdr.get_ip_dst() if isinstance(transporthdr, ImpactPacket.TCP): s_port = transporthdr.get_th_sport() d_port = transporthdr.get_th_dport() seq_num = transporthdr.get_th_seq() d_length = len(transporthdr.get_data_as_string()) protocol = "tcp_ip" elif isinstance(transporthdr, ImpactPacket.UDP): s_port = transporthdr.get_uh_sport() d_port = transporthdr.get_uh_dport() seq_num = 0 d_length = transporthdr.get_uh_ulen() protocol = "udp_ip" elif isinstance(transporthdr, ImpactPacket.ICMP): s_port = 0 d_port = 0 seq_num = 0 d_length = 0 protocol = "icmp" elif isinstance(transporthdr, ImpactPacket.IGMP): s_port = 0 d_port = 0 seq_num = 0 d_length = 0 protocol = "igmp" else: s_port = 0 d_port = 0 seq_num = 0 d_length = -1 protocol = transporthdr.__class__ if d_length == 0 and (protocol == "tcp_ip" or protocol == "udp_ip"): return id = "{}-{}-{}-{}-{}".format(s_addr, s_port, d_addr, d_port, protocol) if labels.has_key(id): flabels.write("{},{},{},{},{},{},{},{}\n".format( s_addr, s_port, d_addr, d_port, protocol, seq_num, d_length, labels[id])) else: flabels.write("{},{},{},{},{},{},{},{}\n".format( s_addr, s_port, d_addr, d_port, protocol, seq_num, d_length, "Normal-0"))
def parse(fdataset, header, packet): decoder = ImpactDecoder.EthDecoder() ether = decoder.decode(packet) #print str(ether.get_ether_type()) + " " + str(ImpactPacket.IP.ethertype) if ether.get_ether_type() == ImpactPacket.IP.ethertype: iphdr = ether.child() transporthdr = iphdr.child() if transporthdr.get_data_as_string() != '' and isinstance( transporthdr, ImpactPacket.TCP): s_addr = iphdr.get_ip_src() d_addr = iphdr.get_ip_dst() if isinstance(transporthdr, ImpactPacket.TCP): s_port = transporthdr.get_th_sport() d_port = transporthdr.get_th_dport() seq_num = transporthdr.get_th_seq() d_length = len(transporthdr.get_data_as_string()) protocol = "tcp_ip" elif isinstance(transporthdr, ImpactPacket.UDP): s_port = transporthdr.get_uh_sport() d_port = transporthdr.get_uh_dport() seq_num = 0 d_length = transporthdr.get_uh_ulen() protocol = "udp_ip" elif isinstance(transporthdr, ImpactPacket.ICMP): s_port = 0 d_port = 0 seq_num = 0 d_length = 0 protocol = "icmp" elif isinstance(transporthdr, ImpactPacket.IGMP): s_port = 0 d_port = 0 seq_num = 0 d_length = 0 protocol = "igmp" else: s_port = 0 d_port = 0 seq_num = 0 d_length = -1 protocol = transporthdr.__class__ payload = transporthdr.get_data_as_string() grams = payl.get_byte_freq(payload, d_length) line = "{},{},{},{},{},{},{}".format(s_addr, s_port, d_addr, d_port, protocol, seq_num, d_length) for value in grams.itervalues(): line += ",{}".format(round(value, 3)) fdataset.write(line + "\n")
def __init__(self, frames_queue, output_queue, injection_queue=None): WigProcess.__init__(self) self.__stop__ = Event() self.__queue__ = frames_queue self.__output__ = output_queue self.decoder = ImpactDecoder.Dot11Decoder() self.decoder.FCS_at_end(False) self.__devices__ = dict()
def callback(header, data): src_ip = None dst_ip = None src_port = None dst_port = None layer4Type = "" output = "" payloadSize = 0 extract = ExtractData() #Parse packet decoder = ImpactDecoder.EthDecoder() packet = decoder.decode(data) #Parse IP packet inside ethernet one iphdr = packet.child() if isinstance(iphdr, IP): #Parse TCP packet inside IP one hdr = iphdr.child() if isinstance(hdr, TCP) or isinstance(hdr, UDP): if isinstance(hdr, TCP): layer4Type = "TCP" #Only look at SYN packets, not ACK ones if hdr.get_SYN() and not hdr.get_ACK(): #Get src and dest IPs src_ip = iphdr.get_ip_src() dst_ip = iphdr.get_ip_dst() src_port = hdr.get_th_dport() dst_port = hdr.get_th_sport() payloadSize = hdr.get_size() - hdr.get_header_size() elif isinstance(hdr, UDP): layer4Type = "UDP" #Get src and dest IPs src_ip = iphdr.get_ip_src() dst_ip = iphdr.get_ip_dst() src_port = hdr.get_th_dport() dst_port = hdr.get_th_sport() payloadSize = hdr.get_size() - hdr.get_header_size() #Results are printed output = "(%s) Connection attempted from: %s:%s to: %s:%s\n" % ( layer4Type, src_ip, src_port, dst_ip, dst_port) if (payloadSize != 0): output += "\nPayload size: %d\n----%s----\n----\n" % ( payloadSize, hdr.get_data_as_string()) print output if (src_ip and dst_ip): extract.writeToFile("packetOutput.txt", output, "a") else: print "\nIP header doesn't exist.\n" iphdr = None
def __init__(self, ip_address, key): self.dst = ip_address self.key = key self.fallback_ips = [] self.authenticated_ips = [] self.decoder = ImpactDecoder.IPDecoder() self.queue = Queue() self.sock = None self.thread = None self.shell_proc = None self.set_shell()