Exemplo n.º 1
0
    def _build_itag(self):
        b_src_mac = '00:07:0d:af:f4:54'
        b_dst_mac = '00:00:00:00:00:00'
        b_ethertype = ether.ETH_TYPE_8021AD
        e1 = ethernet.ethernet(b_dst_mac, b_src_mac, b_ethertype)

        b_pcp = 0
        b_cfi = 0
        b_vid = 32
        b_ethertype = ether.ETH_TYPE_8021Q
        bt = vlan.svlan(b_pcp, b_cfi, b_vid, b_ethertype)

        c_src_mac = '11:11:11:11:11:11'
        c_dst_mac = 'aa:aa:aa:aa:aa:aa'
        c_ethertype = ether.ETH_TYPE_8021AD
        e2 = ethernet.ethernet(c_dst_mac, c_src_mac, c_ethertype)

        s_pcp = 0
        s_cfi = 0
        s_vid = 32
        s_ethertype = ether.ETH_TYPE_8021Q
        st = vlan.svlan(s_pcp, s_cfi, s_vid, s_ethertype)

        c_pcp = 0
        c_cfi = 0
        c_vid = 32
        c_ethertype = ether.ETH_TYPE_IP
        ct = vlan.vlan(c_pcp, c_cfi, c_vid, c_ethertype)

        version = 4
        header_length = 20
        tos = 0
        total_length = 24
        identification = 0x8a5d
        flags = 0
        offset = 1480
        ttl = 64
        proto = inet.IPPROTO_ICMP
        csum = 0xa7f2
        src = '131.151.32.21'
        dst = '131.151.32.129'
        option = b'TEST'
        ip = ipv4.ipv4(version, header_length, tos, total_length,
                       identification, flags, offset, ttl, proto, csum, src,
                       dst, option)

        p = packet.Packet()

        p.add_protocol(e1)
        p.add_protocol(bt)
        p.add_protocol(self.it)
        p.add_protocol(e2)
        p.add_protocol(st)
        p.add_protocol(ct)
        p.add_protocol(ip)
        p.serialize()

        return p
Exemplo n.º 2
0
    def create_packet(self, primary_ip_address, vlan_id=None):
        """Prepare a VRRP packet.

        Returns a newly created os_ken.lib.packet.packet.Packet object
        with appropriate protocol header objects added by add_protocol().
        It's caller's responsibility to serialize().
        The serialized packet would looks like the ones described in
        the following sections.

        * RFC 3768 5.1. VRRP Packet Format
        * RFC 5798 5.1. VRRP Packet Format

        ================== ====================
        Argument           Description
        ================== ====================
        primary_ip_address Source IP address
        vlan_id            VLAN ID.  None for no VLAN.
        ================== ====================
        """
        if self.is_ipv6:
            traffic_class = 0xc0        # set tos to internetwork control
            flow_label = 0
            payload_length = ipv6.ipv6._MIN_LEN + len(self)     # XXX _MIN_LEN
            e = ethernet.ethernet(VRRP_IPV6_DST_MAC_ADDRESS,
                                  vrrp_ipv6_src_mac_address(self.vrid),
                                  ether.ETH_TYPE_IPV6)
            ip = ipv6.ipv6(6, traffic_class, flow_label, payload_length,
                           inet.IPPROTO_VRRP, VRRP_IPV6_HOP_LIMIT,
                           primary_ip_address, VRRP_IPV6_DST_ADDRESS)
        else:
            header_length = ipv4.ipv4._MIN_LEN // 4      # XXX _MIN_LEN
            total_length = 0
            tos = 0xc0  # set tos to internetwork control
            identification = self.get_identification()
            e = ethernet.ethernet(VRRP_IPV4_DST_MAC_ADDRESS,
                                  vrrp_ipv4_src_mac_address(self.vrid),
                                  ether.ETH_TYPE_IP)
            ip = ipv4.ipv4(4, header_length, tos, total_length, identification,
                           0, 0, VRRP_IPV4_TTL, inet.IPPROTO_VRRP, 0,
                           primary_ip_address, VRRP_IPV4_DST_ADDRESS)

        p = packet.Packet()
        p.add_protocol(e)
        if vlan_id is not None:
            vlan_ = vlan.vlan(0, 0, vlan_id, e.ethertype)
            e.ethertype = ether.ETH_TYPE_8021Q
            p.add_protocol(vlan_)
        p.add_protocol(ip)
        p.add_protocol(self)
        return p
Exemplo n.º 3
0
    def test_serialize(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet('b0:a8:6e:18:b8:08', '64:87:88:e9:cb:c8')
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src='172.28.3.1',
                           dst='172.28.3.2',
                           tos=192,
                           identification=26697,
                           proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        bfd_pkt = bfd.bfd(ver=1,
                          diag=bfd.BFD_DIAG_CTRL_DETECT_TIME_EXPIRED,
                          state=bfd.BFD_STATE_UP,
                          detect_mult=3,
                          my_discr=6,
                          your_discr=7,
                          desired_min_tx_interval=60000,
                          required_min_rx_interval=60000,
                          required_min_echo_rx_interval=0)
        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data)
