Example #1
0
    def send_lldp(self, datapath: Datapath):
        ports = self.dpset.get_ports(datapath.id)
        for port in ports:
            pkt = packet.Packet()
            pkt.add_protocol(
                ethernet.ethernet(ethertype=ethernet.ether.ETH_TYPE_LLDP,
                                  dst="01:80:C2:00:00:02",
                                  src=port.hw_addr))
            tlv_chassis_id = lldp.ChassisID(
                subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
                chassis_id=(LLDPPacket.CHASSIS_ID_FMT %
                            dpid_to_str(datapath.id)).encode('ascii'))

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

            tlv_ttl = lldp.TTL(ttl=self.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)
            try:
                self._send_packet(datapath, port.port_no, pkt)
            except Exception as e:
                print(str(e))
    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
 def test_json(self):
     chassis_id = lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                                 chassis_id=b'\x00\x01\x30\xf9\xad\xa0')
     port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                           port_id=b'1/1')
     ttl = lldp.TTL(ttl=120)
     port_desc = lldp.PortDescription(
         port_description=b'Summit300-48-Port 1001\x00')
     sys_name = lldp.SystemName(system_name=b'Summit300-48\x00')
     sys_desc = lldp.SystemDescription(
         system_description=b'Summit300-48 - Version 7.4e.1 (Build 5) '
                            + b'by Release_Master 05/27/05 04:53:11\x00')
     sys_cap = lldp.SystemCapabilities(
         system_cap=0x14,
         enabled_cap=0x14)
     man_addr = lldp.ManagementAddress(
         addr_subtype=0x06, addr=b'\x00\x01\x30\xf9\xad\xa0',
         intf_subtype=0x02, intf_num=1001,
         oid='')
     org_spec = lldp.OrganizationallySpecific(
         oui=b'\x00\x12\x0f', subtype=0x02, info=b'\x07\x01\x00')
     end = lldp.End()
     tlvs = (chassis_id, port_id, ttl, port_desc, sys_name,
             sys_desc, sys_cap, man_addr, org_spec, end)
     lldp1 = lldp.lldp(tlvs)
     jsondict = lldp1.to_jsondict()
     lldp2 = lldp.lldp.from_jsondict(jsondict['lldp'])
     eq_(str(lldp1), str(lldp2))
    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)
Example #5
0
def send_lldp_packet(datapath, port_no, data_size):
    # data_size 0~1440
    ofp = datapath.ofproto
    parser = datapath.ofproto_parser
    pkt = packet.Packet()
    pkt.add_protocol(ethernet.ethernet(ethertype=ether_types.ETH_TYPE_LLDP))
    tlv_chassis_id = lldp.ChassisID(
        subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
        chassis_id=str(datapath.id))
    tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_LOCALLY_ASSIGNED,
                              port_id=str(port_no))
    tlv_ttl = lldp.TTL(ttl=10)
    tlv_end = lldp.End()
    tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_end)
    pkt.add_protocol(lldp.lldp(tlvs))
    pkt.serialize()
    data = pkt.data  # 60bytes
    # bytes in one packet ,can set 0~1440 because MTU Max is 1500
    data = data + bytearray(1440)
    actions = [parser.OFPActionOutput(port=port_no)]
    match = datapath.ofproto_parser.OFPMatch(
        in_port=datapath.ofproto.OFPP_CONTROLLER)
    out = parser.OFPPacketOut(datapath=datapath,
                              buffer_id=ofp.OFP_NO_BUFFER,
                              match=match,
                              actions=actions,
                              data=data)

    datapath.send_msg(out)
