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.BufferException;
29 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
30 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
31 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
32 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
33 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
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)
149 throws NoSuchAlgorithmException {
151 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
152 finalKey = LLDPActivator.getLldpSecureKey();
154 finalKey = ManagementFactory.getRuntimeMXBean().getName();
156 final String pureValue = nodeConnectorId + finalKey;
158 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
159 HashFunction hashFunction = Hashing.md5();
160 Hasher hasher = hashFunction.newHasher();
161 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
162 return hashedValue.asBytes();
165 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId)
166 throws NoSuchAlgorithmException, BufferException {
167 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
168 boolean secAuthenticatorOk = false;
169 if (hashLldptlv != null) {
170 byte[] rawTlvValue = hashLldptlv.getValue();
171 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
172 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
173 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
175 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
178 return secAuthenticatorOk;
181 private static boolean isLLDP(final byte[] packet) {
182 if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
186 final ByteBuffer bb = ByteBuffer.wrap(packet);
188 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
190 if (ethernetType == ETHERNET_TYPE_VLAN) {
191 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
194 return ethernetType == ETHERNET_TYPE_LLDP;
197 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
198 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
200 EntityOwnershipState state = null;
201 java.util.Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
202 if (status.isPresent()) {
203 state = status.get();
205 LOG.error("Fetching ownership status failed for node {}", nodeId);
207 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
210 private static java.util.Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
211 final String nodeId) {
212 Entity entity = createNodeEntity(nodeId);
213 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
215 if (ownershipStatus.isPresent()) {
216 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
217 return java.util.Optional.of(ownershipStatus.get());
219 return java.util.Optional.empty();
222 private static Entity createNodeEntity(final String nodeId) {
223 return new Entity(SERVICE_ENTITY_TYPE, nodeId);