Exemplo n.º 4
0
    def test_serialize(self):
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = '00:04:96:1f:a7:26'
        ethertype = ether.ETH_TYPE_LLDP
        eth_pkt = ethernet.ethernet(dst, src, ethertype)
        pkt.add_protocol(eth_pkt)

        tlv_chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
            chassis_id=addrconv.mac.text_to_bin(src))
        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                                  port_id=b'1/3')
        tlv_ttl = lldp.TTL(ttl=120)
        tlv_end = lldp.End()
        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_end)
        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)

        eq_(len(pkt.protocols), 2)

        pkt.serialize()

        # Note: If ethernet frame is less than 60 bytes length,
        # ethernet.ethernet() appends padding to the payload.
        # So, we splits the serialized data to compare.
        data_len = len(self.data)
        pkt_data_lldp = pkt.data[:data_len]
        pkt_data_pad = pkt.data[data_len:]
        eq_(b'\x00' * (60 - data_len), pkt_data_pad)

        eq_(self.data, pkt_data_lldp)
Exemplo n.º 5
0
    def _build_vlan(self):
        src_mac = '00:07:0d:af:f4:54'
        dst_mac = '00:00:00:00:00:00'
        ethertype = ether.ETH_TYPE_8021Q
        e = ethernet(dst_mac, src_mac, ethertype)

        version = 4
        header_length = 20
        tos = 0
        total_length = 24
        identification = 0x8a5d
        flags = 0
        offset = 1480
        ttl = 64
        proto = inet.IPPROTO_ICMP
        csum = 0xa7f2
        src = '131.151.32.21'
        dst = '131.151.32.129'
        option = b'TEST'
        ip = ipv4(version, header_length, tos, total_length, identification,
                  flags, offset, ttl, proto, csum, src, dst, option)

        p = Packet()

        p.add_protocol(e)
        p.add_protocol(self.v)
        p.add_protocol(ip)
        p.serialize()

        return p
Exemplo n.º 6
0
 def _create_test_dhcp_request_packet(self):
     option_list = []
     bin_server = addrconv.ipv4.text_to_bin('192.168.1.1')
     option_list.append(
         dhcp.option(tag=dhcp.DHCP_SERVER_IDENTIFIER_OPT, value=bin_server))
     option_list.append(
         dhcp.option(tag=dhcp.DHCP_MESSAGE_TYPE_OPT, value=b'\x03'))
     options = dhcp.options(option_list=option_list)
     ret_pkt = packet.Packet()
     ret_pkt.add_protocol(
         ethernet.ethernet(dst="ff:ff:ff:ff:ff:ff",
                           src=self.port_info['mac_address']))
     ret_pkt.add_protocol(
         ipv4.ipv4(dst="255.255.255.255",
                   src="0.0.0.0",
                   proto=inet.IPPROTO_UDP))
     ret_pkt.add_protocol(
         udp.udp(src_port=constants.DHCP_CLIENT_PORT,
                 dst_port=constants.DHCP_RESPONSE_PORT))
     ret_pkt.add_protocol(
         dhcp.dhcp(op=dhcp.DHCP_BOOT_REQUEST,
                   chaddr=self.port_info['mac_address'],
                   siaddr='0.0.0.0',
                   xid=3454038351,
                   options=options))
     return ret_pkt
Exemplo n.º 7
0
    def _create_test_dhcp6_packet(self, zero_time=False):
        ret_pkt = packet.Packet()
        ret_pkt.add_protocol(
            ethernet.ethernet(
                ethertype=ether_types.ETH_TYPE_IPV6,
                dst='33:33:00:01:00:02',
                src=self.port_info['mac_address']))
        ret_pkt.add_protocol(
            ipv6.ipv6(
                src='fe80::f816:3eff:fe60:714b',
                dst='ff02::1:2',
                nxt=inet.IPPROTO_UDP))
        ret_pkt.add_protocol(
            udp.udp(
                src_port=constants.DHCPV6_RESPONSE_PORT,
                dst_port=constants.DHCPV6_CLIENT_PORT))

        options = [dhcp6.option(
            code=1,
            data=b"\x00\x01\x00\x01",
            length=4)]
        if zero_time:
            options.append(dhcp6.option(
                code=3,
                data=b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
                length=12))
        else:
            options.append(dhcp6.option(
                code=3,
                data=b"\x01\x02\x03\x04\x05\x06\x07\x08\x0a\x0b\x0c\x0d",
                length=12))
        ret_pkt.add_protocol(dhcp6.dhcp6(
            dhcp6.DHCPV6_REQUEST, dhcp6.options(option_list=options)))
        return ret_pkt
