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.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.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 public final class LLDPDiscoveryUtils {
44 private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
46 private static final short MINIMUM_LLDP_SIZE = 61;
47 public static final short ETHERNET_TYPE_VLAN = (short) 0x8100;
48 public static final short ETHERNET_TYPE_LLDP = (short) 0x88cc;
49 private static final short ETHERNET_TYPE_OFFSET = 12;
50 private static final short ETHERNET_VLAN_OFFSET = ETHERNET_TYPE_OFFSET + 4;
51 private static final String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
53 private LLDPDiscoveryUtils() {
56 public static String macToString(byte[] mac) {
57 StringBuilder builder = new StringBuilder();
58 for (int i = 0; i < mac.length; i++) {
59 builder.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : ""));
62 return builder.toString();
66 * Returns the encoded in custom TLV for the given lldp.
68 * @param payload lldp payload
69 * @return nodeConnectorId - encoded in custom TLV of given lldp
70 * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
72 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
73 return lldpToNodeConnectorRef(payload, false);
77 * Returns the encoded in custom TLV for the given lldp.
79 * @param payload lldp payload
80 * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
81 * @return nodeConnectorId - encoded in custom TLV of given lldp
83 @SuppressWarnings("checkstyle:IllegalCatch")
84 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck) {
85 NodeConnectorRef nodeConnectorRef = null;
87 if (isLLDP(payload)) {
88 Ethernet ethPkt = new Ethernet();
90 ethPkt.deserialize(payload, 0, payload.length * NetUtils.NUM_BITS_IN_A_BYTE);
91 } catch (PacketException e) {
92 LOG.warn("Failed to decode LLDP packet", e);
93 return nodeConnectorRef;
96 LLDP lldp = (LLDP) ethPkt.getPayload();
99 NodeId srcNodeId = null;
100 NodeConnectorId srcNodeConnectorId = null;
102 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
103 if (systemIdTLV != null) {
104 String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
105 srcNodeId = new NodeId(srcNodeIdString);
107 throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
110 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(LLDPTLV.createPortSubTypeCustomTLVKey());
111 if (nodeConnectorIdLldptlv != null) {
112 srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
113 nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
115 throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
118 if (useExtraAuthenticatorCheck) {
119 boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
121 LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
123 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
127 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
128 .child(Node.class, new NodeKey(srcNodeId))
129 .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
131 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
132 } catch (Exception e) {
133 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
136 return nodeConnectorRef;
140 * Gets an extra authenticator for lldp security.
142 * @param nodeConnectorId the NodeConnectorId
143 * @return extra authenticator for lldp security
145 public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId) {
147 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
148 finalKey = LLDPActivator.getLldpSecureKey();
150 finalKey = ManagementFactory.getRuntimeMXBean().getName();
152 final String pureValue = nodeConnectorId + finalKey;
154 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
155 HashFunction hashFunction = Hashing.md5();
156 Hasher hasher = hashFunction.newHasher();
157 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
158 return hashedValue.asBytes();
161 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
162 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
163 boolean secAuthenticatorOk = false;
164 if (hashLldptlv != null) {
165 byte[] rawTlvValue = hashLldptlv.getValue();
166 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
167 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
168 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
170 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
173 return secAuthenticatorOk;
176 private static boolean isLLDP(final byte[] packet) {
177 if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
181 final ByteBuffer bb = ByteBuffer.wrap(packet);
183 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
185 if (ethernetType == ETHERNET_TYPE_VLAN) {
186 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
189 return ethernetType == ETHERNET_TYPE_LLDP;
192 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
193 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
195 EntityOwnershipState state = null;
196 Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
197 if (status.isPresent()) {
198 state = status.get();
200 LOG.error("Fetching ownership status failed for node {}", nodeId);
202 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
205 private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
206 final String nodeId) {
207 Entity entity = createNodeEntity(nodeId);
208 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
210 if (ownershipStatus.isPresent()) {
211 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
213 return ownershipStatus;
216 private static Entity createNodeEntity(final String nodeId) {
217 return new Entity(SERVICE_ENTITY_TYPE, nodeId);