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.Objects;
21 import java.util.Optional;
23 import org.apache.commons.lang3.ArrayUtils;
24 import org.opendaylight.mdsal.eos.binding.api.Entity;
25 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
26 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
27 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
28 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
29 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
30 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
31 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
32 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
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 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
164 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
165 boolean secAuthenticatorOk = false;
166 if (hashLldptlv != null) {
167 byte[] rawTlvValue = hashLldptlv.getValue();
168 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
169 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
170 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
172 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
175 return secAuthenticatorOk;
178 private static boolean isLLDP(final byte[] packet) {
179 if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
183 final ByteBuffer bb = ByteBuffer.wrap(packet);
185 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
187 if (ethernetType == ETHERNET_TYPE_VLAN) {
188 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
191 return ethernetType == ETHERNET_TYPE_LLDP;
194 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
195 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
197 EntityOwnershipState state = null;
198 Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
199 if (status.isPresent()) {
200 state = status.get();
202 LOG.error("Fetching ownership status failed for node {}", nodeId);
204 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
207 private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
208 final String nodeId) {
209 Entity entity = createNodeEntity(nodeId);
210 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
212 if (ownershipStatus.isPresent()) {
213 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
215 return ownershipStatus;
218 private static Entity createNodeEntity(final String nodeId) {
219 return new Entity(SERVICE_ENTITY_TYPE, nodeId);