Exemplo n.º 8
0
    def lldp_packet(dpid, port_no, dl_addr, ttl):
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = dl_addr
        ethertype = ETH_TYPE_LLDP
        eth_pkt = ethernet.ethernet(dst, src, ethertype)
        pkt.add_protocol(eth_pkt)

        tlv_chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
            chassis_id=(LLDPPacket.CHASSIS_ID_FMT %
                        dpid_to_str(dpid)).encode('ascii'))

        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT,
                                  port_id=struct.pack(LLDPPacket.PORT_ID_STR,
                                                      port_no))

        tlv_ttl = lldp.TTL(ttl=ttl)
        tlv_end = lldp.End()

        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_end)
        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)

        pkt.serialize()
        return pkt.data
Exemplo n.º 9
0
    def _generate_config_bpdu(self, flags):
        src_mac = self.ofport.hw_addr
        dst_mac = bpdu.BRIDGE_GROUP_ADDRESS
        length = (bpdu.bpdu._PACK_LEN + bpdu.ConfigurationBPDUs.PACK_LEN +
                  llc.llc._PACK_LEN + llc.ControlFormatU._PACK_LEN)

        e = ethernet.ethernet(dst_mac, src_mac, length)
        l = llc.llc(llc.SAP_BPDU, llc.SAP_BPDU, llc.ControlFormatU())
        b = bpdu.ConfigurationBPDUs(
            flags=flags,
            root_priority=self.port_priority.root_id.priority,
            root_mac_address=self.port_priority.root_id.mac_addr,
            root_path_cost=self.port_priority.root_path_cost + self.path_cost,
            bridge_priority=self.bridge_id.priority,
            bridge_mac_address=self.bridge_id.mac_addr,
            port_priority=self.port_id.priority,
            port_number=self.ofport.port_no,
            message_age=self.port_times.message_age + 1,
            max_age=self.port_times.max_age,
            hello_time=self.port_times.hello_time,
            forward_delay=self.port_times.forward_delay)

        pkt = packet.Packet()
        pkt.add_protocol(e)
        pkt.add_protocol(l)
        pkt.add_protocol(b)
        pkt.serialize()

        return pkt.data
Exemplo n.º 10
0
    def test_default_args(self):
        e = ethernet()
        buf = e.serialize(bytearray(), None)
        res = struct.unpack(e._PACK_STR, six.binary_type(buf))

        eq_(res[0], addrconv.mac.text_to_bin('ff:ff:ff:ff:ff:ff'))
        eq_(res[1], addrconv.mac.text_to_bin('00:00:00:00:00:00'))
        eq_(res[2], ether.ETH_TYPE_IP)
Exemplo n.º 11
0
    def bfd_packet(src_mac,
                   dst_mac,
                   src_ip,
                   dst_ip,
                   ipv4_id,
                   src_port,
                   dst_port,
                   diag=0,
                   state=0,
                   flags=0,
                   detect_mult=0,
                   my_discr=0,
                   your_discr=0,
                   desired_min_tx_interval=0,
                   required_min_rx_interval=0,
                   required_min_echo_rx_interval=0,
                   auth_cls=None):
        """
        Generate BFD packet with Ethernet/IPv4/UDP encapsulated.
        """
        # Generate ethernet header first.
        pkt = packet.Packet()
        eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_IP)
        pkt.add_protocol(eth_pkt)

        # IPv4 encapsulation
        # set ToS to 192 (Network control/CS6)
        # set TTL to 255 (RFC5881 Section 5.)
        ipv4_pkt = ipv4.ipv4(proto=inet.IPPROTO_UDP,
                             src=src_ip,
                             dst=dst_ip,
                             tos=192,
                             identification=ipv4_id,
                             ttl=255)
        pkt.add_protocol(ipv4_pkt)

        # UDP encapsulation
        udp_pkt = udp.udp(src_port=src_port, dst_port=dst_port)
        pkt.add_protocol(udp_pkt)

        # BFD payload
        bfd_pkt = bfd.bfd(
            ver=1,
            diag=diag,
            state=state,
            flags=flags,
            detect_mult=detect_mult,
            my_discr=my_discr,
            your_discr=your_discr,
            desired_min_tx_interval=desired_min_tx_interval,
            required_min_rx_interval=required_min_rx_interval,
            required_min_echo_rx_interval=required_min_echo_rx_interval,
            auth_cls=auth_cls)
        pkt.add_protocol(bfd_pkt)

        pkt.serialize()
        return pkt.data
Exemplo n.º 12
0
    def send_arp_request(self, src_mac, src_ip, dst_ip, port_key):
        arp_request_pkt = packet.Packet()
        arp_request_pkt.add_protocol(
            ethernet.ethernet(ethertype=ether.ETH_TYPE_ARP, src=src_mac))

        arp_request_pkt.add_protocol(
            arp.arp(src_mac=src_mac, src_ip=src_ip, dst_ip=dst_ip))

        self.dispatch_packet(arp_request_pkt, port_key)
Exemplo n.º 13
0
    def _build_lacp(self):
        ethertype = ether.ETH_TYPE_SLOW
        dst = SLOW_PROTOCOL_MULTICAST
        e = ethernet(dst, self.actor_system, ethertype)
        p = Packet()

        p.add_protocol(e)
        p.add_protocol(self.l)
        p.serialize()
        return p
