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.opendaylight.mdsal.eos.binding.api.Entity;
22 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
23 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
24 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
25 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
26 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
27 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
28 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
29 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkDiscoveredBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public final class LLDPDiscoveryUtils {
46 private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
48 private static final short MINIMUM_LLDP_SIZE = 61;
49 public static final short ETHERNET_TYPE_VLAN = (short) 0x8100;
50 public static final short ETHERNET_TYPE_LLDP = (short) 0x88cc;
51 private static final short ETHERNET_TYPE_OFFSET = 12;
52 private static final short ETHERNET_VLAN_OFFSET = ETHERNET_TYPE_OFFSET + 4;
53 private static final String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
55 private LLDPDiscoveryUtils() {
58 public static String macToString(byte[] mac) {
59 StringBuilder builder = new StringBuilder();
60 for (int i = 0; i < mac.length; i++) {
61 builder.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : ""));
64 return builder.toString();
68 * Returns the encoded in custom TLV for the given lldp.
70 * @param payload lldp payload
71 * @return nodeConnectorId - encoded in custom TLV of given lldp
72 * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
74 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
75 return lldpToNodeConnectorRef(payload, false);
79 * Returns the encoded in custom TLV for the given lldp.
81 * @param payload lldp payload
82 * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
83 * @return nodeConnectorId - encoded in custom TLV of given lldp
85 @SuppressWarnings("checkstyle:IllegalCatch")
86 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck) {
87 NodeConnectorRef nodeConnectorRef = null;
89 if (isLLDP(payload)) {
90 Ethernet ethPkt = new Ethernet();
92 ethPkt.deserialize(payload, 0, payload.length * NetUtils.NUM_BITS_IN_A_BYTE);
93 } catch (PacketException e) {
94 LOG.warn("Failed to decode LLDP packet", e);
95 return nodeConnectorRef;
98 LLDP lldp = (LLDP) ethPkt.getPayload();
101 NodeId srcNodeId = null;
102 NodeConnectorId srcNodeConnectorId = null;
104 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
105 if (systemIdTLV != null) {
106 String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
107 srcNodeId = new NodeId(srcNodeIdString);
109 throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
112 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(LLDPTLV.createPortSubTypeCustomTLVKey());
113 if (nodeConnectorIdLldptlv != null) {
114 srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
115 nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
117 throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
120 if (useExtraAuthenticatorCheck) {
121 boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
123 LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
125 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
129 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
130 .child(Node.class, new NodeKey(srcNodeId))
131 .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
133 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
134 } catch (Exception e) {
135 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
138 return nodeConnectorRef;
142 * Gets an extra authenticator for lldp security.
144 * @param nodeConnectorId the NodeConnectorId
145 * @return extra authenticator for lldp security
147 public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId) {
149 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
150 finalKey = LLDPActivator.getLldpSecureKey();
152 finalKey = ManagementFactory.getRuntimeMXBean().getName();
154 final String pureValue = nodeConnectorId + finalKey;
156 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
157 HashFunction hashFunction = Hashing.md5();
158 Hasher hasher = hashFunction.newHasher();
159 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
160 return hashedValue.asBytes();
163 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
164 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
166 EntityOwnershipState state = null;
167 Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
168 if (status.isPresent()) {
169 state = status.get();
171 LOG.error("Fetching ownership status failed for node {}", nodeId);
173 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
176 public static org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819
177 .LinkDiscovered toLLDPLinkDiscovered(Link link) {
178 return new LinkDiscoveredBuilder()
179 .setSource(getNodeConnectorRefFromLink(link.getSource().getSourceTp(),
180 link.getSource().getSourceNode()))
181 .setDestination(getNodeConnectorRefFromLink(link.getDestination().getDestTp(),
182 link.getDestination().getDestNode()))
186 private static boolean isLLDP(final byte[] packet) {
187 if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
191 final ByteBuffer bb = ByteBuffer.wrap(packet);
193 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
195 if (ethernetType == ETHERNET_TYPE_VLAN) {
196 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
199 return ethernetType == ETHERNET_TYPE_LLDP;
202 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
203 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
204 boolean secAuthenticatorOk = false;
205 if (hashLldptlv != null) {
206 byte[] rawTlvValue = hashLldptlv.getValue();
207 byte[] lldpCustomSecurityHash = Arrays.copyOfRange(rawTlvValue, 4, rawTlvValue.length);
208 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
209 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
211 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
214 return secAuthenticatorOk;
217 private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
218 final String nodeId) {
219 Entity entity = createNodeEntity(nodeId);
220 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
222 if (ownershipStatus.isPresent()) {
223 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
225 return ownershipStatus;
228 private static Entity createNodeEntity(final String nodeId) {
229 return new Entity(SERVICE_ENTITY_TYPE, nodeId);
232 private static NodeConnectorRef getNodeConnectorRefFromLink(final TpId tpId, final org.opendaylight.yang.gen.v1.urn
233 .tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId) {
234 String nodeConnectorId = tpId.getValue();
235 InstanceIdentifier<NodeConnector> nciid
236 = InstanceIdentifier.builder(Nodes.class)
239 new NodeKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
243 new NodeConnectorKey(new NodeConnectorId(nodeConnectorId)))
245 return new NodeConnectorRef(nciid);