def testAll(dut): """ test with eth+IPv4+TCP+Payload""" fork(Clock(dut.clk, 6.4, 'ns').start()) dut._log.info("Running test") dut.reset_n <= 0 dut.ethBus <= 0 dut.IPv4Bus <= 0 dut.payload_in_data <= 0 dut.tcpBus <= 0 yield ClockCycles(dut.clk, 10) dut.reset_n <= 1 dut._log.info("end Rst") dut.ethBus <= int.from_bytes( raw( Ether(src="aa:aa:aa:aa:aa:aa", dst='11:11:11:11:11:11', type="IPv4")), 'little') dut.IPv4Bus <= int.from_bytes( raw(IP(src="192.168.1.1", dst="192.168.1.2")), 'little') dut.tcpBus <= int.from_bytes(raw(TCP(sport=80, dport=12000)), 'little') dut.payload_in_data <= int(0xDEADBEEFDEADBEEF) yield ClockCycles(dut.clk, 15) yield ClockCycles(dut.clk, 1) yield ClockCycles(dut.clk, 15) dut._log.info("end Test")
def check_tcpsyn(args, packet): dst_ip = args.to[0] ip = packet.getlayer(sp.IP) if not ip: return False if ip.dst != dst_ip: return False tcp = packet.getlayer(sp.TCP) if not tcp: return False # Verify IP checksum chksum = ip.chksum ip.chksum = None new_chksum = sp.IP(sp.raw(ip)).chksum if chksum != new_chksum: print("Expected IP checksum %x but found %x\n" % (new_cshkum, chksum)) return False # Verify TCP checksum chksum = tcp.chksum packet_raw = sp.raw(packet) tcp.chksum = None newpacket = sp.Ether(sp.raw(packet[sp.Ether])) new_chksum = newpacket[sp.TCP].chksum if chksum != new_chksum: print("Expected TCP checksum %x but found %x\n" % (new_chksum, chksum)) return False return True
def run(self): while True: self.enter_loop.wait() self.enter_loop.clear() if self.stopped: return p, remote = self.socket.recvfrom(1500) p = DNS(raw(p)) # check received packet for correctness assert (p is not None) assert (p[DNS].qr == 0) assert (p[DNS].opcode == 0) # has two queries assert (p[DNS].qdcount == TEST_QDCOUNT) qdcount = p[DNS].qdcount # both for TEST_NAME assert (p[DNS].qd[0].qname == TEST_NAME.encode("utf-8") + b".") assert (p[DNS].qd[1].qname == TEST_NAME.encode("utf-8") + b".") assert (any(p[DNS].qd[i].qtype == DNS_RR_TYPE_A for i in range(qdcount))) # one is A assert (any(p[DNS].qd[i].qtype == DNS_RR_TYPE_AAAA for i in range(qdcount))) # one is AAAA if self.reply is not None: self.socket.sendto(raw(self.reply), remote) self.reply = None
def main(pcap0, pcap1): cap0 = pkts(pcap0) cap1 = pkts(pcap1) d = dict() for idx, pkt in enumerate(cap0): hval = md5(raw(pkt)).hexdigest() d[hval] = idx damaged_pkts = 0 for _, pkt in enumerate(cap1): hval = md5(raw(pkt)).hexdigest() if hval in d: d[hval] = -1 else: damaged_pkts += 1 # Filter out indices of lost or damaged packets idx_of_lost_or_damaged_pkts = list(filter(lambda x: x >= 0, d.values())) total_sent_pkts = len(cap0) total_recv_pkts = len(cap1) total_recv_pkts_no_damaged = total_recv_pkts - damaged_pkts assert (total_recv_pkts_no_damaged == (total_sent_pkts - len(idx_of_lost_or_damaged_pkts))) rate_damaged_pkts = damaged_pkts / total_sent_pkts rate_lost_pkts = (total_sent_pkts - total_recv_pkts) / total_sent_pkts #print("Rate of damaged packets: {}".format(round(rate_damaged_pkts, 2))) #print("Rate of lost packets: {}".format(round(rate_lost_pkts, 2))) plot(range(1, total_sent_pkts + 1), idx_of_lost_or_damaged_pkts, rate_damaged_pkts, rate_lost_pkts)
def run(self): while True: pkt, info = self.recv_pkt() self._print(pkt, info[1], RECV_MODE) if pkt.fin_flag == 1 and all( i == 0 for i in (pkt.ack_flag, pkt.nak_flag, pkt.dat_flag, pkt.get_flag)): cli_fin_ack = RUSH(seq_num=self._seq_num, ack_num=pkt.seq_num, fin_flag=1, ack_flag=1) self._socket.sendto(raw(cli_fin_ack), self._serv_info) self._seq_num += 1 self._print(cli_fin_ack, self._serv_info[1], SEND_MODE) while True: serv_fin_ack, info = self.recv_pkt() self._print(serv_fin_ack, info[1], RECV_MODE) if serv_fin_ack.fin_flag == 1 and serv_fin_ack.ack_flag == 1 and \ all(i == 0 for i in (serv_fin_ack.nak_flag, serv_fin_ack.dat_flag, serv_fin_ack.get_flag)): return # end of connection elif pkt.dat_flag == 1: ack = RUSH(seq_num=self._seq_num, ack_num=pkt.seq_num, dat_flag=1, ack_flag=1) self._socket.sendto(raw(ack), self._serv_info) self._seq_num += 1 self._print(ack, self._serv_info[1], SEND_MODE)
def __init__(self, pkt): if isinstance(pkt, packet.Packet): assert len(pkt) >= 0x20 self.ndps = [] self.dgs = [] s = MBIMStream(raw(pkt)) self.usb_urb = s.pop_raw(0x20) if len(s) < 0x1e: # no payload return assert s.pop_str_len(4) == "NCMH" self.header_len = s.pop_uint16() self.seq = s.pop_uint16() assert s.pop_uint16() == len(pkt) - len( self.usb_urb ) # if this fails, it probably means we had multiple datagram pointers in this packet self.ndp_idx = s.pop_uint16() # ^^^ Header, vvv pointer assert s.pop_str_len(4) == "NCM0" self.ndp_len = s.pop_uint16() self.ndp_next_idx = s.pop_uint16() max_ndps = (self.ndp_len - 8) // 4 # ^^^ using // because we want to truncate for i in range(max_ndps): dg_idx = s.pop_uint16() dg_len = s.pop_uint16() if dg_idx == 0 and dg_len == 0: break self.ndps.append((dg_idx, dg_len)) self.dgs.append( Ether(raw(pkt)[0x20 + dg_idx:0x20 + dg_idx + dg_len])) else: print("MBIM construction is not yet implemented.")
def test_scapy_sniffer(self): send_data = [ Ether(src="99:54:8f:91:12:f6", dst="44:35:a2:a6:d0:bd") / IPv6(src="fe80::1", dst="fe80::2") / ICMPv6EchoRequest(), Ether(src="44:35:a2:a6:d0:bd", dst="99:54:8f:91:12:f6") / IPv6(src="fe80::2", dst="fe80::1") / ICMPv6EchoReply(), Ether(src="1f:db:ed:9c:26:6e", dst="18:39:3c:e8:1f:ad") / IPv6(src="2001:db8:8a5a:4020:f160:162:c83d:527d", dst="2001:db8:2932:29c9:35eb:9377:ae68:634d") / UDP(sport=31245, dport=8788) / b"abcdef", Ether(src="18:39:3c:e8:1f:ad", dst="1f:db:ed:9c:26:6e") / IPv6(src="2001:db8:2932:29c9:35eb:9377:ae68:634d", dst="2001:db8:8a5a:4020:f160:162:c83d:527d") / UDP(sport=8788, dport=31245) / b"12345", ] sniffer = AsyncSniffer() sniffer.start() self.spawn.expect(r"Initializing L2listen with arguments") self.spawn.expect(r"Bound socket to '(.*)'\s") remote = self.spawn.match.group(1) # wait a bit to avoid race where socket is not bound yet time.sleep(.5) for packet in send_data: time.sleep(.001) # some spacing for test stability self.assertEqual(len(raw(packet)), self.comm_sock.sendto(raw(packet), remote)) for packet in send_data: self.spawn.expect(r"Receiving on L2listen with arguments") results = sniffer.stop() self.assertIsNotNone(results) self.assertEqual(len(send_data), len(results)) for pkt in send_data: self.assertIn(Ether(raw(pkt)), results)
def run(self): while True: self.enter_loop.wait() self.enter_loop.clear() if self.stopped: return p, remote = self.socket.recvfrom(1500) p = DNS(raw(p)) # check received packet for correctness assert(p is not None) assert(p[DNS].qr == 0) assert(p[DNS].opcode == 0) # has two queries assert(p[DNS].qdcount == TEST_QDCOUNT) qdcount = p[DNS].qdcount # both for TEST_NAME assert(p[DNS].qd[0].qname == TEST_NAME.encode("utf-8") + b".") assert(p[DNS].qd[1].qname == TEST_NAME.encode("utf-8") + b".") assert(any(p[DNS].qd[i].qtype == DNS_RR_TYPE_A for i in range(qdcount))) # one is A assert(any(p[DNS].qd[i].qtype == DNS_RR_TYPE_AAAA for i in range(qdcount))) # one is AAAA if self.reply is not None: self.socket.sendto(raw(self.reply), remote) self.reply = None
def _do_device(self, msg): # We do not receive REQUEST from host if type is not CTRL if msg.ep.eptype != USBDefs.EP.TransferType.CTRL: req = req_from_msg(msg) self._pcap.write(raw(req)) # Convert and write pcap_pkt = usbdev_to_usbpcap(msg) self._pcap.write(raw(pcap_pkt))
def _do_host(self, msg): # Convert and write pcap_pkt = usbhost_to_usbpcap(msg) self._pcap.write(raw(pcap_pkt)) # We do not receive ACK from device for OUT data if msg.ep.epdir == msg.URBEPDirection.URB_OUT: ack = ack_from_msg(msg) self._pcap.write(raw(ack))
def set_PHV(self, pkt, payload=None): """ set PHV for deparser """ scap_to_PHV(self.dut, pkt, self.name_to_VHDL) full_hdr = scapy_to_BinaryValue(pkt) print("emitted {} bytes : \n {}".format(len(raw(pkt)), raw(pkt))) self.dut._log.info("send {}B : {}".format(len(full_hdr.buff), full_hdr.binstr)) new_output = PHVDeparser(len(self.dut.packet_out_tdata), full_hdr) self.expected_output.extend(new_output)
def test_broadcast_modify_hrm(msg, device_type): pkt = ANTMessage(msg, device_type=device_type) pkt.show() assert pkt._calc_checksum() == pkt.checksum pkt[HRMPayload].heart_rate = 0xFF assert raw(pkt) != msg new_pkt = ANTMessage(raw(pkt), device_type=device_type) assert new_pkt.checksum == new_pkt._calc_checksum()
def traffic_gen(mac: str, enabled: Callable) -> None: with configure_eth_if() as so: payload = bytes.fromhex('ff') # DUMMY_TRAFFIC code payload += bytes(1485) eth_frame = Ether(dst=mac, src=so.getsockname()[4], type=0x2222) / raw(payload) try: while enabled() == 1: so.send(raw(eth_frame)) except Exception as e: raise e
def traffic_gen(mac: str, pipe_rcv: connection.Connection) -> None: with configure_eth_if() as so: payload = bytes.fromhex('ff') # DUMMY_TRAFFIC code payload += bytes(1485) eth_frame = Ether(dst=mac, src=so.getsockname()[4], type=0x2222) / raw(payload) try: while pipe_rcv.poll() is not True: so.send(raw(eth_frame)) except Exception as e: raise e
def send_eth_packet(mac: str) -> None: with configure_eth_if() as so: so.settimeout(10) payload = bytearray(1010) for i, _ in enumerate(payload): payload[i] = i & 0xff eth_frame = Ether(dst=mac, src=so.getsockname()[4], type=0x2222) / raw(payload) try: so.send(raw(eth_frame)) except Exception as e: raise e
def handle_req(data): req = DNS(data) print(raw(req)) req.show() print(req.qd.qname) log.write(req.qd.qname + b'\n') log.flush() resp = DNS(id=req.id,qd=req.qd,an=DNSRR(rrname=req.qd.qname, type='CNAME', ttl=64, rdata=payload)) resp.show() return raw(resp)
def handle_pkt(pkt): if (pkt[IP].tos >> 2) == 0x17: int_pkt = None if UDP in pkt: int_pkt = INT_shim(raw(pkt[UDP].payload)) elif TCP in pkt: int_pkt = INT_shim(raw(pkt[TCP].payload)) int_pkt.show() int_words = memoryview(int_pkt.load[:int_pkt[INT_shim].len]).cast("I") for i, word in enumerate(int_words): if i % int_pkt[INT].hop_ml: print("=== HOP ===") print('{:#034b}'.format(word))
def _send(self, pkt, additional, sock, target_info=None, print_out=False, extend_message=""): time.sleep(0.2) try: message = raw(pkt) if additional is not None: message += raw(additional) if target_info is None: sock.sendall(message) else: sock.sendto(message, target_info) if print_out: self._print(pkt, additional, f"{extend_message}Sent: ") except: traceback.print_exc(file=sys.stderr) assert False, f"Error while sending a message to a socket."
def send_and_exp_any_dhcp6(cls, send_pkt, client=True, ipv6_src=None): sniffer = AsyncSniffer(iface=cls.tap) sniffer.start() time.sleep(cls.pre_sniffer_wait) cls._sendp(send_pkt, client=client, ipv6_src=ipv6_src) time.sleep(cls.post_sniffer_wait) return [ pkt for pkt in sniffer.stop() if cls._contains_dhcp(pkt) and # filter out sent packet (UDP not in pkt or raw(pkt[UDP].payload) != raw(send_pkt)) and # filter out ICMPv6 since error notifications can also contain # the sent packets and we are not interested in error # notifications ICMPv6DestUnreach not in pkt ]
def packet_handler(packet): global memberDataLatest print(memberDataLatest) raw_pkt = scp.raw(packet) enableFlag = False if(b'Peer1' in raw_pkt and 'Peer1' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer1") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer1" if(b'Peer2' in raw_pkt and 'Peer2' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer2") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer2" if(b'Peer3' in raw_pkt and 'Peer3' in acceptedMembers): enableFlag = True idx = raw_pkt.index("Peer3") data = str(raw_pkt[idx+5:]).strip().split(',') msg2 = raw_pkt[idx:].strip() name = "Peer3" if ((b'Peer1' in raw_pkt) or (b'Peer2' in raw_pkt) or (b'Peer3' in raw_pkt)) and enableFlag: mData = data if int(mData[0]) > memberDataLatest[name]: memberDataLatest[name] = int(mData[0]) mData[-1] = str(time.time()) memberData[name].append(mData) for member in members: pkt = scp.IP(dst=members[member])/scp.ICMP()/scp.Raw(load=msg2) scp.send(pkt) if len(memberData[name]) > bufferSize: memberData[name].pop(0)
def test_send_ack_instead_of_syn(child, src_if, src_ll, dst_if, dst_l2, dst_ll, dst_port): # check if any debug output is generated during `@testfunc` decorator # execution. If so, send fewer packets to prevent the target node # from being overwhelmed by packets and output. debug = child.expect( [pexpect.TIMEOUT, r'GNRC_TCP: Enter "\S+", File: .+\(\d+\)\s'], timeout=1) if debug: count = 10 else: count = 1000 # see https://github.com/RIOT-OS/RIOT/pull/12001 provided_data = base64.b64decode("rwsQf2pekYLaU+exUBBwgPDKAAA=") tcp_hdr = TCP(provided_data) assert provided_data == raw(tcp_hdr) # set destination port to application specific port tcp_hdr.dport = dst_port sendp(Ether(dst=dst_l2) / IPv6(src=src_ll, dst=dst_ll) / tcp_hdr, iface=src_if, verbose=0, count=count) # check if server actually still works with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock: sock.settimeout(child.timeout) addr_info = socket.getaddrinfo(dst_ll + '%' + src_if, dst_port, type=socket.SOCK_STREAM) sock.connect(addr_info[0][-1]) child.expect_exact('gnrc_tcp_open_passive: returns 0') verify_pktbuf_empty(child)
def ping6(send_if, dst_ip, args): ether = sp.Ether() ip6 = sp.IPv6(dst=dst_ip) icmp = sp.ICMPv6EchoRequest(data=sp.raw(PAYLOAD_MAGIC)) req = ether / ip6 / icmp sp.sendp(req, iface=send_if, verbose=False)
def main(argv): if len(argv) >1: print("Usage: python3 server.py [verbosity]") return my_port = free_port() print("[port] <client> <server> :",free_port(),my_port) debug_level = 1 if len(argv) > 2: if argv[1] in ("0", "1", "2"): debug_level = int(argv[1]) # conn = Connection(LOCALHOST, my_port, debug_level) # if not conn.connect(): # return try: # clientResp, clientInfo= conn.recv_pkt() # Fix up the response # print("Raw:",raw(clientResp)) # responseList = str(clientResp).strip().split(' ') # print("AS LIST\r\n::",responseList) # print("ENCODE\r\n::",*responseList) # print("REPR\r\n::",repr(*responseList)) ack = RUSH(seq_num=2, ack_num=1, dat_flag=1, ack_flag=1) print(raw(ack)) print(repr(ack)) # conn.run() except AssertionError as e: print(e.args[0])
def main(): definitions, benchmarks = [], [] for protocol, packets in BENCHMARKS: for direction, packet, layernames in packets: for layername in layernames: layer = LAYERS[layername] length = len(raw(packet[layer])) enc_name = mktestname(protocol, direction, layername, "encode", length) dec_name = mktestname(protocol, direction, layername, "decode", length) enc_inputname, dec_inputname = enc_name + "_input", dec_name + "_input" definitions.append( mkletdef_bytestring(dec_inputname, packet[layer])) definitions.append( mkletdef_packet(enc_inputname, dec_inputname, packet, layer)) benchmarks.append( mkbench(enc_name, enc_inputname, "encode", packet, layer)) benchmarks.append( mkbench(dec_name, dec_inputname, "decode", packet, layer)) with open("microbenchmarks.ml", mode="w") as f: f.write( MAIN_TEMPLATE.format(SZ, "\n\n".join(definitions), ";\n".join(benchmarks)))
def preprocessing(self, packet): import numpy as np import scapy.all as sp packet.getlayer(0).dst = '0' packet.getlayer(0).src = '0' if packet.getlayer(1) is not None: if packet.getlayer(1).name == 'IPv6': packet.getlayer(1).src = "0000::0000:0000:0000:0000" packet.getlayer(1).dst = '0000::00' else: packet.getlayer(1).src = "0" packet.getlayer(1).dst = '0' if packet.getlayer(2) is not None: packet.getlayer(2).sport = 0 packet.getlayer(2).dport = 0 hex_bytes = sp.raw(packet) if len(hex_bytes) >= 52: num_list = [int(n) for n in hex_bytes][:40 + 12] else: missing = 52 - len(hex_bytes) padding = [0] * missing num_list = [int(n) for n in hex_bytes] + padding num_list = np.asarray(num_list).astype(int).reshape(-1) return num_list return None
def main(argv): if (len(argv) != 7): print( "Invalid args!\npgen.py [tcp/udp/other] [source ip] [source port] [dest ip] [dest port] [out file name]" ) exit(-1) protocol = argv[1].lower() sourceAddr = argv[2] sourcePort = int(argv[3]) destAddr = argv[4] destPort = int(argv[5]) outFileName = argv[6] if (protocol == "tcp"): pkt = IP(dst=destAddr, src=sourceAddr) / TCP(dport=destPort, sport=sourcePort) elif (protocol == "udp"): pkt = IP(dst=destAddr, src=sourceAddr) / UDP(dport=destPort, sport=sourcePort) else: pkt = IP(dst=destAddr, src=sourceAddr) / ICMP( ) # this just exists to create failing test cases, ICMP is arbitrary outFile = open(outFileName, "wb") outFile.write(raw(pkt)) outFile.close() print("Packet created!")
def get_pck_features(p): feats = [0] * get_features_n() if TCP in p: ptcp = p[TCP] feats[1] = 1 #feats[2] = 1 if p.seq == 1 else 0 feats[3] = min(ptcp.sport, 1000) feats[4] = min(ptcp.dport, 1000) r_data = bytes(ptcp.payload) elif UDP in p: pudp = p[UDP] feats[1] = 2 feats[3] = min(pudp.sport, 1000) feats[4] = min(pudp.dport, 1000) r_data = bytes(pudp.payload) else: r_data = raw(p) feats[0] = len(r_data) if len(r_data) > 0: mc = Counter(r_data).most_common(2) feats[5] = mc[0][0] feats[6] = mc[0][1] / len(r_data) if len(mc) > 1: feats[7] = mc[1][0] feats[8] = mc[1][1] / len(r_data) return r_data, feats
def invalid_flags(self): """Invalid because the server should be expecting an ACK or a NAK, not a get""" pkt, info = self.recv_pkt() self._print(pkt, info[1], RECV_MODE) invalid = RUSH(seq_num=self._seq_num, ack_num=1, get_flag=1) self._socket.sendto(raw(invalid), self._serv_info) self._print(invalid, self._serv_info[1], SEND_MODE, note="[INVALID]")
def nak(self): pkt, info = self.recv_pkt() self._print(pkt, info[1], RECV_MODE) nak = RUSH(seq_num=self._seq_num, ack_num=1, dat_flag=1, nak_flag=1) self._socket.sendto(raw(nak), self._serv_info) self._print(nak, self._serv_info[1], SEND_MODE) self._seq_num += 1
def send_request(self, resource): pkt = RUSH(seq_num=self._seq_num, get_flag=1, data=str_to_int(resource)) self._socket.sendto(raw(pkt), self._serv_info) self._seq_num += 1 self._print(pkt, self._serv_info[1], SEND_MODE)
def test_gnrc_tcp_garbage_packets_short_header(child): """ This test verifies fix malformed tcp header. See https://github.com/RIOT-OS/RIOT/issues/12086 """ # Setup RIOT as server with RiotTcpServer(child, generate_port_number()) as riot_srv: # Construct HostTcpClient to lookup node properties host_cli = HostTcpClient(riot_srv) # Try to accept incoming connection from host system. child.sendline('gnrc_tcp_accept 2000') # Build malformed short header with SYN Flag tcp_hdr = TCP(dport=int(riot_srv.listen_port), flags="S", sport=2342, seq=1, dataofs=6) tcp_hdr = raw(tcp_hdr)[:-2] sendp(Ether(dst=riot_srv.mac) / IPv6(src=host_cli.address, dst=riot_srv.address) / tcp_hdr, iface=host_cli.interface, verbose=0) # Establish normal tcp connection from host system to check if RIOT node # was able to recover from malformed packet with host_cli: child.expect_exact('gnrc_tcp_accept: returns 0') riot_srv.close()
def callback(packet): try: p = Photon.from_bytes(raw(packet)) for command in p.command: if isinstance(command.data, Photon.ReliableFragment): fragment = command.data messages = decoder.add_fragment(fragment) if messages: handle_messages(messages) except EOFError: print('Unable to parse packet') except ValueError: print('Packet is probably malformed')
def main(): definitions, benchmarks = [], [] for protocol, packets in BENCHMARKS: for direction, packet, layernames in packets: for layername in layernames: layer = LAYERS[layername] length = len(raw(packet[layer])) enc_name = mktestname(protocol, direction, layername, "encode", length) dec_name = mktestname(protocol, direction, layername, "decode", length) enc_inputname, dec_inputname = enc_name + "_input", dec_name + "_input" definitions.append(mkletdef_bytestring(dec_inputname, packet[layer])) definitions.append(mkletdef_packet(enc_inputname, dec_inputname, packet, layer)) benchmarks.append(mkbench(enc_name, enc_inputname, "encode", packet, layer)) benchmarks.append(mkbench(dec_name, dec_inputname, "decode", packet, layer)) with open("microbenchmarks.ml", mode="w") as f: f.write(MAIN_TEMPLATE.format(SZ, "\n\n".join(definitions), ";\n".join(benchmarks)))
def mkletdef_bytestring(letname, subpacket): return LETDEF_BYTESTRING_TEMPLATE.format(letname, fmtarray(raw(subpacket)))