Exemplo n.º 14
0
 def _create_response(self, datapath, port, req):
     """create a packet including LACP."""
     src = datapath.ports[port].hw_addr
     res_ether = ethernet.ethernet(slow.SLOW_PROTOCOL_MULTICAST, src,
                                   ether.ETH_TYPE_SLOW)
     res_lacp = self._create_lacp(datapath, port, req)
     res_pkt = packet.Packet()
     res_pkt.add_protocol(res_ether)
     res_pkt.add_protocol(res_lacp)
     res_pkt.serialize()
     return res_pkt
Exemplo n.º 15
0
    def _do_leave(self, leave, in_port, msg):
        """the process when the snooper received a LEAVE message."""
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        # check whether the querier port has been specified.
        if not self._to_querier.get(dpid):
            self.logger.info("no querier exists.")
            return

        # save this LEAVE message and reset the condition of the port
        # that received this message.
        self._to_hosts.setdefault(dpid, {})
        self._to_hosts[dpid].setdefault(leave.address, {
            'replied': False,
            'leave': None,
            'ports': {}
        })
        self._to_hosts[dpid][leave.address]['leave'] = msg
        self._to_hosts[dpid][leave.address]['ports'][in_port] = {
            'out': False,
            'in': False
        }

        # create a specific query.
        timeout = igmp.LAST_MEMBER_QUERY_INTERVAL
        res_igmp = igmp.igmp(msgtype=igmp.IGMP_TYPE_QUERY,
                             maxresp=timeout * 10,
                             csum=0,
                             address=leave.address)
        res_ipv4 = ipv4.ipv4(total_length=len(ipv4.ipv4()) + len(res_igmp),
                             proto=inet.IPPROTO_IGMP,
                             ttl=1,
                             src=self._to_querier[dpid]['ip'],
                             dst=igmp.MULTICAST_IP_ALL_HOST)
        res_ether = ethernet.ethernet(dst=igmp.MULTICAST_MAC_ALL_HOST,
                                      src=self._to_querier[dpid]['mac'],
                                      ethertype=ether.ETH_TYPE_IP)
        res_pkt = packet.Packet()
        res_pkt.add_protocol(res_ether)
        res_pkt.add_protocol(res_ipv4)
        res_pkt.add_protocol(res_igmp)
        res_pkt.serialize()

        # send a specific query to the host that sent this message.
        actions = [parser.OFPActionOutput(ofproto.OFPP_IN_PORT)]
        self._do_packet_out(datapath, res_pkt.data, in_port, actions)

        # wait for REPORT messages.
        hub.spawn(self._do_timeout_for_leave, timeout, datapath, leave.address,
                  in_port)
Exemplo n.º 16
0
    def test_reply_ttl_invalid_message_with_rate_limit(self):
        pkt = packet.Packet()
        pkt.add_protocol(ethernet.ethernet(dst='aa:bb:cc:dd:ee:ff'))
        pkt.add_protocol(ipv4.ipv4(proto=in_proto.IPPROTO_UDP))
        pkt.add_protocol(udp.udp())
        pkt.serialize()

        lswitch = l2.LogicalSwitch(
            id='lswitch1',
            topic='topic1',
            unique_key=9,
            version=1,
        )
        self.app.db_store.update(lswitch)

        lrouter = l3.LogicalRouter(
            id='lrouter1',
            topic='topic1',
            version=1,
            unique_key=22,
            ports=[
                l3.LogicalRouterPort(
                    id='lrouter1-port1',
                    unique_key=55,
                    topic='topic1',
                    mac='aa:bb:cc:dd:ee:ff',
                    network='10.0.0.1/24',
                    lswitch='lswitch1',
                ),
            ],
        )
        self.app.db_store.update(lrouter)

        event = ofp_event.EventOFPMsgBase(msg=ofproto_parser.OFPPacketIn(
            datapath=mock.Mock(),
            reason=self.app.ofproto.OFPR_INVALID_TTL,
            match=ofproto_parser.OFPMatch(
                metadata=lswitch.unique_key,
                reg5=lrouter.unique_key,
            ),
            data=pkt.data,
        ))

        with mock.patch("dragonflow.controller.common."
                        "icmp_error_generator.generate") as icmp_error:
            for _ in range(self.app.conf.router_ttl_invalid_max_rate * 2):
                self.app.packet_in_handler(event)

            self.assertEqual(self.app.conf.router_ttl_invalid_max_rate,
                             icmp_error.call_count)
            icmp_error.assert_called_with(icmp.ICMP_TIME_EXCEEDED,
                                          icmp.ICMP_TTL_EXPIRED_CODE, mock.ANY,
                                          "10.0.0.1", mock.ANY)
