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