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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.hash.HashCode;
13 import com.google.common.hash.HashFunction;
14 import com.google.common.hash.Hasher;
15 import com.google.common.hash.Hashing;
16 import java.lang.management.ManagementFactory;
17 import java.nio.ByteBuffer;
18 import java.nio.charset.Charset;
19 import java.nio.charset.StandardCharsets;
20 import java.security.NoSuchAlgorithmException;
21 import java.util.Arrays;
22 import java.util.Objects;
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.BitBufferHelper;
29 import org.opendaylight.openflowplugin.libraries.liblldp.CustomTLVKey;
30 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
31 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
32 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
33 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
34 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public final class LLDPDiscoveryUtils {
48 private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
50 private static final short MINIMUM_LLDP_SIZE = 61;
51 public static final short ETHERNET_TYPE_VLAN = (short) 0x8100;
52 public static final short ETHERNET_TYPE_LLDP = (short) 0x88cc;
53 private static final short ETHERNET_TYPE_OFFSET = 12;
54 private static final short ETHERNET_VLAN_OFFSET = ETHERNET_TYPE_OFFSET + 4;
55 private static final String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
57 private LLDPDiscoveryUtils() {
60 public static String macToString(byte[] mac) {
61 StringBuilder builder = new StringBuilder();
62 for (int i = 0; i < mac.length; i++) {
63 builder.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : ""));
66 return builder.toString();
70 * Returns the encoded in custom TLV for the given lldp.
72 * @param payload lldp payload
73 * @return nodeConnectorId - encoded in custom TLV of given lldp
74 * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
76 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload) {
77 return lldpToNodeConnectorRef(payload, false);
81 * Returns the encoded in custom TLV for the given lldp.
83 * @param payload lldp payload
84 * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
85 * @return nodeConnectorId - encoded in custom TLV of given lldp
87 @SuppressWarnings("checkstyle:IllegalCatch")
88 public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck) {
89 NodeConnectorRef nodeConnectorRef = null;
91 if (isLLDP(payload)) {
92 Ethernet ethPkt = new Ethernet();
94 ethPkt.deserialize(payload, 0, payload.length * NetUtils.NUM_BITS_IN_A_BYTE);
95 } catch (PacketException e) {
96 LOG.warn("Failed to decode LLDP packet {}", e);
97 return nodeConnectorRef;
100 LLDP lldp = (LLDP) ethPkt.getPayload();
103 NodeId srcNodeId = null;
104 NodeConnectorId srcNodeConnectorId = null;
106 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
107 if (systemIdTLV != null) {
108 String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
109 srcNodeId = new NodeId(srcNodeIdString);
111 throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
114 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(new CustomTLVKey(
115 BitBufferHelper.getInt(LLDPTLV.OFOUI), LLDPTLV.CUSTOM_TLV_SUB_TYPE_NODE_CONNECTOR_ID[0]));
116 if (nodeConnectorIdLldptlv != null) {
117 srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
118 nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
120 throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
123 if (useExtraAuthenticatorCheck) {
124 boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
126 LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
128 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
132 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
133 .child(Node.class, new NodeKey(srcNodeId))
134 .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
136 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
137 } catch (Exception e) {
138 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
141 return nodeConnectorRef;
145 * Gets an extra authenticator for lldp security.
147 * @param nodeConnectorId the NodeConnectorId
148 * @return extra authenticator for lldp security
150 public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
151 throws NoSuchAlgorithmException {
153 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
154 finalKey = LLDPActivator.getLldpSecureKey();
156 finalKey = ManagementFactory.getRuntimeMXBean().getName();
158 final String pureValue = nodeConnectorId + finalKey;
160 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
161 HashFunction hashFunction = Hashing.md5();
162 Hasher hasher = hashFunction.newHasher();
163 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
164 return hashedValue.asBytes();
167 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId)
168 throws NoSuchAlgorithmException {
169 final LLDPTLV hashLldptlv = lldp.getCustomTLV(
170 new CustomTLVKey(BitBufferHelper.getInt(LLDPTLV.OFOUI), LLDPTLV.CUSTOM_TLV_SUB_TYPE_CUSTOM_SEC[0]));
171 boolean secAuthenticatorOk = false;
172 if (hashLldptlv != null) {
173 byte[] rawTlvValue = hashLldptlv.getValue();
174 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
175 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
176 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
178 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
181 return secAuthenticatorOk;
184 private static boolean isLLDP(final byte[] packet) {
185 if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
189 final ByteBuffer bb = ByteBuffer.wrap(packet);
191 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
193 if (ethernetType == ETHERNET_TYPE_VLAN) {
194 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
197 return ethernetType == ETHERNET_TYPE_LLDP;
200 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
201 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
203 EntityOwnershipState state = null;
204 java.util.Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
205 if (status.isPresent()) {
206 state = status.get();
208 LOG.error("Fetching ownership status failed for node {}", nodeId);
210 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
213 private static java.util.Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
214 final String nodeId) {
215 Entity entity = createNodeEntity(nodeId);
216 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
218 if (ownershipStatus.isPresent()) {
219 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
220 return java.util.Optional.of(ownershipStatus.get());
222 return java.util.Optional.empty();
225 private static Entity createNodeEntity(final String nodeId) {
226 return new Entity(SERVICE_ENTITY_TYPE, nodeId);