Example #6
0
    def send_lldp(self, datapath, port_no, hw_addr):
        ofproto = datapath.ofproto
        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_LLDP,
                              src=hw_addr,
                              dst=lldp.LLDP_MAC_NEAREST_BRIDGE))
        chassis = lldp.ChassisID(subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
                                 chassis_id=str(datapath.id))
        port = lldp.PortID(subtype=lldp.PortID.SUB_LOCALLY_ASSIGNED,
                           port_id=str(port_no))
        ttl = lldp.TTL(ttl=10)
        end = lldp.End()
        tlvs = (chassis, port, ttl, end)
        pkt.add_protocol(lldp.lldp(tlvs))
        pkt.serialize()

        data = pkt.data
        parser = datapath.ofproto_parser
        actions = [parser.OFPActionOutput(port=port_no)]
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        datapath.send_msg(out)
Example #7
0
    def send_lldp_packet(self, datapath, port_no, hw_addr):
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        timestamp = time.time()
        pkt = packet.Packet()
        pkt.add_protocol(
            ethernet.ethernet(ethertype=self.lldp_type,
                              src=hw_addr,
                              dst=lldp.LLDP_MAC_NEAREST_BRIDGE))

        tlv_chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
            chassis_id=str(datapath.id))
        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_LOCALLY_ASSIGNED,
                                  port_id=str(port_no))
        tlv_ttl = lldp.TTL(ttl=10)
        tlv_time = lldp.TimeStamp(timestamp=timestamp)
        tlv_end = lldp.End()
        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_time, tlv_end)
        pkt.add_protocol(lldp.lldp(tlvs))
        pkt.serialize()
        data = pkt.data
        actions = [parser.OFPActionOutput(port_no)]
        out = parser.OFPPacketOut(datapath=datapath,
                                  buffer_id=ofproto.OFP_NO_BUFFER,
                                  in_port=ofproto.OFPP_CONTROLLER,
                                  actions=actions,
                                  data=data)
        datapath.send_msg(out)
Example #8
0
    def test_to_string(self):
        chassis_id = lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                                    chassis_id=b'\x00\x04\x96\x1f\xa7\x26')
        port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                              port_id=b'1/3')
        ttl = lldp.TTL(ttl=120)
        end = lldp.End()
        tlvs = (chassis_id, port_id, ttl, end)
        lldp_pkt = lldp.lldp(tlvs)

        chassis_id_values = {
            'subtype': lldp.ChassisID.SUB_MAC_ADDRESS,
            'chassis_id': b'\x00\x04\x96\x1f\xa7\x26',
            'len': chassis_id.len,
            'typelen': chassis_id.typelen
        }
        _ch_id_str = ','.join([
            '%s=%s' % (k, repr(chassis_id_values[k]))
            for k, v in inspect.getmembers(chassis_id)
            if k in chassis_id_values
        ])
        tlv_chassis_id_str = '%s(%s)' % (lldp.ChassisID.__name__, _ch_id_str)

        port_id_values = {
            'subtype': port_id.subtype,
            'port_id': port_id.port_id,
            'len': port_id.len,
            'typelen': port_id.typelen
        }
        _port_id_str = ','.join([
            '%s=%s' % (k, repr(port_id_values[k]))
            for k, v in inspect.getmembers(port_id) if k in port_id_values
        ])
        tlv_port_id_str = '%s(%s)' % (lldp.PortID.__name__, _port_id_str)

        ttl_values = {'ttl': ttl.ttl, 'len': ttl.len, 'typelen': ttl.typelen}
        _ttl_str = ','.join([
            '%s=%s' % (k, repr(ttl_values[k]))
            for k, v in inspect.getmembers(ttl) if k in ttl_values
        ])
        tlv_ttl_str = '%s(%s)' % (lldp.TTL.__name__, _ttl_str)

        end_values = {'len': end.len, 'typelen': end.typelen}
        _end_str = ','.join([
            '%s=%s' % (k, repr(end_values[k]))
            for k, v in inspect.getmembers(end) if k in end_values
        ])
        tlv_end_str = '%s(%s)' % (lldp.End.__name__, _end_str)

        _tlvs_str = '(%s, %s, %s, %s)'
        tlvs_str = _tlvs_str % (tlv_chassis_id_str, tlv_port_id_str,
                                tlv_ttl_str, tlv_end_str)

        _lldp_str = '%s(tlvs=%s)'
        lldp_str = _lldp_str % (lldp.lldp.__name__, tlvs_str)

        eq_(str(lldp_pkt), lldp_str)
        eq_(repr(lldp_pkt), lldp_str)
    def test_serialize_without_ethernet(self):
        tlv_chassis_id = lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                                        chassis_id=b'\x00\x04\x96\x1f\xa7\x26')
        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)

        eq_(lldp_pkt.serialize(None, None),
            self.data[ethernet.ethernet._MIN_LEN:])
 def test_json(self):
     chassis_id = lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                                 chassis_id=b'\x00\x04\x96\x1f\xa7\x26')
     port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                           port_id=b'1/3')
     ttl = lldp.TTL(ttl=120)
     end = lldp.End()
     tlvs = (chassis_id, port_id, ttl, end)
     lldp1 = lldp.lldp(tlvs)
     jsondict = lldp1.to_jsondict()
     lldp2 = lldp.lldp.from_jsondict(jsondict['lldp'])
     eq_(str(lldp1), str(lldp2))