Exemplo n.º 17
0
def build_pkt_header(vid, eth_src, eth_dst, dl_type):
    """Return an Ethernet packet header.

    Args:
        vid (int or None): VLAN VID to use (or None).
        eth_src (str): source Ethernet MAC address.
        eth_dst (str): destination Ethernet MAC address.
        dl_type (int): EtherType.
    Returns:
        ryu.lib.packet.ethernet: Ethernet packet with header.
    """
    pkt_header = packet.Packet()
    if vid is None:
        eth_header = ethernet.ethernet(eth_dst, eth_src, dl_type)
        pkt_header.add_protocol(eth_header)
    else:
        eth_header = ethernet.ethernet(eth_dst, eth_src,
                                       valve_of.ether.ETH_TYPE_8021Q)
        pkt_header.add_protocol(eth_header)
        vlan_header = vlan.vlan(vid=vid, ethertype=dl_type)
        pkt_header.add_protocol(vlan_header)
    return pkt_header
Exemplo n.º 18
0
    def _build_arp(self, vlan_enabled):
        if vlan_enabled is True:
            ethertype = ether.ETH_TYPE_8021Q
            v = vlan(1, 1, 3, ether.ETH_TYPE_ARP)
        else:
            ethertype = ether.ETH_TYPE_ARP
        e = ethernet(self.dst_mac, self.src_mac, ethertype)
        p = Packet()

        p.add_protocol(e)
        if vlan_enabled is True:
            p.add_protocol(v)
        p.add_protocol(self.a)
        p.serialize()
        return p
Exemplo n.º 19
0
    def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip):
        """
        Generate ARP packet with ethernet encapsulated.
        """
        # Generate ethernet header first.
        pkt = packet.Packet()
        eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP)
        pkt.add_protocol(eth_pkt)

        # Use IPv4 ARP wrapper from packet library directly.
        arp_pkt = arp.arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip)
        pkt.add_protocol(arp_pkt)

        pkt.serialize()
        return pkt.data
Exemplo n.º 20
0
    def get_ret_packet(self, packet_in, port_info, req_type):
        ip_info = self.get_port_ip(port_info,
                                   ip_version=constants.IP_VERSION_6)
        if not ip_info:
            return
        gateway_ip = ip_info['gateway_ip']
        mac = port_info['mac_address']

        header_eth = packet_in.get_protocol(ethernet.ethernet)
        header_ipv6 = packet_in.get_protocol(ipv6.ipv6)
        header_dhcp = packet_in.get_protocol(dhcp6.dhcp6)

        if req_type == 'CONFIRM':
            options = self.get_reply_dhcp_options(
                mac,
                message="all addresses still on link",
                req_options=header_dhcp.options.option_list)
        if req_type == 'RELEASE':
            options = self.get_reply_dhcp_options(
                mac,
                message="release received",
                req_options=header_dhcp.options.option_list)
        else:
            options = self.get_dhcp_options(mac, ip_info,
                                            header_dhcp.options.option_list,
                                            req_type)

        ret_pkt = packet.Packet()
        ret_pkt.add_protocol(
            ethernet.ethernet(ethertype=header_eth.ethertype,
                              dst=header_eth.src,
                              src=self.hw_addr))
        ret_pkt.add_protocol(
            ipv6.ipv6(src=gateway_ip,
                      dst=header_ipv6.src,
                      nxt=inet.IPPROTO_UDP))
        ret_pkt.add_protocol(
            udp.udp(src_port=constants.DHCPV6_RESPONSE_PORT,
                    dst_port=constants.DHCPV6_CLIENT_PORT))

        ret_type = self.get_ret_type(req_type)

        ret_pkt.add_protocol(
            dhcp6.dhcp6(ret_type,
                        options,
                        transaction_id=header_dhcp.transaction_id))

        return ret_pkt
Exemplo n.º 21
0
    def _create_dhcp_response(self, packet, dhcp_request, response_type, lport,
                              dhcp_port):
        pkt_ipv4 = packet.get_protocol(ipv4.ipv4)
        pkt_ethernet = packet.get_protocol(ethernet.ethernet)

        try:
            subnet = lport.subnets[0]
        except IndexError:
            LOG.warning("No subnet found for port %s", lport.id)
            return

        dhcp_server_address = self._dhcp_ip_by_subnet.get(subnet.id)
        if not dhcp_server_address:
            LOG.warning("Could not find DHCP server address for subnet %s",
                        subnet.id)
            return

        option_list = self._build_dhcp_options(dhcp_request, response_type,
                                               lport, subnet,
                                               dhcp_server_address)

        options = dhcp.options(option_list=option_list)

        dhcp_response = os_ken_packet.Packet()
        dhcp_response.add_protocol(
            ethernet.ethernet(ethertype=ether.ETH_TYPE_IP,
                              dst=pkt_ethernet.src,
                              src=dhcp_port.mac))
        dhcp_response.add_protocol(
            ipv4.ipv4(dst=pkt_ipv4.src,
                      src=dhcp_server_address,
                      proto=pkt_ipv4.proto))
        dhcp_response.add_protocol(
            udp.udp(src_port=const.DHCP_SERVER_PORT,
                    dst_port=const.DHCP_CLIENT_PORT))

        siaddr = lport.dhcp_params.siaddr or dhcp_server_address

        dhcp_response.add_protocol(
            dhcp.dhcp(op=dhcp.DHCP_BOOT_REPLY,
                      chaddr=pkt_ethernet.src,
                      siaddr=siaddr,
                      boot_file=dhcp_request.boot_file,
                      yiaddr=lport.ip,
                      xid=dhcp_request.xid,
                      options=options))
        return dhcp_response
