我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用scapy.all.Ether()。
def _send_to_target(self, data): ether = Ether(dst='ff:ff:ff:ff:ff:ff') ip = IP(src=self.host, dst='255.255.255.255') udp = UDP(sport=68, dport=self.port) payload = Raw(load=data) packet = str(ether / ip / udp / payload) self.logger.debug('Sending header+data to host: %s:%d' % (self.host, self.port)) self.socket.send(packet) self.logger.debug('Header+data sent to host')
def send_arp_reply(request): if request.haslayer(ARP): global _current_number_of_packets global _current_network_interface global _current_mac_address global _arp SOCK = socket(AF_PACKET, SOCK_RAW) SOCK.bind((_current_network_interface, 0)) if request[ARP].op == 1: if request[Ether].dst == "ff:ff:ff:ff:ff:ff" and request[ARP].hwdst == "00:00:00:00:00:00": print Base.c_info + "ARP request from MAC: " + request[ARP].hwsrc + " IP: " + request[ARP].pdst reply = _arp.make_response(ethernet_src_mac=_current_mac_address, ethernet_dst_mac=request[ARP].hwsrc, sender_mac=_current_mac_address, sender_ip=request[ARP].pdst, target_mac=request[ARP].hwsrc, target_ip=request[ARP].psrc) SOCK.send(reply) _current_number_of_packets += 1 if _current_number_of_packets >= _number_of_packets: SOCK.close() exit(0)
def cmd_dhcp_discover(iface, timeout, verbose): conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False hw = get_if_raw_hwaddr(conf.iface) ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68,dport=67) bootp = BOOTP(chaddr=hw) dhcp = DHCP(options=[("message-type","discover"),"end"]) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, multi=True, timeout=5) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.summary())
def callback(self, packet): flags = packet.sprintf("%TCP.flags%") proto = IP if IPv6 in packet: proto = IPv6 if flags == "A" and not self.ignore_packet(packet, proto): src_mac = packet[Ether].src dst_mac = packet[Ether].dst src_ip = packet[proto].src dst_ip = packet[proto].dst src_port = packet[TCP].sport dst_port = packet[TCP].dport seq = packet[TCP].seq ack = packet[TCP].ack if self.verbose: print("RST from %s:%s (%s) --> %s:%s (%s) w/ %s" % (src_ip, src_port, src_mac, dst_ip, dst_port, dst_mac, ack)) if self.noisy: self.send(self.build_packet(src_mac, dst_mac, src_ip, dst_ip, src_port, dst_port, seq, proto)) self.send(self.build_packet(dst_mac, src_mac, dst_ip, src_ip, dst_port, src_port, ack, proto))
def test_mtu_regular(exp_src_mac, exp_dst_mac, port_interface_mapping, a, create_str): fwd_pkt1 = Ether() / IP(dst='10.1.0.1') / TCP(sport=5793, dport=80) fwd_pkt2 = Ether() / IP(dst='10.1.0.34') / TCP(sport=5793, dport=80) fwd_pkt3 = Ether() / IP(dst='10.1.0.32') / TCP(sport=5793, dport=80) / Raw(create_str) exp_pkt1 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.1', ttl=fwd_pkt1[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt2 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.34', ttl=fwd_pkt2[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt3 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.32', ttl=fwd_pkt3[IP].ttl-1) / TCP(sport=5793, dport=80) / Raw(create_str)) pack = send_pkts_and_capture(port_interface_mapping, [{'port': 0, 'packet': fwd_pkt1}, {'port': 1, 'packet': fwd_pkt2}, {'port': 1, 'packet': fwd_pkt3}]) input_ports = {0, 1} output = create_port_seq_list([{'port': 2, 'packet': exp_pkt1}, {'port': 2, 'packet': exp_pkt2}, {'port': 3, 'packet': exp_pkt3}], pack, input_ports) return output
def test_mtu_failing(exp_src_mac, exp_dst_mac, port_interface_mapping, a, create_str): fwd_pkt1 = Ether() / IP(dst='10.1.0.1') / TCP(sport=5793, dport=80) fwd_pkt2 = Ether() / IP(dst='10.1.0.34') / TCP(sport=5793, dport=80) fwd_pkt3 = Ether() / IP(dst='10.1.0.32') / TCP(sport=5793, dport=80) / Raw(create_str) exp_pkt1 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.1', ttl=fwd_pkt1[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt2 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.34', ttl=fwd_pkt2[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt3 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.32', ttl=fwd_pkt3[IP].ttl-1) / TCP(sport=5793, dport=80) / Raw(create_str)) pack = send_pkts_and_capture(port_interface_mapping, [{'port': 0, 'packet': fwd_pkt1}, {'port': 1, 'packet': fwd_pkt2}, {'port': 1, 'packet': fwd_pkt3}]) input_ports = {0, 1} output = create_port_seq_list([{'port': 2, 'packet': exp_pkt1}, {'port': 2, 'packet': exp_pkt2}, {'port': 3, 'packet': exp_pkt3}], pack, input_ports) return output
def test_multicast_sa_da(a, port_interface_mapping, exp_src_mac, exp_dst_mac): fwd_pkt1 = Ether() / IP(src='10.1.0.3', dst='224.1.0.1') / TCP(sport=5793, dport=80) fwd_pkt2 = Ether() / IP(src='10.1.0.5', dst='224.1.0.1') / TCP(sport=5793, dport=80) exp_pkt1 = (Ether(src=exp_src_mac) / IP(src='10.1.0.3', dst='224.1.0.1', ttl=fwd_pkt1[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt2 = (Ether(src=exp_src_mac) / IP(src='10.1.0.5',dst='224.1.0.1', ttl=fwd_pkt2[IP].ttl-1) / TCP(sport=5793, dport=80)) pack = send_pkts_and_capture(port_interface_mapping, [{'port': 0, 'packet': fwd_pkt1}, {'port': 1, 'packet': fwd_pkt2}]) input_ports = {0, 1} output = create_port_seq_list([{'port': 2, 'packet': exp_pkt1}, {'port': 3, 'packet': exp_pkt1}, {'port': 4, 'packet': exp_pkt2}, {'port': 5, 'packet': exp_pkt2}, {'port': 6, 'packet': exp_pkt2}], pack, input_ports) return output
def test_multicast_rpf(a, port_interface_mapping, exp_src_mac, exp_dst_mac): fwd_pkt1 = Ether() / IP(src='10.1.0.3', dst='224.1.0.1') / TCP(sport=5793, dport=80) fwd_pkt2 = Ether() / IP(src='10.1.0.5', dst='224.1.0.1') / TCP(sport=5793, dport=80) exp_pkt1 = (Ether(src=exp_src_mac) / IP(src='10.1.0.3', dst='224.1.0.1', ttl=fwd_pkt1[IP].ttl-1) / TCP(sport=5793, dport=80)) exp_pkt2 = (Ether(src=exp_src_mac) / IP(src='10.1.0.5',dst='224.1.0.1', ttl=fwd_pkt2[IP].ttl-1) / TCP(sport=5793, dport=80)) # The ports 1 nad 0 are exchanged to check that the rpf and ingress port are different , # thus dropping the packets pack = send_pkts_and_capture(port_interface_mapping, [{'port': 1, 'packet': fwd_pkt1}, {'port': 0, 'packet': fwd_pkt2}]) input_ports = {0, 1} output = create_port_seq_list([], pack, input_ports) return output
def send_dhcp_over_qvb(self, port_id, port_mac): """Send DHCP Discovery over qvb device. """ qvb_device = utils.get_vif_name(constants.QVB_DEVICE_PREFIX, port_id) ethernet = scapy.Ether(dst='ff:ff:ff:ff:ff:ff', src=port_mac, type=0x800) ip = scapy.IP(src='0.0.0.0', dst='255.255.255.255') udp = scapy.UDP(sport=68, dport=67) port_mac_t = tuple(map(lambda x: int(x, 16), port_mac.split(':'))) hw = struct.pack('6B', *port_mac_t) bootp = scapy.BOOTP(chaddr=hw, flags=1) dhcp = scapy.DHCP(options=[("message-type", "discover"), "end"]) packet = ethernet / ip / udp / bootp / dhcp scapy.sendp(packet, iface=qvb_device)
def test_get_dhcp_mt(self): dhcp = scapy.DHCP(options=[("message-type", "discover"), "end"]) pkt = scapy.Ether() / scapy.IP() / scapy.UDP() / scapy.BOOTP() / dhcp message = self.scapy_dri.get_dhcp_mt(str(pkt)) self.assertIn(message, constants.DHCP_MESSATE_TYPE)
def cmd_dhcp_starvation(iface, timeout, sleeptime, verbose): conf.verb = False if iface: conf.iface = iface conf.checkIPaddr = False ether = Ether(dst="ff:ff:ff:ff:ff:ff") ip = IP(src="0.0.0.0",dst="255.255.255.255") udp = UDP(sport=68, dport=67) dhcp = DHCP(options=[("message-type","discover"),"end"]) while True: bootp = BOOTP(chaddr=str(RandMAC())) dhcp_discover = ether / ip / udp / bootp / dhcp ans, unans = srp(dhcp_discover, timeout=1) # Press CTRL-C after several seconds for _, pkt in ans: if verbose: print(pkt.show()) else: print(pkt.sprintf(r"%IP.src% offers %BOOTP.yiaddr%")) sleep(sleeptime)
def _send(self): """ Send a batch of randomly selected packets from the sending pool, then ensure the sending pool gets refilled if necessary. The packets are encapsulated in an Ethernet frame of type 0xcafe and removed from the sending pool, and finally broadcast in a batch. This function reschedules itself to occur every sending_freq seconds. """ self._scheduler.enter(self._sending_freq, 1, self._send) log_debug("Sending scheduler queue length: {}".format(len(self._scheduler.queue))) if self._sending: batch = [] s = sample(self._sending_pool, self._batch_size) for pkt in s: batch.append(Ether(dst="ff:ff:ff:ff:ff:ff", src=self._mac_address, type=ETHERTYPE) / pkt) self._sending_pool.remove(pkt) t_before = time() _gen_send_repeatable(self._sending_socket, batch, iface=self._wireless_interface, verbose=False) t_after = time() with open(self._stats_file_name, 'a') as stats_file: stats_file.write('{},{},{}\n'.format(t_before, t_after, len(batch))) self._sent_pkt_counter += len(batch) log_network("snt {} in {}s".format(len(batch), t_after - t_before)) self._prepare_sending_pool()
def get_mac(iface, ip): gw_ip = "" gws = gateways() for gw in gws.keys(): try: if str(gws[gw][AF_INET][1]) == iface: gw_ip = str(gws[gw][AF_INET][0]) except IndexError: if str(gws[gw][0][1]) == iface: gw_ip = str(gws[gw][0][0]) try: alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), iface=iface, timeout=10, verbose=0) return str(alive[0][1].hwsrc) except IndexError: try: alive, dead = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=gw_ip), iface=iface, timeout=10, verbose=0) return str(alive[0][1].hwsrc) except: return "ff:ff:ff:ff:ff:ff" except: return "ff:ff:ff:ff:ff:ff"
def runTest(self): pkt = scapy2.Ether(src="e4:1d:2d:a5:f3:ac", dst="00:02:03:04:05:00") pkt /= scapy2.IP(src="10.0.0.1", dst="10.0.0.0") # get L4 port number port_number = testutils.test_params_get("port_number") port = port_number["port_number"] pkt /= scapy2.TCP(sport = int(port)) pkt /= ("badabadaboom") # get packets number count = testutils.test_params_get("count") pack_number = count["count"] # send packets send(self, 0, pkt, int(pack_number))
def add_eth_ip_udp_headers(dport): eth = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') ip = IP(dst='10.0.0.2', ttl=64) udp = UDP(sport=65231, dport=dport) pkt = eth / ip / udp return pkt
def get_packetmod_pcap(nb_headers, nb_fields, mod_type, out_dir, packet_size=256): pkt = Packet() if mod_type == 'add': eth = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') ptp = PTP(reserved2=0) pkt = eth / ptp / '0x0' * 6 elif mod_type == 'rm': eth = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') ptp = PTP(reserved2=1) pkt = eth / ptp pkt /= add_layers(nb_fields, nb_headers) pkt = add_padding(pkt, packet_size) elif mod_type == 'mod': eth = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') ptp = PTP(reserved2=1) pkt = eth / ptp pkt /= add_layers(nb_fields, nb_headers) pkt = add_padding(pkt, packet_size) wrpcap('%s/test.pcap' % out_dir, pkt)
def test_ttl_cases(exp_src_mac, exp_dst_mac, port_interface_mapping, a): fwd_pkt1 = Ether() / IP(dst='10.1.0.1') / TCP(sport=5793, dport=80) fwd_pkt2 = Ether() / IP(dst='10.1.0.34', ttl =1) / TCP(sport=5793, dport=80) fwd_pkt3 = Ether() / IP(dst='10.1.0.32', ttl=0) / TCP(sport=5793, dport=80) exp_pkt1 = (Ether(src=exp_src_mac, dst=exp_dst_mac) / IP(dst='10.1.0.1', ttl=fwd_pkt1[IP].ttl-1) / TCP(sport=5793, dport=80)) pack = send_pkts_and_capture(port_interface_mapping, [{'port': 0, 'packet': fwd_pkt1}, {'port': 1, 'packet': fwd_pkt2}, {'port': 1, 'packet': fwd_pkt3}]) input_ports = {0, 1} output = create_port_seq_list([{'port': 2, 'packet': exp_pkt1}], pack, input_ports) return output
def get_arp_op(self, buff): ether_packet = scapy.Ether(buff) arp_packet = ether_packet[scapy.ARP] return constants.ARP_OP_TYPE[arp_packet.op]
def cmd_arpoison(t1, t2, iface, verbose): """ARP cache poison""" conf.verb = False if iface: conf.iface = iface mac1 = getmacbyip(t1) mac2 = getmacbyip(t2) pkt1 = Ether(dst=mac1)/ARP(op="is-at", psrc=t2, pdst=t1, hwdst=mac1) pkt2 = Ether(dst=mac2)/ARP(op="is-at", psrc=t1, pdst=t2, hwdst=mac2) try: while 1: sendp(pkt1) sendp(pkt2) if verbose: pkt1.show2() pkt2.show2() else: print(pkt1.summary()) print(pkt2.summary()) time.sleep(1) except KeyboardInterrupt: pass
def __init__(self, batch_size, sending_interval, wireless_interface, data_store): """ Initialize an aDTN instance and its respective key manager and message store, as well as a sending message pool from which the next sending batch gets generated. Define aDTNInnerPacket to be the payload of aDTNPacket. Define aDTNPacket to be the payload of Ethernet frames of type 0xcafe. Set up a scheduler to handle message sending. Define a thread to handle received messages. The wireless interface should be previously set to ad-hoc mode and its ESSID should be the same in other devices running aDTN. :param batch_size: number of packets to transmit at each sending operation :param sending_interval: number of seconds between two sending operations :param wireless_interface: wireless interface to send and receive packets """ self._batch_size = batch_size self._sending_freq = sending_interval self._wireless_interface = wireless_interface self._km = KeyManager() self.data_store = DataStore(data_store) self._sending_pool = [] self._scheduler = sched.scheduler(time, sleep) self._sending = None self._sniffing = None self._thread_send = None self._thread_receive = None self._sent_pkt_counter = None self._received_pkt_counter = None self._decrypted_pkt_counter = None self._start_time = None self._mac_address = macget(getcard(wireless_interface)) self._sending_socket = L2Socket(iface=self._wireless_interface) bind_layers(aDTNPacket, aDTNInnerPacket) bind_layers(Ether, aDTNPacket, type=ETHERTYPE) log_debug("MAC address in use: {}".format(self._mac_address)) self._stats_file_name = '{}_{}.stats'.format(batch_size, sending_interval)
def dhcpv6_callback(pkt): global dhcpv6_server_mac global dhcpv6_server_ipv6_link global dhcpv6_server_duid if pkt.haslayer(DHCP6_Reply): if pkt[DHCP6OptServerId].duid is None: return False else: dhcpv6_server_mac = pkt[Ether].src dhcpv6_server_ipv6_link = pkt[IPv6].src dhcpv6_server_duid = pkt[DHCP6OptServerId].duid return True else: return False
def make_arp_reply_packet(): return (Ether(src=sender_mac_address, dst=args.target_mac) / ARP(hwsrc=sender_mac_address, psrc=args.sender_ip, hwdst=args.target_mac, pdst=args.target_ip))
def build_packet(self, src_mac, dst_mac, src_ip, dst_ip, src_port, dst_port, seq, proto): eth = Ether(src=src_mac, dst=dst_mac, type=0x800) if proto == IP: ip = IP(src=src_ip, dst=dst_ip) elif proto == IPv6: ip = IPv6(src=src_ip, dst=dst_ip) else: return str(eth) #if unknown L2 protocol, send back dud ether packet tcp = TCP(sport=src_port, dport=dst_port, seq=seq, flags="R") return str(eth/ip/tcp)
def _get_source_from_packet(self, packet): try: ethernet_header = packet["Ether"] return ethernet_header.src except: dot11_header = packet["Dot11"] return dot11_header.addr2
def _get_destination_from_packet(self, packet): try: ethernet_header = packet["Ether"] return ethernet_header.dst except: dot11_header = packet["Dot11"] return dot11_header.addr1
def arping(mac, ip, timeout): """Arping function takes IP Address or Network, returns nested mac/ip list""" for i in range(timeout/2): ans = srp1(Ether(dst=mac)/ARP(pdst=ip), timeout=2, verbose=0) if ans: break return ans
def dispatch(pkt): src = pkt[Ether].src if src in buttons: now = time.time() if lastseen[src] == 0 or lastseen[src] < now - interval: lastseen[src] = now rx(buttons[src])
def get_parser_header_pcap(nb_fields, nb_headers, out_dir, packet_size=256): pkt = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') / PTP() pkt /= add_layers(nb_fields, nb_headers) pkt = add_padding(pkt, packet_size) wrpcap('%s/test.pcap' % out_dir, pkt)
def get_parser_field_pcap(nb_fields, out_dir, packet_size=256): pkt = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') / PTP() pkt /= vary_header_field(nb_fields) pkt = add_padding(pkt, packet_size) wrpcap('%s/test.pcap' % out_dir, pkt)
def set_custom_field_pcap(nb_fields, out_dir, packet_size=256): pkt = Ether(src='0C:C4:7A:A3:25:34', dst='0C:C4:7A:A3:25:35') / PTP() pkt /= add_layers(nb_fields, 1) pkt = add_padding(pkt, packet_size) wrpcap('%s/test.pcap' % out_dir, pkt)
def update_cache(self): try: ans, unans = arping(self._router_ip + "/24", iface=self._interface, verbose=False) self._arp_cache = [] if ans: for s, r in ans: self._arp_cache.append([r[ARP].psrc, r[Ether].src.lower()]) _LOGGER.debug("ARP cache: %s", self._arp_cache) except Exception as e: _LOGGER.error("Error when trying update ARP cache: %s", str(e))
def get_dhcp_mt(self, buff): """Pick out DHCP Message Type from buffer. """ ether_packet = scapy.Ether(buff) dhcp_packet = ether_packet[scapy.DHCP] # ('message-type', 1) message = dhcp_packet.options[0] return constants.DHCP_MESSATE_TYPE[message[1]]
def cmd_synflood(ip, interface, count, port, forgemac, forgeip, verbose): conf.verb = False if interface: conf.iface = interface layer2 = Ether() layer3 = IP() layer3.dst = ip layer4 = TCP() layer4.dport = port pkt = layer2 / layer3 / layer4 counter = 0 print("please, remember to block your RST responses") while True: if forgeip: pkt[IP].src = "%s.%s" %(pkt[IP].src.rsplit('.', maxsplit=1)[0], randint(1, 254)) if forgemac: pkt[Ether].src = RandMAC() pkt[TCP].sport = randint(10000, 65000) if verbose: print(pkt.summary()) else: print('.', end='') sys.stdout.flush() sendp(pkt) counter += 1 if count != 0 and counter == count: break return True
def cmd_arping(ip, iface, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') conf.verb = False if iface: conf.iface = iface res, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), timeout=2) res.show()
def parse_eap_packet(self, packet): eap_layer = packet[EAP] if eap_layer.type not in EAP_TYPES: return REQUEST, RESPONSE = 1, 2 # Means that we are the Access Point that the use is connecting to if Ether in packet: client_mac = packet[Ether].dst elif self._packet_is_from_ap(packet): client_mac = self._get_destination_from_packet(packet) else: client_mac = self._get_source_from_packet(packet) if client_mac: if client_mac not in self.wifi_clients: self.wifi_clients[client_mac] = WiFiClient(client_mac) else: return client = self.wifi_clients[client_mac] client.user_id = eap_layer.id if EAP_TYPES[eap_layer.type] == "ID" and eap_layer.code == RESPONSE: client.identity = eap_layer.identity elif EAP_TYPES[eap_layer.type] == "MD5": auth_id = eap_layer.id if auth_id not in client.authentications["MD5"]: client.authentications["MD5"][auth_id] = ChallengeResponseAuth(auth_id, "MD5") authentication = client.authentications["MD5"][auth_id] if eap_layer.code == REQUEST: authentication.challenge = eap_layer.load[1:17].encode("HEX") elif packet[EAP].code == RESPONSE: authentication.response = eap_layer.load[1:17].encode("HEX") elif EAP_TYPES[eap_layer.type] == "LEAP": auth_id = eap_layer.id if auth_id not in client.authentications["LEAP"]: client.authentications["LEAP"][auth_id] = ChallengeResponseAuth(auth_id, "LEAP") authentication = client.authentications["LEAP"][auth_id] leap_layer = packet[LEAP] if leap_layer.name: authentication.username = leap_layer.name if eap_layer.code == REQUEST: if len(leap_layer.data) == 8: authentication.challenge = leap_layer.data.encode("HEX") elif packet[EAP].code == RESPONSE: if len(leap_layer.data) == 24: authentication.response = eap_layer.data.encode("HEX") client.check_and_log_credentials()
def runTest(self): pkt = scapy2.Ether() pkt /= scapy2.IP(src="21.0.0.2", dst="22.0.0.2") pkt /= scapy2.TCP(dport = 80, flags="S", seq=42) pkt /= ("badabadaboom") t = Thread(target=self.Sniffer, args=("eth2",)) t.start() scapy2.sendp(pkt, iface='eth2') sleep(4) # fail if no reply if self.sniffed_cnt == 0: self.assertTrue(False) #res = scapy2.sniff(iface="eth2", timeout=3) #print res #if res: # raise #if reply: # raise #print "================______====\n" #print reply #print error #print "================______====\n" #if reply: # reply.show() #(rcv_device, rcv_port, rcv_pkt, pkt_time) = dp_poll(self, device_number=0, port_number=0, timeout=5) #send_packet(self, 0, pkt) #(rcv_device, rcv_port, rcv_pkt, pkt_time) = dp_poll(self, device_number=0, port_number=0, timeout=5) # verify_packet(self, masked_exp_pkt, 1) #mpkt = Mask(pkt) #mpkt.set_do_not_care(0, 14*8) #mpkt.set_do_not_care(16*8, 49*8) #verify_packet(self, mpkt, 0) #(rcv_device, rcv_port, rcv_pkt, pkt_time) = dp_poll(self, device_number=0, port_number=0, timeout=5) #print "================______====\n" #y = 0 #for x in rcv_pkt: # print "%d - %X" % (y, ord(x)) # y +=1
def packet_out(self, in_port, out_port, data): in_port = "CONTROLLER" if in_port == ofp.OFPP_CONTROLLER else in_port print "PACKET OUT (%s => %s): " % (in_port, out_port) hexdump(data) if self.in_out_iface is not None: try: # disect the packet pkt = Ether(data) # remove payload from Ether frame payload = pkt.payload payload_type = pkt.type pkt.remove_payload() # insert Dot1Q shim with vlan_id = out_port if self.in_out_stag is None: ## WARNING -- This was changed from 0x88a8 to 0x8100 when ## testing with the Intel XL710 quad 10GE boards. The ## XL710 does not support the TPID for the STAG. ## ## Long term, it should be changed back to 0x88a8! ## pkt.type = 0x8100 new_pkt = pkt / Dot1Q(vlan=out_port, type=payload_type) / payload else: pkt.type = 0x8100 new_pkt = ( pkt / Dot1Q(vlan=self.in_out_stag, type=0x8100) / Dot1Q(vlan=out_port, type=payload_type) / payload) # send out the packet sendp(new_pkt, iface=self.in_out_iface) except Exception, e: logging.exception("Could not parse packet-out data as scapy.Ether:\n") logging.error(hexdump(data, 'return'))
def forward_packet(self, pkt): print "Received packet:" hexdump(str(pkt)) pkt.show() try: assert isinstance(pkt, Ether) assert isinstance(pkt.getlayer(1), Dot1Q) dot1q = pkt.getlayer(1) assert isinstance(dot1q, Dot1Q) if self.in_out_stag is None: payload = dot1q.payload payload_type = dot1q.type pkt.remove_payload() pkt.type = payload_type new_pkt = pkt / payload in_port = dot1q.vlan else: if dot1q.vlan != self.in_out_stag: print 'Dropping packet because outer tag %d does not match %d' % ( dot1q.vlan, self.in_out_stag) return dot1q_inner = dot1q.getlayer(1) assert isinstance(dot1q_inner, Dot1Q) payload = dot1q_inner.payload payload_type = dot1q_inner.type pkt.remove_payload() pkt.type = payload_type new_pkt = pkt / payload in_port = dot1q_inner.vlan if self.agent is not None: self.agent.send_packet_in(str(new_pkt), in_port=in_port) print 'new packet forwarded to controller (with in_port=%d):' % in_port new_pkt.show() except Exception, e: logging.exception("Unexpected packet format received by InOutReceiver: %s" % e) logging.error(hexdump(str(pkt), 'return'))