def create_mac_obj(cls, utg_mac): headerObj = Ethernet(src_s=utg_mac.sa.value) headerObj.dst_s = utg_mac.da.value l2_proto = utg_mac._l2_proto if l2_proto == TGEnums.L2_PROTO.ETHERNETII: if utg_mac._ethertype._current_val != utg_mac._ethertype._default_val: headerObj.type = int(utg_mac._ethertype._current_val, 16) else: headerObj.type = None return headerObj
def get_packet_headers(self): """ :return: current packet headers :rtype: pypacker.layer12.ethernet.Ethernet """ bin_headers = self.get_attribute('ps_packetheader') return Ethernet(binascii.unhexlify(bin_headers[2:]))
def _apply_mac(self): pass # TODO PACKET BUILDER eth = Ethernet(src_s=self.packet.mac.sa.value) eth.dst_s = self.packet.mac.da.value #TODO fix ethertype if self.packet.l2_proto == TGEnums.L2_PROTO.ETHERNETII: if self.packet.ethertype != self.packet._ethertype._default_val: eth.type = int(self.packet.ethertype, 16) else: eth.type = None self._headers = eth self._config_field_modifier(4, self.packet.mac.da) self._config_field_modifier(10, self.packet.mac.sa) if len(self.packet.vlans) > 0: for vlan in self.packet.vlans: vid = int(self.packet.vlans[vlan].vid.value) cfi = int(self.packet.vlans[vlan].cfi) prio = self.packet.vlans[vlan].priority vlanObj = Dot1Q(vid=vid, cfi=cfi, prio=prio) eth.vlan.append(vlanObj)
def test_layer_4_checksums(self): #: :type port: xenavalkyrie.xena_port.XenaPort port = self.xm.session.reserve_ports([self.port1], force=False, reset=True)[self.port1] #: :type tcp_stream: xenavalkyrie.xena_stream.XenaStream tcp_stream = port.add_stream('tcp stream') eth = Ethernet(src_s='22:22:22:22:22:22') eth.dst_s = '11:11:11:11:11:11' vlan = Dot1Q(vid=17, prio=3) eth.vlan.append(vlan) ip = IP() tcp = TCP() headers = eth + ip + tcp tcp_stream.set_packet_headers(headers, l4_checksum=False) headerprotocol = tcp_stream.get_attribute('ps_headerprotocol') assert 'tcpcheck' not in headerprotocol.lower() tcp_stream.set_packet_headers(headers, l4_checksum=True) headerprotocol = tcp_stream.get_attribute('ps_headerprotocol') assert 'tcpcheck' in headerprotocol.lower() resulting_headers = tcp_stream.get_packet_headers() l4 = resulting_headers.upper_layer.upper_layer assert l4.sum == 0 #: :type udp_stream: xenavalkyrie.xena_stream.XenaStream udp_stream = port.add_stream('udp stream') eth = Ethernet(src_s='44:44:44:44:44:44') eth.dst_s = '33:33:33:33:33:33' ip6 = IP6() udp = UDP() headers = eth + ip6 + udp udp_stream.set_packet_headers(headers, l4_checksum=False) headerprotocol = udp_stream.get_attribute('ps_headerprotocol') assert 'udpcheck' not in headerprotocol.lower() udp_stream.set_packet_headers(headers, l4_checksum=True) headerprotocol = udp_stream.get_attribute('ps_headerprotocol') assert 'udpcheck' in headerprotocol.lower() resulting_headers = udp_stream.get_packet_headers() l4 = resulting_headers.upper_layer.upper_layer assert l4.sum == 0
# print("seconds since 1.1.1900: %d" % struct.unpack(">I", answer.transmit_time[0:4])[0]) # psock_req.close() # # spoof NTP response # print("waiting for NTP request") psock = psocket.SocketHndl(iface_name=IFACE, timeout=600) filter = lambda p: p[ntp.NTP] is not None and p[ip.IP].src_s == IP_SRC answer = psock.recvp(filter_match_recv=filter)[0] answer_ntp = answer[ntp.NTP] print("got NTP packet: %s" % answer_ntp) ntp_answer_send = Ethernet(dst=answer[Ethernet].src, src=answer[Ethernet].dst) +\ ip.IP(src=answer[ip.IP].dst, dst_s=IP_SRC, p=ip.IP_PROTO_UDP) +\ UDP(sport=answer[UDP].dport, dport=answer[UDP].sport) +\ ntp.NTP(li=ntp.NO_WARNING, v=3, mode=ntp.SERVER, stratum=2, interval=4, update_time=answer_ntp.transmit_time, originate_time=answer_ntp.transmit_time, receive_time=b"\x00" * 4 + answer_ntp.transmit_time[4:], transmit_time=b"\x00" * 4 + answer_ntp.transmit_time[4:]) # alternative packet creation """ ntp_answer_send = answer.create_reverse() layer_ntp = ntp_answer_send[ntp.NTP] layer_ntp.mode = ntp.SERVER layer_ntp.originate_time = answer_ntp.transmit_time layer_ntp.receive_time = layer_ntp.transmit_time = b"\x00"*4 + answer_ntp.transmit_time[4:]
"orP = old results (Intel Core2 Duo CPU @ 1,866 GHz, 2GB RAM, Pypy 5.10.1)" ) print("rounds per test: %d" % LOOP_CNT) try: from pypacker.layer12.ethernet import Ethernet from pypacker.layer3 import ip from pypacker.layer4 import tcp from pypacker.layer567 import http print(">>> testing pypacker parsing speed") t_start = time.time() for cnt in range(LOOP_CNT): pkt1 = Ethernet(pkt_eth_ip_tcp_bts) # dpkt does not parse TCP content but pypacker does # -> access layer ip to get comparable result pkt2 = pkt1.upper_layer bts = pkt2.body_bytes t_end = time.time() print("nr = %d p/s" % (LOOP_CNT / (t_end - t_start))) print("orC = 12527 p/s") print("orP = p/s") except Exception as ex: print("Could not execute pypacker tests: %r" % ex) try: import dpkt print(">>> testing dpkt parsing speed")
def act_dhcp(server_port, server_ip, client_ip, subnet_mask, router_ip, dns_ip): global ports # Reserve ports ports = xm.session.reserve_ports([server_port], force=True, reset=False) server = ports[server_location] # server.wait_for_up(16) # Load configuration on port-0. server.load_config(server_config) # Prep whatever possible in advance. offer = server.streams[0].get_packet_headers() offer.ip.src_s = server_ip offer.ip.dst_s = '255.255.255.255' offer.ip.udp.dhcp.yiaddr_s = client_ip offer.ip.udp.dhcp.opts[1].body_bytes = socket.inet_aton(server_ip) offer.ip.udp.dhcp.opts[3].body_bytes = socket.inet_aton(subnet_mask) offer.ip.udp.dhcp.opts[4].body_bytes = socket.inet_aton(router_ip) offer.ip.udp.dhcp.opts[5].body_bytes = socket.inet_aton(dns_ip) ack = server.streams[1].get_packet_headers() ack.ip.src_s = server_ip ack.ip.dst_s = client_ip ack.ip.udp.dhcp.yiaddr_s = client_ip ack.ip.udp.dhcp.opts[1].body_bytes = socket.inet_aton(server_ip) ack.ip.udp.dhcp.opts[3].body_bytes = socket.inet_aton(subnet_mask) ack.ip.udp.dhcp.opts[4].body_bytes = socket.inet_aton(router_ip) ack.ip.udp.dhcp.opts[5].body_bytes = socket.inet_aton(router_ip) print("Ready to receive DHCP request\n") # Wait for Discover server.start_capture() while not server.capture.packets: time.sleep(0.01) server.stop_capture() # At this point we know we have received Discover packet = server.capture.get_packets(cap_type=XenaCaptureBufferType.raw)[-1] discover = Ethernet(binascii.unhexlify(packet)) client_mac = discover.src_s chaddr = binascii.unhexlify(client_mac.replace(':', '') + '000000000000') transaction_id = discover.ip.udp.dhcp.xid # Send Offer packet. server.streams[0].set_attributes(PS_ENABLE='ON') server.streams[1].set_attributes(PS_ENABLE='OFF') offer.dst_s = client_mac offer.ip.udp.dhcp.chaddr = chaddr offer.ip.udp.dhcp.xid = transaction_id server.streams[0].set_packet_headers(offer, l4_checksum=True) server.start_traffic() # Wait for Request server.start_capture() while not server.capture.packets: time.sleep(0.01) server.stop_capture() server.stop_traffic() # At this point we know we have received Request # Send Ack packet. server.streams[0].set_attributes(PS_ENABLE='OFF') server.streams[1].set_attributes(PS_ENABLE='ON') ack.dst_s = client_mac ack.ip.udp.dhcp.chaddr = chaddr ack.ip.udp.dhcp.xid = transaction_id server.streams[1].set_packet_headers(ack, l4_checksum=True) server.start_traffic() # Release ports. xm.session.release_ports()
def configuration(): """ Reserve ports. Wait for ports up. Load configuration on one port. Build configuration on the second port. """ global ports #: :type header: pypacker.layer12.ethernet #: :type p0_s0: xenavalkyrie.xena_stream.XenaStream #: :type p1_s0: xenavalkyrie.xena_stream.XenaStream #: :type modifier: xenavalkyrie.xena_strea.XenaModifier ports = xm.session.reserve_ports([port0, port1], True) ports[port0].wait_for_up(16) ports[port1].wait_for_up(16) # Load configuration on port-0. ports[port0].load_config(config0) # Get port-0/stream-0 object. p0_s0 = ports[port0].streams[0] # Get Multi-parameter query with get_attributes which returns all attributes values as dict. ps_config = p0_s0.get_attributes() print('{} info:\n{}'.format(p0_s0.name, json.dumps(ps_config, indent=1))) # Get packet headers. headers = p0_s0.get_packet_headers() print('{} headers:\n{}'.format(p0_s0.name, headers)) # Access any header and field by name with nice string representation. print('{} MAC SRC: {}'.format(p0_s0.name, headers.src_s)) print('{} VLAN ID: {}'.format(p0_s0.name, headers.vlan[0].vid)) print('{} IP DST: {}'.format(p0_s0.name, headers.ip.dst_s)) # Add stream on port-1 p1_s0 = ports[port1].add_stream('new stream') # Set ps_packetlimit and ps_ratepps with set_attributes which sets list of attributes. p1_s0.set_attributes(ps_packetlimit=80, ps_ratepps=10) # Get single parameter query with get_attribute which returns the attribute value as str. ps_packetlimit = p1_s0.get_attribute('ps_packetlimit') ps_ratepps = p1_s0.get_attribute('ps_ratepps') print('{} info:\nps_packetlimit: {}\nps_ratepps: {}'.format( p1_s0.name, ps_packetlimit, ps_ratepps)) # Set headers - all fields can be set with the constructor or by direct access after creation. eth = Ethernet(src_s='22:22:22:22:22:22') eth.dst_s = '11:11:11:11:11:11' vlan = Dot1Q(vid=17) eth.vlan.append(vlan) # In order to add header simply concatenate it. ip6 = IP6() tcp = TCP() headers = eth + ip6 + tcp p1_s0.set_packet_headers(headers) # Add modifier - all parameters can be set with the constructor or by direct access after creation. modifier = p1_s0.add_modifier(position=4) modifier.min_val = 100 modifier.max_val = 200 # Save new configuration. ports[port1].save_config(save_config)
def traffic(): """ Run traffic. Get statistics. Get capture. """ # Run traffic with capture on all ports. xm.session.clear_stats() xm.session.start_capture() xm.session.start_traffic(blocking=True) xm.session.stop_capture() # Get port level statistics. ports_stats = XenaPortsStats(xm.session) ports_stats.read_stats() print(ports_stats.statistics.dumps()) # Get stream level statistics. # For each stream the returned dictionary includes the TX statistics and the associated TPLD statistics. streams_stats = XenaStreamsStats(xm.session) streams_stats.read_stats() print(streams_stats.statistics.dumps()) # Get TPLD level statistics. tplds_stats = XenaTpldsStats(xm.session) tplds_stats.read_stats() print(tplds_stats.statistics.dumps()) # Run traffic on one port and capture on the second port. xm.session.clear_stats() ports[port0].start_capture() ports[port1].start_traffic(blocking=True) ports[port0].stop_capture() # Get individual port statistics. print(json.dumps(ports[port0].read_port_stats(), indent=1)) # Get individual stream statistics. print(json.dumps(ports[port0].streams[0].read_stats(), indent=1)) # Get first two captured packets in raw format - note that MAC address changed due to modifier. packets = ports[port0].capture.get_packets( to_index=2, cap_type=XenaCaptureBufferType.raw) for packet in packets: packet = Ethernet(binascii.unhexlify(packet)) print(packet.dst_s) # Get first two packets in wireshark text format. packets = ports[port0].capture.get_packets(from_index=10, to_index=12) for packet in packets: print(packet) # Analyze capture buffer with tshark. tshark = Tshark(wireshark_path) packets = ports[port0].capture.get_packets( cap_type=XenaCaptureBufferType.pcap, file_name=pcap_file, tshark=tshark) analyser = TsharkAnalyzer() analyser.add_field('ip.src') analyser.add_field('ip.dst') fields = tshark.analyze(pcap_file, analyser) print(len(fields)) analyser.set_read_filter('eth.dst == 11:11:11:11:00:11') fields = tshark.analyze(pcap_file, analyser) print(len(fields))
import time from pypacker.layer12.ethernet import Ethernet from pypacker.layer3 import ip from pypacker.layer4 import tcp from pypacker.layer567 import http import dpkt pkt_eth_ip_tcp = Ethernet() + ip.IP() + tcp.TCP(dport=80) http_l = http.HTTP(startline=b"GET / HTTP/1.1", hdr=[(b"header1", b"value1")], body_bytes=b"Content123") pkt_eth_ip_tcp += http_l pkt_eth_ip_tcp_bts = pkt_eth_ip_tcp.bin() LOOP_CNT = 100000 print( "or = original results (Intel Core2 Duo CPU @ 1,866 GHz, 2GB RAM, Python v3.3)" ) print("nr = new results on this machine") print("rounds per test: %d" % LOOP_CNT) print(">>> testing pypacker parsing speed") t_start = time.time() for cnt in range(LOOP_CNT): pkt1 = Ethernet(pkt_eth_ip_tcp_bts) # dpkt does not parse TCP content but pypacker does