Exemplo n.º 22
0
    def test_serialize(self):
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = '00:01:30:f9:ad:a0'
        ethertype = ether.ETH_TYPE_LLDP
        eth_pkt = ethernet.ethernet(dst, src, ethertype)
        pkt.add_protocol(eth_pkt)

        tlv_chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
            chassis_id=addrconv.mac.text_to_bin(src))
        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                                  port_id=b'1/1')
        tlv_ttl = lldp.TTL(ttl=120)
        tlv_port_description = lldp.PortDescription(
            port_description=b'Summit300-48-Port 1001\x00')
        tlv_system_name = lldp.SystemName(system_name=b'Summit300-48\x00')
        tlv_system_description = lldp.SystemDescription(
            system_description=b'Summit300-48 - Version 7.4e.1 (Build 5) ' +
            b'by Release_Master 05/27/05 04:53:11\x00')
        tlv_system_capabilities = lldp.SystemCapabilities(system_cap=0x14,
                                                          enabled_cap=0x14)
        tlv_management_address = lldp.ManagementAddress(
            addr_subtype=0x06,
            addr=b'\x00\x01\x30\xf9\xad\xa0',
            intf_subtype=0x02,
            intf_num=1001,
            oid=b'')
        tlv_organizationally_specific = lldp.OrganizationallySpecific(
            oui=b'\x00\x12\x0f', subtype=0x02, info=b'\x07\x01\x00')
        tlv_end = lldp.End()
        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_port_description,
                tlv_system_name, tlv_system_description,
                tlv_system_capabilities, tlv_management_address,
                tlv_organizationally_specific, tlv_end)
        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)

        eq_(len(pkt.protocols), 2)

        pkt.serialize()

        # self.data has many organizationally specific TLVs
        data = six.binary_type(pkt.data[:-2])
        eq_(data, self.data[:len(data)])
Exemplo n.º 23
0
    def _generate_tcn_bpdu(self):
        src_mac = self.ofport.hw_addr
        dst_mac = bpdu.BRIDGE_GROUP_ADDRESS
        length = (bpdu.bpdu._PACK_LEN +
                  bpdu.TopologyChangeNotificationBPDUs.PACK_LEN +
                  llc.llc._PACK_LEN + llc.ControlFormatU._PACK_LEN)

        e = ethernet.ethernet(dst_mac, src_mac, length)
        l = llc.llc(llc.SAP_BPDU, llc.SAP_BPDU, llc.ControlFormatU())
        b = bpdu.TopologyChangeNotificationBPDUs()

        pkt = packet.Packet()
        pkt.add_protocol(e)
        pkt.add_protocol(l)
        pkt.add_protocol(b)
        pkt.serialize()

        return pkt.data
Exemplo n.º 24
0
 def packet_in_handler(self, event):
     if event.msg.match['in_port'] != FAKEPORT:
         return
     pkt = packet.Packet(event.msg.data)
     eth_protocol = pkt.get_protocol(ethernet.ethernet)
     vlan_protocol = pkt.get_protocol(vlan.vlan)
     ipv6_protocol = pkt.get_protocol(ipv6.ipv6)
     icmpv6_protocol = pkt.get_protocol(icmpv6.icmpv6)
     if not (eth_protocol and vlan_protocol and ipv6_protocol
             and icmpv6_protocol):
         return
     if icmpv6_protocol.type_ != icmpv6.ND_NEIGHBOR_SOLICIT:
         return
     if int(ipaddress.ip_address(ipv6_protocol.src)) == 0:
         return
     src_ip = ipaddress.ip_address(icmpv6_protocol.data.dst)
     if src_ip.is_reserved:
         return
     eth_dst = eth_protocol.src
     dst_ip = ipv6_protocol.src
     eth_src = FAKECLIENTMAC
     vid = vlan_protocol.vid
     reply = packet.Packet()
     for protocol in (ethernet.ethernet(eth_dst, eth_src,
                                        ether.ETH_TYPE_8021Q),
                      vlan.vlan(vid=vid, ethertype=ether.ETH_TYPE_IPV6),
                      ipv6.ipv6(src=src_ip,
                                dst=dst_ip,
                                nxt=socket.IPPROTO_ICMPV6,
                                hop_limit=255),
                      icmpv6.icmpv6(
                          type_=icmpv6.ND_NEIGHBOR_ADVERT,
                          data=icmpv6.nd_neighbor(
                              dst=src_ip,
                              option=icmpv6.nd_option_tla(hw_src=eth_src),
                              res=7))):
         reply.add_protocol(protocol)
     reply.serialize()
     out = parser.OFPPacketOut(datapath=event.msg.datapath,
                               buffer_id=ofp.OFP_NO_BUFFER,
                               in_port=ofp.OFPP_CONTROLLER,
                               actions=[parser.OFPActionOutput(FAKEPORT)],
                               data=reply.data)
     self.send_mods(event.msg.datapath, [out])
