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.security.NoSuchAlgorithmException;
20 import java.util.Arrays;
21 import java.util.Objects;
22 import java.util.Optional;
24 import org.apache.commons.lang3.ArrayUtils;
25 import org.opendaylight.mdsal.eos.binding.api.Entity;
26 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
27 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
28 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
29 import org.opendaylight.openflowplugin.libraries.liblldp.BufferException;
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(LLDPTLV.createPortSubTypeCustomTLVKey());
115 if (nodeConnectorIdLldptlv != null) {
116 srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
117 nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
119 throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
122 if (useExtraAuthenticatorCheck) {
123 boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
125 LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
127 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
131 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
132 .child(Node.class, new NodeKey(srcNodeId))
133 .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
135 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
136 } catch (Exception e) {
137 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
140 return nodeConnectorRef;
144 * Gets an extra authenticator for lldp security.
146 * @param nodeConnectorId the NodeConnectorId
147 * @return extra authenticator for lldp security
149 public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
150 throws NoSuchAlgorithmException {
152 if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
153 finalKey = LLDPActivator.getLldpSecureKey();
155 finalKey = ManagementFactory.getRuntimeMXBean().getName();
157 final String pureValue = nodeConnectorId + finalKey;
159 final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
160 HashFunction hashFunction = Hashing.md5();
161 Hasher hasher = hashFunction.newHasher();
162 HashCode hashedValue = hasher.putBytes(pureBytes).hash();
163 return hashedValue.asBytes();
166 private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId)
167 throws NoSuchAlgorithmException, BufferException {
168 final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
169 boolean secAuthenticatorOk = false;
170 if (hashLldptlv != null) {
171 byte[] rawTlvValue = hashLldptlv.getValue();
172 byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
173 byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
174 secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
176 LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
179 return secAuthenticatorOk;
182 private static boolean isLLDP(final byte[] packet) {
183 if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
187 final ByteBuffer bb = ByteBuffer.wrap(packet);
189 short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
191 if (ethernetType == ETHERNET_TYPE_VLAN) {
192 ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
195 return ethernetType == ETHERNET_TYPE_LLDP;
198 public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
199 Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
201 EntityOwnershipState state = null;
202 java.util.Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
203 if (status.isPresent()) {
204 state = status.get();
206 LOG.error("Fetching ownership status failed for node {}", nodeId);
208 return state != null && state.equals(EntityOwnershipState.IS_OWNER);
211 private static java.util.Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
212 final String nodeId) {
213 Entity entity = createNodeEntity(nodeId);
214 Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
216 if (ownershipStatus.isPresent()) {
217 LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
218 return java.util.Optional.of(ownershipStatus.get());
220 return java.util.Optional.empty();
223 private static Entity createNodeEntity(final String nodeId) {
224 return new Entity(SERVICE_ENTITY_TYPE, nodeId);