Example #11
0
 def __init__(self, switch):
     self.switch = switch
     e = ethernet.ethernet(src='12:34:56:ab:cd:ef',
                           dst='00:11:22:33:44:55',
                           ethertype=35020)
     lldp_ch = lldp.ChassisID(subtype=7, chassis_id=str(switch.id))
     lldp_port = lldp.PortID(subtype=7, port_id='Openflow')
     lldp_ttl = lldp.TTL(ttl=1024)
     lldp_end = lldp.End()
     l = lldp.lldp([lldp_ch, lldp_port, lldp_ttl, lldp_end])
     p = packet.Packet()
     p.add_protocol(e)
     p.add_protocol(l)
     self.packet = p
Example #12
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(
            subtype=lldp.ChassisID.SUB_CHASSIS_COMPONENT,
            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)])
Example #13
0
    def lldp_packet(dpid,
                    port_no,
                    dl_addr,
                    ttl,
                    vport_no=ofproto_v1_0.OFPP_NONE):
        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))

        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)
        # Add LLDPDU for OXP.
        if CONF.oxp_role is not None:
            tlv_domain_id = lldp.DomainID(
                subtype=lldp.DomainID.SUB_LOCALLY_ASSIGNED,
                domain_id=LLDPPacket.DOMAIN_ID_FMT %
                dpid_to_str(CONF.oxp_domain_id))

            tlv_vport_id = lldp.VPortID(
                subtype=lldp.VPortID.SUB_PORT_COMPONENT,
                vport_id=struct.pack(LLDPPacket.VPORT_ID_STR, vport_no))

            tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_domain_id,
                    tlv_vport_id, tlv_end)

        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)

        pkt.serialize()
        return pkt.data
Example #14
0
def prepare_lldp_packet(node, port, vlan_id):
    """
        Prepare the LLDP frame to be used by PacketOut
        Args:
            node: destination node
            port: destination port
            vlan_id: vlan tag to be added to pkt
        Returns:
            an Ethernet+LLDP frame (data field of PacketOut)
    """

    pkt = packet.Packet()
    # Generate Ethernet frame
    dst = lldp.LLDP_MAC_NEAREST_BRIDGE
    src = 'ca:fe:ca:fe:ca:fe'
    vlan_pkt = None

    if vlan_id > 1:
        ethertype = ether.ETH_TYPE_8021Q
        vlan_pkt = vlan.vlan(vid=vlan_id, ethertype=ether.ETH_TYPE_LLDP)
    else:
        ethertype = ether.ETH_TYPE_LLDP

    eth_pkt = ethernet.ethernet(dst, src, ethertype)
    pkt.add_protocol(eth_pkt)

    if vlan_id > 1:
        pkt.add_protocol(vlan_pkt)

    # Generate LLDP packet
    dp = '%016x' % node.dpid
    chassis_subtype = lldp.ChassisID.SUB_LOCALLY_ASSIGNED
    tlv_chassis_id = lldp.ChassisID(subtype=chassis_subtype,
                                    chassis_id=dp)
    tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT,
                              port_id=(b'%s' % port))
    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)
    pkt.serialize()

    return pkt
Example #15
0
def lldp_beacon(eth_src,
                chassis_id,
                port_id,
                ttl,
                org_tlvs=None,
                system_name=None,
                port_descr=None):
    """Return an LLDP frame suitable for a host/access port.

    Args:
        eth_src (str): source Ethernet MAC address.
        chassis_id (str): Chassis ID.
        port_id (int): port ID,
        TTL (int): TTL for payload.
        org_tlvs (list): list of tuples of (OUI, subtype, info).
    Returns:
        ryu.lib.packet.ethernet: Ethernet packet with header.
    """
    pkt = build_pkt_header(None, eth_src, lldp.LLDP_MAC_NEAREST_BRIDGE,
                           valve_of.ether.ETH_TYPE_LLDP)
    tlvs = [
        lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                       chassis_id=addrconv.mac.text_to_bin(chassis_id)),
        lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                    port_id=str(port_id).encode('utf-8')),
        lldp.TTL(ttl=ttl)
    ]
    for tlv, info_name, info in ((lldp.SystemName, 'system_name', system_name),
                                 (lldp.PortDescription, 'port_description',
                                  port_descr)):
        if info is not None:
            info_args = {info_name: info.encode('UTF-8')}
            tlvs.append(tlv(**info_args))
    if org_tlvs is not None:
        for tlv_oui, tlv_subtype, tlv_info in org_tlvs:
            tlvs.append(
                lldp.OrganizationallySpecific(oui=tlv_oui,
                                              subtype=tlv_subtype,
                                              info=tlv_info))
    tlvs.append(lldp.End())
    lldp_pkt = lldp.lldp(tlvs)
    pkt.add_protocol(lldp_pkt)
    pkt.serialize()
    return pkt