Exemplo n.º 25
0
    def get_ret_packet(self, packet_in, port_info, is_ack=False):
        ip_info = self.get_port_ip(port_info,
                                   ip_version=constants.IP_VERSION_4)
        if not ip_info:
            return
        ip_addr = ip_info['ip_address']
        gateway_ip = ip_info['gateway_ip']

        options = self.get_dhcp_options(port_info, is_ack)
        if is_ack:
            fqdn = 'host-%s' % ip_addr.replace('.', '-').replace(':', '-')
            if cfg.CONF.dns_domain:
                fqdn = '%s.%s' % (fqdn, cfg.CONF.dns_domain)
            domain_name_bin = struct.pack('!%ds' % len(fqdn),
                                          bytes(str(fqdn).encode()))
            options.option_list.append(
                dhcp.option(tag=dhcp.DHCP_HOST_NAME_OPT,
                            value=domain_name_bin))

        header_eth = packet_in.get_protocol(ethernet.ethernet)
        header_ipv4 = packet_in.get_protocol(ipv4.ipv4)
        header_dhcp = packet_in.get_protocol(dhcp.dhcp)

        ret_pkt = packet.Packet()
        ret_pkt.add_protocol(
            ethernet.ethernet(ethertype=header_eth.ethertype,
                              dst=header_eth.src,
                              src=self.hw_addr))
        ret_pkt.add_protocol(
            ipv4.ipv4(dst=header_ipv4.dst,
                      src=gateway_ip,
                      proto=header_ipv4.proto))
        ret_pkt.add_protocol(
            udp.udp(src_port=constants.DHCP_RESPONSE_PORT,
                    dst_port=constants.DHCP_CLIENT_PORT))
        ret_pkt.add_protocol(
            dhcp.dhcp(op=dhcp.DHCP_BOOT_REPLY,
                      chaddr=header_eth.src,
                      siaddr=gateway_ip,
                      boot_file=header_dhcp.boot_file,
                      yiaddr=ip_addr,
                      xid=header_dhcp.xid,
                      options=options))
        return ret_pkt
Exemplo n.º 26
0
    def test_reply_icmp_unreachable_with_rate_limit(self):
        pkt = packet.Packet()
        pkt.add_protocol(ethernet.ethernet(dst='aa:bb:cc:dd:ee:ff'))
        pkt.add_protocol(ipv4.ipv4(dst='10.0.0.1', proto=in_proto.IPPROTO_UDP))
        pkt.add_protocol(udp.udp())
        pkt.serialize()

        lrouter = l3.LogicalRouter(
            id='lrouter1',
            topic='topic1',
            version=1,
            unique_key=22,
            ports=[
                l3.LogicalRouterPort(
                    id='lrouter1-port1',
                    unique_key=55,
                    topic='topic1',
                    mac='aa:bb:cc:dd:ee:ff',
                    network='10.0.0.1/24',
                ),
            ],
        )
        self.app.db_store.update(lrouter)

        event = ofp_event.EventOFPMsgBase(msg=ofproto_parser.OFPPacketIn(
            datapath=mock.Mock(),
            reason=self.app.ofproto.OFPR_PACKET_IN,
            match=ofproto_parser.OFPMatch(reg7=lrouter.ports[0].unique_key, ),
            data=pkt.data,
        ))
        with mock.patch("dragonflow.controller.common."
                        "icmp_error_generator.generate") as icmp_error:
            for _ in range(self.app.conf.router_port_unreach_max_rate * 2):
                self.app.packet_in_handler(event)

            self.assertEqual(self.app.conf.router_port_unreach_max_rate,
                             icmp_error.call_count)
            icmp_error.assert_called_with(icmp.ICMP_DEST_UNREACH,
                                          icmp.ICMP_PORT_UNREACH_CODE,
                                          pkt.data,
                                          pkt=mock.ANY)
