Fix spotbugs logging complaints
[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.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.Optional;
21 import org.apache.commons.lang3.ArrayUtils;
22 import org.opendaylight.mdsal.eos.binding.api.Entity;
23 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
24 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
25 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
26 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
27 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
28 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
29 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
30 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public final class LLDPDiscoveryUtils {
44     private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
45
46     private static final short MINIMUM_LLDP_SIZE = 61;
47     public static final short ETHERNET_TYPE_VLAN = (short) 0x8100;
48     public static final short ETHERNET_TYPE_LLDP = (short) 0x88cc;
49     private static final short ETHERNET_TYPE_OFFSET = 12;
50     private static final short ETHERNET_VLAN_OFFSET = ETHERNET_TYPE_OFFSET + 4;
51     private static final String SERVICE_ENTITY_TYPE = "org.opendaylight.mdsal.ServiceEntityType";
52
53     private LLDPDiscoveryUtils() {
54     }
55
56     public static String macToString(byte[] mac) {
57         StringBuilder builder = new StringBuilder();
58         for (int i = 0; i < mac.length; i++) {
59             builder.append(String.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : ""));
60         }
61
62         return builder.toString();
63     }
64
65     /**
66      * Returns the encoded in custom TLV for the given lldp.
67      *
68      * @param payload lldp payload
69      * @return nodeConnectorId - encoded in custom TLV of given lldp
70      * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
71      */
72     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload)  {
73         return lldpToNodeConnectorRef(payload, false);
74     }
75
76     /**
77      * Returns the encoded in custom TLV for the given lldp.
78      *
79      * @param payload lldp payload
80      * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
81      * @return nodeConnectorId - encoded in custom TLV of given lldp
82      */
83     @SuppressWarnings("checkstyle:IllegalCatch")
84     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck)  {
85         NodeConnectorRef nodeConnectorRef = null;
86
87         if (isLLDP(payload)) {
88             Ethernet ethPkt = new Ethernet();
89             try {
90                 ethPkt.deserialize(payload, 0, payload.length * NetUtils.NUM_BITS_IN_A_BYTE);
91             } catch (PacketException e) {
92                 LOG.warn("Failed to decode LLDP packet", e);
93                 return nodeConnectorRef;
94             }
95
96             LLDP lldp = (LLDP) ethPkt.getPayload();
97
98             try {
99                 NodeId srcNodeId = null;
100                 NodeConnectorId srcNodeConnectorId = null;
101
102                 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
103                 if (systemIdTLV != null) {
104                     String srcNodeIdString = new String(systemIdTLV.getValue(), Charset.defaultCharset());
105                     srcNodeId = new NodeId(srcNodeIdString);
106                 } else {
107                     throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
108                 }
109
110                 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(LLDPTLV.createPortSubTypeCustomTLVKey());
111                 if (nodeConnectorIdLldptlv != null) {
112                     srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
113                             nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
114                 } else {
115                     throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
116                 }
117
118                 if (useExtraAuthenticatorCheck) {
119                     boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
120                     if (!secure) {
121                         LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
122                         throw new Exception(
123                                 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
124                     }
125                 }
126
127                 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
128                         .child(Node.class, new NodeKey(srcNodeId))
129                         .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
130                         .build();
131                 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
132             } catch (Exception e) {
133                 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
134             }
135         }
136         return nodeConnectorRef;
137     }
138
139     /**
140      * Gets an extra authenticator for lldp security.
141      *
142      * @param nodeConnectorId the NodeConnectorId
143      * @return extra authenticator for lldp security
144      */
145     public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId) {
146         String finalKey;
147         if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
148             finalKey = LLDPActivator.getLldpSecureKey();
149         } else {
150             finalKey = ManagementFactory.getRuntimeMXBean().getName();
151         }
152         final String pureValue = nodeConnectorId + finalKey;
153
154         final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
155         HashFunction hashFunction = Hashing.md5();
156         Hasher hasher = hashFunction.newHasher();
157         HashCode hashedValue = hasher.putBytes(pureBytes).hash();
158         return hashedValue.asBytes();
159     }
160
161     private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
162         final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
163         boolean secAuthenticatorOk = false;
164         if (hashLldptlv != null) {
165             byte[] rawTlvValue = hashLldptlv.getValue();
166             byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
167             byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
168             secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
169         } else {
170             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
171         }
172
173         return secAuthenticatorOk;
174     }
175
176     private static boolean isLLDP(final byte[] packet) {
177         if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
178             return false;
179         }
180
181         final ByteBuffer bb = ByteBuffer.wrap(packet);
182
183         short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
184
185         if (ethernetType == ETHERNET_TYPE_VLAN) {
186             ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
187         }
188
189         return ethernetType == ETHERNET_TYPE_LLDP;
190     }
191
192     public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
193         Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
194
195         EntityOwnershipState state = null;
196         Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
197         if (status.isPresent()) {
198             state = status.get();
199         } else {
200             LOG.error("Fetching ownership status failed for node {}", nodeId);
201         }
202         return state != null && state.equals(EntityOwnershipState.IS_OWNER);
203     }
204
205     private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
206             final String nodeId) {
207         Entity entity = createNodeEntity(nodeId);
208         Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
209
210         if (ownershipStatus.isPresent()) {
211             LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
212         }
213         return ownershipStatus;
214     }
215
216     private static Entity createNodeEntity(final String nodeId) {
217         return new Entity(SERVICE_ENTITY_TYPE, nodeId);
218     }
219 }