Example #16
0
    def send_lldp_packet(self, datapath, port, hw_addr, ttl):
        #表示對應的 ofproto module
        ofproto = datapath.ofproto
        #表示對應的 ofproto_parser module
        ofp_parser = datapath.ofproto_parser

        #產生一個封包object
        pkt = packet.Packet()
        #ethertype: LLDP
        #src: 發送 LLDP 的 switch port 的 mac
        #dst: LLDP_MAC_NEAREST_BRIDGE
        pkt.add_protocol(
            ethernet.ethernet(ethertype=ether_types.ETH_TYPE_LLDP,
                              src=hw_addr,
                              dst=lldp.LLDP_MAC_NEAREST_BRIDGE))

        #chassis_id: 發送 LLDP 封包的 switch id
        chassis_id = lldp.ChassisID(
            subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
            chassis_id=str(datapath.id))
        #port_id: 發送 LLDP 封包的 switch port id
        port_id = lldp.PortID(subtype=lldp.PortID.SUB_LOCALLY_ASSIGNED,
                              port_id=str(port))

        #Time to live
        ttl = lldp.TTL(ttl=10)
        end = lldp.End()
        tlvs = (chassis_id, port_id, ttl, end)
        pkt.add_protocol(lldp.lldp(tlvs))
        pkt.serialize()

        #self.logger.info("packet-out %s" % pkt)

        data = pkt.data
        actions = [ofp_parser.OFPActionOutput(port=port)]
        out = ofp_parser.OFPPacketOut(datapath=datapath,
                                      buffer_id=ofproto.OFP_NO_BUFFER,
                                      in_port=ofproto.OFPP_CONTROLLER,
                                      actions=actions,
                                      data=data)
        datapath.send_msg(out)
Example #17
0
    def create_discovery_packet (self, dpid, port_no, dl_addr):
        """
        Build discovery packet
        """
        CHASSIS_ID_PREFIX = 'dpid:'
        #CHASSIS_ID_PREFIX_LEN = len(CHASSIS_ID_PREFIX)
        CHASSIS_ID_FMT = CHASSIS_ID_PREFIX + '%s'
        
        PORT_ID_STR = '!I'      # uint32_t
        
        
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = dl_addr
        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_LOCALLY_ASSIGNED,
            chassis_id=CHASSIS_ID_FMT %
            dpid_to_str(dpid))
        
        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT,
                                  port_id=struct.pack(
                                      PORT_ID_STR,
                                      port_no))

        
        
        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)

        pkt.serialize()
        return pkt.data
Example #18
0
    def test_serialize(self):
        pkt = packet.Packet()

        dst = lldp.LLDP_MAC_NEAREST_BRIDGE
        src = '\x00\x04\x96\x1f\xa7\x26'
        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=src)
        tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                                  port_id='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()
        eq_(pkt.data, self.data)
Example #19
0
    def new_dp(self, dp):

        # Let's go with LLDP for topology build-up
        # priority has 16 bits, here use TOP PRIORITY
        match = dp.ofproto_parser.OFPMatch(eth_type=ether_types.ETH_TYPE_LLDP)
        actions = [
            dp.ofproto_parser.OFPActionOutput(dp.ofproto.OFPP_CONTROLLER)
        ]
        inst = [
            dp.ofproto_parser.OFPInstructionActions(
                dp.ofproto.OFPIT_APPLY_ACTIONS, actions)
        ]
        flow_mod = dp.ofproto_parser.OFPFlowMod(datapath=dp,
                                                table_id=0,
                                                priority=2**16 - 1,
                                                match=match,
                                                instructions=inst)
        dp.send_msg(flow_mod)

        layer_lldp = lldp.lldp(tlvs=[
            lldp.ChassisID(subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
                           chassis_id=str(dp.id)),
            lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT, port_id='0'),
            lldp.TTL(ttl=1),
            lldp.End()
        ])
        layer_ether = ethernet.ethernet(dst=lldp.LLDP_MAC_NEAREST_BRIDGE,
                                        src=self.dps[dp.id].hwaddr,
                                        ethertype=ether.ETH_TYPE_LLDP)
        pkt = packet.Packet()
        pkt.add_protocol(layer_ether)
        pkt.add_protocol(layer_lldp)
        pkt.serialize()

        print("depositing new dp............")
        self.dps[dp.id].this_dp = dp
        self.dps[dp.id].prober = pkt