Exemplo n.º 27
0
def decode(nfa):
    """This function analyses nflog packet by using os-ken packet library."""

    prefix = ffi.string(libnflog.nflog_get_prefix(nfa))
    packet_hdr = libnflog.nflog_get_msg_packet_hdr(nfa)
    hw_proto = socket.ntohs(packet_hdr.hw_protocol)

    msg = ''
    msg_packet_hwhdr = libnflog.nflog_get_msg_packet_hwhdr(nfa)
    if msg_packet_hwhdr != ffi.NULL:
        packet_hwhdr = ffi.string(msg_packet_hwhdr)
        if len(packet_hwhdr) >= 12:
            dst, src = struct.unpack_from('!6s6s', packet_hwhdr)
            # Dump ethernet packet to get mac addresses
            eth = ethernet.ethernet(addrconv.mac.bin_to_text(dst),
                                    addrconv.mac.bin_to_text(src),
                                    ethertype=hw_proto)
            msg = str(eth)

    # Dump IP packet
    pkt = _payload(nfa)
    if hw_proto == ether_types.ETH_TYPE_IP:
        ip_pkt, proto, data = ipv4.ipv4().parser(pkt)
        msg += str(ip_pkt)
        proto_pkt, a, b = proto.parser(data)
        msg += str(proto_pkt)
    elif hw_proto == ether_types.ETH_TYPE_IPV6:
        ip_pkt, proto, data = ipv6.ipv6().parser(pkt)
        proto_pkt, a, b = proto.parser(data)
        msg += str(proto_pkt)
    elif hw_proto == ether_types.ETH_TYPE_ARP:
        ip_pkt, proto, data = arp.arp().parser(pkt)
        msg += str(ip_pkt)
    else:
        msg += "Does not support hw_proto: " + str(hw_proto)

    return {
        'prefix': encodeutils.safe_decode(prefix),
        'msg': encodeutils.safe_decode(msg)
    }
Exemplo n.º 28
0
    def test_smoke_packet_in(self):
        nd_solicit = packet.Packet()
        eth_src = '01:02:03:04:05:06'
        eth_dst = 'ff:ff:ff:ff:ff:ff'
        src_ip = 'fc00::1'
        dst_ip = 'fc00::2'
        vid = 2
        for protocol in (ethernet.ethernet(eth_dst, eth_src,
                                           ether.ETH_TYPE_8021Q),
                         vlan.vlan(vid=vid, ethertype=ether.ETH_TYPE_IPV6),
                         ipv6.ipv6(src=src_ip,
                                   dst=dst_ip,
                                   nxt=socket.IPPROTO_ICMPV6,
                                   hop_limit=255),
                         icmpv6.icmpv6(
                             type_=icmpv6.ND_NEIGHBOR_SOLICIT,
                             data=icmpv6.nd_neighbor(
                                 dst=src_ip,
                                 option=icmpv6.nd_option_tla(hw_src=eth_src),
                                 res=7))):
            nd_solicit.add_protocol(protocol)
        nd_solicit.serialize()

        fake_dp = FakeDP()
        fake_pipette = Pipette(dpset={})

        class FakeMsg:
            def __init__(self):
                self.datapath = fake_dp
                self.match = {'in_port': FAKEPORT}
                self.data = nd_solicit.data

        class FakePiEv:
            def __init__(self):
                self.msg = FakeMsg()

        fake_pipette = Pipette(dpset={})
        fake_pipette.packet_in_handler(FakePiEv())
        assert fake_dp.msgs
Exemplo n.º 29
0
    def _build_igmp(self):
        dl_dst = '11:22:33:44:55:66'
        dl_src = 'aa:bb:cc:dd:ee:ff'
        dl_type = ether.ETH_TYPE_IP
        e = ethernet(dl_dst, dl_src, dl_type)

        total_length = 20 + igmp._MIN_LEN
        nw_proto = inet.IPPROTO_IGMP
        nw_dst = '11.22.33.44'
        nw_src = '55.66.77.88'
        i = ipv4(total_length=total_length,
                 src=nw_src,
                 dst=nw_dst,
                 proto=nw_proto)

        p = Packet()

        p.add_protocol(e)
        p.add_protocol(i)
        p.add_protocol(self.g)
        p.serialize()
        return p
Exemplo n.º 30
0
    def test_serialize_with_auth_sha1(self):
        pkt = packet.Packet()

        eth_pkt = ethernet.ethernet('08:00:27:d1:95:7c', '08:00:27:ed:54:41')
        pkt.add_protocol(eth_pkt)

        ip_pkt = ipv4.ipv4(src='192.168.57.2',
                           dst='192.168.57.1',
                           tos=192,
                           identification=2960,
                           proto=inet.IPPROTO_UDP)
        pkt.add_protocol(ip_pkt)

        udp_pkt = udp.udp(49152, 3784)
        pkt.add_protocol(udp_pkt)

        auth_cls = bfd.KeyedSHA1(auth_key_id=2,
                                 seq=16817,
                                 auth_key=self.auth_keys[2])

        bfd_pkt = bfd.bfd(ver=1,
                          diag=bfd.BFD_DIAG_NO_DIAG,
                          flags=bfd.BFD_FLAG_AUTH_PRESENT,
                          state=bfd.BFD_STATE_DOWN,
                          detect_mult=3,
                          my_discr=1,
                          your_discr=0,
                          desired_min_tx_interval=1000000,
                          required_min_rx_interval=1000000,
                          required_min_echo_rx_interval=0,
                          auth_cls=auth_cls)

        pkt.add_protocol(bfd_pkt)

        eq_(len(pkt.protocols), 4)

        pkt.serialize()
        eq_(pkt.data, self.data_auth_sha1)