Fix findbugs violations in applications
[openflowplugin.git] / applications / topology-lldp-discovery / src / main / java / org / opendaylight / openflowplugin / applications / topology / lldp / utils / LLDPDiscoveryUtils.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.openflowplugin.applications.topology.lldp.utils;
9
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;
46
47 public final class LLDPDiscoveryUtils {
48     private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
49
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";
56
57     private LLDPDiscoveryUtils() {
58     }
59
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 ? ":" : ""));
64         }
65
66         return builder.toString();
67     }
68
69     /**
70      * Returns the encoded in custom TLV for the given lldp.
71      *
72      * @param payload lldp payload
73      * @return nodeConnectorId - encoded in custom TLV of given lldp
74      * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
75      */
76     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload)  {
77         return lldpToNodeConnectorRef(payload, false);
78     }
79
80     /**
81      * Returns the encoded in custom TLV for the given lldp.
82      *
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
86      */
87     @SuppressWarnings("checkstyle:IllegalCatch")
88     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck)  {
89         NodeConnectorRef nodeConnectorRef = null;
90
91         if (isLLDP(payload)) {
92             Ethernet ethPkt = new Ethernet();
93             try {
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;
98             }
99
100             LLDP lldp = (LLDP) ethPkt.getPayload();
101
102             try {
103                 NodeId srcNodeId = null;
104                 NodeConnectorId srcNodeConnectorId = null;
105
106                 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
107                 if (systemIdTLV != null) {
108                     String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
109                     srcNodeId = new NodeId(srcNodeIdString);
110                 } else {
111                     throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
112                 }
113
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()));
119                 } else {
120                     throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
121                 }
122
123                 if (useExtraAuthenticatorCheck) {
124                     boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
125                     if (!secure) {
126                         LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
127                         throw new Exception(
128                                 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
129                     }
130                 }
131
132                 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
133                         .child(Node.class, new NodeKey(srcNodeId))
134                         .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
135                         .toInstance();
136                 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
137             } catch (Exception e) {
138                 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
139             }
140         }
141         return nodeConnectorRef;
142     }
143
144     /**
145      * Gets an extra authenticator for lldp security.
146      *
147      * @param nodeConnectorId the NodeConnectorId
148      * @return extra authenticator for lldp security
149      */
150     public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
151             throws NoSuchAlgorithmException {
152         String finalKey;
153         if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
154             finalKey = LLDPActivator.getLldpSecureKey();
155         } else {
156             finalKey = ManagementFactory.getRuntimeMXBean().getName();
157         }
158         final String pureValue = nodeConnectorId + finalKey;
159
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();
165     }
166
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);
177         } else {
178             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
179         }
180
181         return secAuthenticatorOk;
182     }
183
184     private static boolean isLLDP(final byte[] packet) {
185         if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
186             return false;
187         }
188
189         final ByteBuffer bb = ByteBuffer.wrap(packet);
190
191         short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
192
193         if (ethernetType == ETHERNET_TYPE_VLAN) {
194             ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
195         }
196
197         return ethernetType == ETHERNET_TYPE_LLDP;
198     }
199
200     public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
201         Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
202
203         EntityOwnershipState state = null;
204         java.util.Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
205         if (status.isPresent()) {
206             state = status.get();
207         } else {
208             LOG.error("Fetching ownership status failed for node {}", nodeId);
209         }
210         return state != null && state.equals(EntityOwnershipState.IS_OWNER);
211     }
212
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);
217
218         if (ownershipStatus.isPresent()) {
219             LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
220             return java.util.Optional.of(ownershipStatus.get());
221         }
222         return java.util.Optional.empty();
223     }
224
225     private static Entity createNodeEntity(final String nodeId) {
226         return new Entity(SERVICE_ENTITY_TYPE, nodeId);
227     }
228 }