2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.openflowplugin.applications.topology.lldp.utils;
10 import com.google.common.base.Preconditions;
11 import com.google.common.hash.HashCode;
12 import com.google.common.hash.HashFunction;
13 import com.google.common.hash.Hasher;
14 import com.google.common.hash.Hashing;
15 import java.lang.management.ManagementFactory;
16 import java.nio.ByteBuffer;
17 import java.nio.charset.Charset;
18 import java.nio.charset.StandardCharsets;
19 import java.util.Arrays;
20 import java.util.Optional;
21 import org.apache.commons.lang3.ArrayUtils;
22 import org.opendaylight.mdsal.eos.binding.api.Entity;
23 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
24 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
25 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
26 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
27 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
28 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
29 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
30 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkDiscoveredBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public final class LLDPDiscoveryUtils {
47 private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
49 private static final short MINIMUM_LLDP_SIZE = 61;
50 public static final short ETHERNET_TYPE_VLAN = (short) 0x8100;
51 public static final short ETHERNET_TYPE_LLDP = (short) 0x88cc;
52 private static final short ETHERNET_TYPE_OFFSET = 12;
53 private static final short ETHERNET_VLAN_OFFSET = ETHERNET_TYPE_OFFSET + 4;
54 private static final String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
56 private LLDPDiscoveryUtils() {
59 public static String macToString(byte[] mac) {
60 StringBuilder builder = new StringBuilder();
61 for (int i = 0; i < mac.length; i++) {
62 builder.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : ""));
65 return builder.toString();
69 * Returns the encoded in custom TLV for the given lldp.
71 * @param payload lldp payload
72 * @return nodeConnectorId - encoded in custom TLV of given lldp
73 * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
75 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
76 return lldpToNodeConnectorRef(payload, false);
80 * Returns the encoded in custom TLV for the given lldp.
82 * @param payload lldp payload
83 * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
84 * @return nodeConnectorId - encoded in custom TLV of given lldp
86 @SuppressWarnings("checkstyle:IllegalCatch")
87 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck) {
88 NodeConnectorRef nodeConnectorRef = null;
90 if (isLLDP(payload)) {
91 Ethernet ethPkt = new Ethernet();
93 ethPkt.deserialize(payload, 0, payload.length * NetUtils.NUM_BITS_IN_A_BYTE);
94 } catch (PacketException e) {
95 LOG.warn("Failed to decode LLDP packet", e);
96 return nodeConnectorRef;
99 LLDP lldp = (LLDP) ethPkt.getPayload();
102 NodeId srcNodeId = null;
103 NodeConnectorId srcNodeConnectorId = null;
105 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
106 if (systemIdTLV != null) {
107 String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
108 srcNodeId = new NodeId(srcNodeIdString);
110 throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
113 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(LLDPTLV.createPortSubTypeCustomTLVKey());
114 if (nodeConnectorIdLldptlv != null) {
115 srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
116 nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
118 throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
121 if (useExtraAuthenticatorCheck) {
122 boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
124 LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
126 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
130 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
131 .child(Node.class, new NodeKey(srcNodeId))
132 .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
134 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
135 } catch (Exception e) {
136 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
139 return nodeConnectorRef;
143 * Gets an extra authenticator for lldp security.
145 * @param nodeConnectorId the NodeConnectorId
146 * @return extra authenticator for lldp security
148 public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId) {
150 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
151 finalKey = LLDPActivator.getLldpSecureKey();
153 finalKey = ManagementFactory.getRuntimeMXBean().getName();
155 final String pureValue = nodeConnectorId + finalKey;
157 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
158 HashFunction hashFunction = Hashing.md5();
159 Hasher hasher = hashFunction.newHasher();
160 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
161 return hashedValue.asBytes();
164 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
165 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
167 EntityOwnershipState state = null;
168 Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
169 if (status.isPresent()) {
170 state = status.get();
172 LOG.error("Fetching ownership status failed for node {}", nodeId);
174 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
177 public static org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819
178 .LinkDiscovered toLLDPLinkDiscovered(Link link) {
179 return new LinkDiscoveredBuilder()
180 .setSource(getNodeConnectorRefFromLink(link.getSource().getSourceTp(),
181 link.getSource().getSourceNode()))
182 .setDestination(getNodeConnectorRefFromLink(link.getDestination().getDestTp(),
183 link.getDestination().getDestNode()))
187 private static boolean isLLDP(final byte[] packet) {
188 if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
192 final ByteBuffer bb = ByteBuffer.wrap(packet);
194 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
196 if (ethernetType == ETHERNET_TYPE_VLAN) {
197 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
200 return ethernetType == ETHERNET_TYPE_LLDP;
203 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
204 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
205 boolean secAuthenticatorOk = false;
206 if (hashLldptlv != null) {
207 byte[] rawTlvValue = hashLldptlv.getValue();
208 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
209 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
210 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
212 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
215 return secAuthenticatorOk;
218 private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
219 final String nodeId) {
220 Entity entity = createNodeEntity(nodeId);
221 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
223 if (ownershipStatus.isPresent()) {
224 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
226 return ownershipStatus;
229 private static Entity createNodeEntity(final String nodeId) {
230 return new Entity(SERVICE_ENTITY_TYPE, nodeId);
233 private static NodeConnectorRef getNodeConnectorRefFromLink(final TpId tpId, final org.opendaylight.yang.gen.v1.urn
234 .tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId) {
235 String nodeConnectorId = tpId.getValue();
236 InstanceIdentifier<NodeConnector> nciid
237 = InstanceIdentifier.builder(Nodes.class)
240 new NodeKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
244 new NodeConnectorKey(new NodeConnectorId(nodeConnectorId)))
246 return new NodeConnectorRef(nciid);