Example #20
0
    def lldp_packet(dpid, port_no, queue_id, 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()
        ############################################################################################
        # ADD: Organisationally specific TLV, which consists of the link data
        # dpid, port_no, queue
        # ########################################################################################## 
        tlv_link_data_1 = lldp.OrganizationallySpecific(oui='1', subtype=0, info=str(dpid))
        tlv_link_data_2 = lldp.OrganizationallySpecific(oui='1', subtype=0, info=str(port_no))
        tlv_link_data_3 = lldp.OrganizationallySpecific(oui='1', subtype=0, info=str(queue_id))
        tlv_link_data_4 = lldp.OrganizationallySpecific(oui='1', subtype=0, info=str(Decimal(time.time())))
        ############################################################################################
        tlvs = (tlv_chassis_id, tlv_port_id, tlv_ttl, tlv_link_data_1, tlv_link_data_2,
        tlv_link_data_3, tlv_link_data_4, tlv_end)
        lldp_pkt = lldp.lldp(tlvs)
        pkt.add_protocol(lldp_pkt)
        pkt.serialize()
        return pkt.data
Example #21
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()
        eq_(pkt.data, self.data)
Example #22
0
	def _upstream_collector(self, pkt):
		(version, msg_type, msg_len, xid) = ofproto_parser.header(pkt)

		# Switch configuration messages
		if msg_type == ofproto_v1_0.OFPT_FEATURES_REPLY:
			# print("Reply xid: " + hex(xid))
			msg = ofproto_v1_0_parser.OFPSwitchFeatures.parser(self.datapath, version, msg_type, msg_len, xid, pkt)
			match = ofproto_v1_0_parser.OFPMatch(dl_type=ETH_TYPE_LLDP, dl_dst=lldp.LLDP_MAC_NEAREST_BRIDGE)
			cookie = 0
			command = ofproto_v1_0.OFPFC_ADD
			idle_timeout = hard_timeout = 0
			priority = 0
			buffer_id = ofproto_v1_0.OFP_NO_BUFFER
			out_port = ofproto_v1_0.OFPP_NONE
			flags = 0
			actions = [ofproto_v1_0_parser.OFPActionOutput(ofproto_v1_0.OFPP_CONTROLLER)]
			mod = ofproto_v1_0_parser.OFPFlowMod(self.datapath, match, cookie, command, idle_timeout, hard_timeout, priority, buffer_id, out_port, flags, actions)
			mod.serialize()

			self.id = msg.datapath_id
			self.ports = msg.ports

			# print(str(self.id) + " : Receive Features Reply Message")
			# print(msg)

			for port in self.ports.values():
				db_message = {"switch_id": hex(self.id),
							  "port_no": port.port_no,
							  "hw_addr": port.hw_addr,
							  "timestamp": datetime.datetime.utcnow()}

				try:
					self.db.switch_port.insert_one(db_message)
				except:
					if(self.id != None):
						print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(hex(self.id)) + "] --- Failed to write data into database")
					else:
						print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(self.id) + "] --- Failed to write data into database")

				pkt_lldp = packet.Packet()

				dst = BROADCAST_STR
				src = port.hw_addr
				ethertype = ETH_TYPE_LLDP
				eth_pkt = ethernet.ethernet(dst, src, ethertype)
				pkt_lldp.add_protocol(eth_pkt)

				tlv_chassis_id = lldp.ChassisID(
					subtype=lldp.ChassisID.SUB_LOCALLY_ASSIGNED,
					chassis_id='dpid:%s' % dpid_to_str(self.id))

				tlv_port_id = lldp.PortID(subtype=lldp.PortID.SUB_PORT_COMPONENT,
										  port_id=struct.pack('!I', port.port_no))

				tlv_ttl = lldp.TTL(ttl=120)
				tlv_desc = lldp.PortDescription(port_description="ProxyTopologyMonitorLLDP")
				tlv_end = lldp.End()

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

				pkt_lldp.serialize()

				actions = [ofproto_v1_0_parser.OFPActionOutput(port.port_no)]
				out = ofproto_v1_0_parser.OFPPacketOut(
					datapath=self.datapath, in_port=ofproto_v1_0.OFPP_CONTROLLER,
					buffer_id=ofproto_v1_0.OFP_NO_BUFFER, actions=actions,
					data=pkt_lldp.data)
				out.serialize()

				try:
					self.switch_socket.send(out.buf)
				except:
					if(self.id != None):
						print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(hex(self.id)) + "] --- Broken Pipe (Downstream : LLDP Message)")
					else:
						print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(self.id) + "] --- Broken Pipe (Downstream : LLDP Message)")
					# self._close()
					pass

		elif msg_type == ofproto_v1_0.OFPT_STATS_REPLY:
			msg = ofproto_v1_0_parser.OFPPortStatsReply.parser(self.datapath, version, msg_type, msg_len, xid, pkt)
			if(type(msg) is ofproto_v1_0_parser.OFPFlowStatsReply):
				# print(str(self.id) + " : Receive Flow Stats Message")
				# print(msg.body)

				for flow in msg.body:
					db_message = {"switch": hex(self.id),
								  "message": {
									  "header": {
										  "version": msg.version,
										  "type": msg.msg_type,
										  "length": msg.msg_len,
										  "xid": msg.xid
									  },
									  "match": {
										  "wildcards": flow.match.wildcards,
										  "in_port": flow.match.in_port,
										  "dl_src": mac.haddr_to_str(flow.match.dl_src),
										  "dl_dst": mac.haddr_to_str(flow.match.dl_dst),
										  "dl_vlan": flow.match.dl_vlan,
										  "dl_vlan_pcp": flow.match.dl_vlan_pcp,
										  "dl_type": flow.match.dl_type,
										  "nw_tos": flow.match.nw_tos,
										  "nw_proto": flow.match.nw_proto,
										  "nw_src": ip.ipv4_to_str(flow.match.nw_src),
										  "nw_dst": ip.ipv4_to_str(flow.match.nw_dst),
										  "tp_src": flow.match.tp_src,
										  "tp_dst": flow.match.tp_dst
									  },
									  "cookie": flow.cookie,
									  "idle_timeout": flow.idle_timeout,
									  "hard_timeout": flow.hard_timeout,
									  "priority": flow.priority,
									  "flags": msg.flags,
									  "actions": []
								  },
								  "timestamp": datetime.datetime.utcnow()}

					for action in flow.actions:
						db_message["message"]["actions"].append(vars(action));

					try:
						self.db.flow_stats.insert_one(db_message)
					except:
						if(self.id != None):
							print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(hex(self.id)) + "] --- Failed to write data into database")
						else:
							print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(self.id) + "] --- Failed to write data into database")
						pass

			if(type(msg) is ofproto_v1_0_parser.OFPPortStatsReply):
				# print(str(self.id) + " : Receive Port Stats Message")
				# print(msg.body)

				for port in msg.body:
					# print(port)
					db_message = {"switch": hex(self.id),
								  "port_no": port.port_no,
								  "rx_packets": port.rx_packets,
								  "tx_packets": port.tx_packets,
								  "rx_bytes": port.rx_bytes,
								  "tx_bytes": port.tx_bytes,
								  "rx_dropped": port.rx_dropped,
								  "tx_dropped": port.tx_dropped,
								  "rx_errors": port.rx_errors,
								  "tx_errors": port.tx_errors,
								  "rx_frame_err": port.rx_frame_err,
								  "rx_over_err": port.rx_over_err,
								  "rx_crc_err": port.rx_crc_err,
								  "collisions": port.collisions,
								  "timestamp": datetime.datetime.utcnow()}

					try:
						self.db.port_stats.insert_one(db_message)
					except:
						if(self.id != None):
							print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(hex(self.id)) + "] --- Failed to write data into database")
						else:
							print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(self.id) + "] --- Failed to write data into database")

				pass

		# Asynchronous messages
		elif msg_type == ofproto_v1_0.OFPT_PACKET_IN:
			msg = ofproto_v1_0_parser.OFPPacketIn.parser(self.datapath, version, msg_type, msg_len, xid, pkt)
			pkt_msg = packet.Packet(msg.data)

			if pkt_msg.get_protocol(ethernet.ethernet).ethertype == ETH_TYPE_LLDP:
				lldp_msg = pkt_msg.get_protocol(lldp.lldp)

				if lldp_msg != None:
					if lldp_msg.tlvs[3].tlv_info == "ProxyTopologyMonitorLLDP":

						(port,) = struct.unpack('!I', lldp_msg.tlvs[1].port_id)
						switch_src = str_to_dpid(lldp_msg.tlvs[0].chassis_id[5:])

						# print(str(self.id) + " : Receive Proxy LLDP Packet")
						# print(lldp_msg)

						# Write to database
						try:
							self.db.topology.insert_one({"switch_dst": hex(self.id),
													 	 "port_dst": port,
													 	 "switch_src": hex(switch_src),
													 	 "port_src": msg.in_port,
													 	 "timestamp": datetime.datetime.utcnow()})
						except:
							if(self.id != None):
								print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(hex(self.id)) + "] --- Failed to write data into database")
							else:
								print(datetime.datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S') + " : ERROR [" + str(self.id) + "] --- Failed to write data into database")

						return

					elif lldp_msg.tlvs[3].tlv_info != "ProxyTopologyMonitorLLDP":
						# print(lldp_msg)
						# print("Controller LLDP packet")
						pass
    def test_to_string(self):
        chassis_id = lldp.ChassisID(subtype=lldp.ChassisID.SUB_MAC_ADDRESS,
                                    chassis_id=b'\x00\x01\x30\xf9\xad\xa0')
        port_id = lldp.PortID(subtype=lldp.PortID.SUB_INTERFACE_NAME,
                              port_id=b'1/1')
        ttl = lldp.TTL(ttl=120)
        port_desc = lldp.PortDescription(
            port_description=b'Summit300-48-Port 1001\x00')
        sys_name = lldp.SystemName(system_name=b'Summit300-48\x00')
        sys_desc = lldp.SystemDescription(
            system_description=b'Summit300-48 - Version 7.4e.1 (Build 5) '
                               + b'by Release_Master 05/27/05 04:53:11\x00')
        sys_cap = lldp.SystemCapabilities(
            system_cap=0x14,
            enabled_cap=0x14)
        man_addr = lldp.ManagementAddress(
            addr_subtype=0x06, addr=b'\x00\x01\x30\xf9\xad\xa0',
            intf_subtype=0x02, intf_num=1001,
            oid='')
        org_spec = lldp.OrganizationallySpecific(
            oui=b'\x00\x12\x0f', subtype=0x02, info=b'\x07\x01\x00')
        end = lldp.End()
        tlvs = (chassis_id, port_id, ttl, port_desc, sys_name,
                sys_desc, sys_cap, man_addr, org_spec, end)
        lldp_pkt = lldp.lldp(tlvs)

        # ChassisID string
        chassis_id_values = {'subtype': lldp.ChassisID.SUB_MAC_ADDRESS,
                             'chassis_id': b'\x00\x01\x30\xf9\xad\xa0',
                             'len': chassis_id.len,
                             'typelen': chassis_id.typelen}
        _ch_id_str = ','.join(['%s=%s' % (k, repr(chassis_id_values[k]))
                               for k, v in inspect.getmembers(chassis_id)
                               if k in chassis_id_values])
        tlv_chassis_id_str = '%s(%s)' % (lldp.ChassisID.__name__, _ch_id_str)

        # PortID string
        port_id_values = {'subtype': port_id.subtype,
                          'port_id': port_id.port_id,
                          'len': port_id.len,
                          'typelen': port_id.typelen}
        _port_id_str = ','.join(['%s=%s' % (k, repr(port_id_values[k]))
                                 for k, v in inspect.getmembers(port_id)
                                 if k in port_id_values])
        tlv_port_id_str = '%s(%s)' % (lldp.PortID.__name__, _port_id_str)

        # TTL string
        ttl_values = {'ttl': ttl.ttl,
                      'len': ttl.len,
                      'typelen': ttl.typelen}
        _ttl_str = ','.join(['%s=%s' % (k, repr(ttl_values[k]))
                             for k, v in inspect.getmembers(ttl)
                             if k in ttl_values])
        tlv_ttl_str = '%s(%s)' % (lldp.TTL.__name__, _ttl_str)

        # PortDescription string
        port_desc_values = {'tlv_info': port_desc.tlv_info,
                            'len': port_desc.len,
                            'typelen': port_desc.typelen}
        _port_desc_str = ','.join(['%s=%s' % (k, repr(port_desc_values[k]))
                                   for k, v in inspect.getmembers(port_desc)
                                   if k in port_desc_values])
        tlv_port_desc_str = '%s(%s)' % (lldp.PortDescription.__name__,
                                        _port_desc_str)

        # SystemName string
        sys_name_values = {'tlv_info': sys_name.tlv_info,
                           'len': sys_name.len,
                           'typelen': sys_name.typelen}
        _system_name_str = ','.join(['%s=%s' % (k, repr(sys_name_values[k]))
                                     for k, v in inspect.getmembers(sys_name)
                                     if k in sys_name_values])
        tlv_system_name_str = '%s(%s)' % (lldp.SystemName.__name__,
                                          _system_name_str)

        # SystemDescription string
        sys_desc_values = {'tlv_info': sys_desc.tlv_info,
                           'len': sys_desc.len,
                           'typelen': sys_desc.typelen}
        _sys_desc_str = ','.join(['%s=%s' % (k, repr(sys_desc_values[k]))
                                  for k, v in inspect.getmembers(sys_desc)
                                  if k in sys_desc_values])
        tlv_sys_desc_str = '%s(%s)' % (lldp.SystemDescription.__name__,
                                       _sys_desc_str)

        # SystemCapabilities string
        sys_cap_values = {'system_cap': 0x14,
                          'enabled_cap': 0x14,
                          'len': sys_cap.len,
                          'typelen': sys_cap.typelen}
        _sys_cap_str = ','.join(['%s=%s' % (k, repr(sys_cap_values[k]))
                                 for k, v in inspect.getmembers(sys_cap)
                                 if k in sys_cap_values])
        tlv_sys_cap_str = '%s(%s)' % (lldp.SystemCapabilities.__name__,
                                      _sys_cap_str)

        # ManagementAddress string
        man_addr_values = {'addr_subtype': 0x06,
                           'addr': b'\x00\x01\x30\xf9\xad\xa0',
                           'addr_len': man_addr.addr_len,
                           'intf_subtype': 0x02,
                           'intf_num': 1001,
                           'oid': '',
                           'oid_len': man_addr.oid_len,
                           'len': man_addr.len,
                           'typelen': man_addr.typelen}
        _man_addr_str = ','.join(['%s=%s' % (k, repr(man_addr_values[k]))
                                  for k, v in inspect.getmembers(man_addr)
                                  if k in man_addr_values])
        tlv_man_addr_str = '%s(%s)' % (lldp.ManagementAddress.__name__,
                                       _man_addr_str)

        # OrganizationallySpecific string
        org_spec_values = {'oui': b'\x00\x12\x0f',
                           'subtype': 0x02,
                           'info': b'\x07\x01\x00',
                           'len': org_spec.len,
                           'typelen': org_spec.typelen}
        _org_spec_str = ','.join(['%s=%s' % (k, repr(org_spec_values[k]))
                                  for k, v in inspect.getmembers(org_spec)
                                  if k in org_spec_values])
        tlv_org_spec_str = '%s(%s)' % (lldp.OrganizationallySpecific.__name__,
                                       _org_spec_str)

        # End string
        end_values = {'len': end.len,
                      'typelen': end.typelen}
        _end_str = ','.join(['%s=%s' % (k, repr(end_values[k]))
                             for k, v in inspect.getmembers(end)
                             if k in end_values])
        tlv_end_str = '%s(%s)' % (lldp.End.__name__, _end_str)

        # tlvs string
        _tlvs_str = '(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
        tlvs_str = _tlvs_str % (tlv_chassis_id_str,
                                tlv_port_id_str,
                                tlv_ttl_str,
                                tlv_port_desc_str,
                                tlv_system_name_str,
                                tlv_sys_desc_str,
                                tlv_sys_cap_str,
                                tlv_man_addr_str,
                                tlv_org_spec_str,
                                tlv_end_str)

        # lldp string
        _lldp_str = '%s(tlvs=%s)'
        lldp_str = _lldp_str % (lldp.lldp.__name__,
                                tlvs_str)

        eq_(str(lldp_pkt), lldp_str)
        eq_(repr(lldp_pkt), lldp_str)