OPNFLWPLUG-1032: Neon-MRI: Bump odlparent, yangtools, mdsal
[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.security.NoSuchAlgorithmException;
20 import java.util.Arrays;
21 import java.util.Objects;
22 import java.util.Optional;
23
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;
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(LLDPTLV.createPortSubTypeCustomTLVKey());
115                 if (nodeConnectorIdLldptlv != null) {
116                     srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
117                             nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
118                 } else {
119                     throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
120                 }
121
122                 if (useExtraAuthenticatorCheck) {
123                     boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
124                     if (!secure) {
125                         LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
126                         throw new Exception(
127                                 "Attack. LLDP packet with inconsistent extra authenticator field was received.");
128                     }
129                 }
130
131                 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
132                         .child(Node.class, new NodeKey(srcNodeId))
133                         .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
134                         .build();
135                 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
136             } catch (Exception e) {
137                 LOG.debug("Caught exception while parsing out lldp optional and custom fields", e);
138             }
139         }
140         return nodeConnectorRef;
141     }
142
143     /**
144      * Gets an extra authenticator for lldp security.
145      *
146      * @param nodeConnectorId the NodeConnectorId
147      * @return extra authenticator for lldp security
148      */
149     public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
150             throws NoSuchAlgorithmException {
151         String finalKey;
152         if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
153             finalKey = LLDPActivator.getLldpSecureKey();
154         } else {
155             finalKey = ManagementFactory.getRuntimeMXBean().getName();
156         }
157         final String pureValue = nodeConnectorId + finalKey;
158
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();
164     }
165
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);
175         } else {
176             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
177         }
178
179         return secAuthenticatorOk;
180     }
181
182     private static boolean isLLDP(final byte[] packet) {
183         if (Objects.isNull(packet) || packet.length < MINIMUM_LLDP_SIZE) {
184             return false;
185         }
186
187         final ByteBuffer bb = ByteBuffer.wrap(packet);
188
189         short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
190
191         if (ethernetType == ETHERNET_TYPE_VLAN) {
192             ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
193         }
194
195         return ethernetType == ETHERNET_TYPE_LLDP;
196     }
197
198     public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
199         Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
200
201         EntityOwnershipState state = null;
202         java.util.Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
203         if (status.isPresent()) {
204             state = status.get();
205         } else {
206             LOG.error("Fetching ownership status failed for node {}", nodeId);
207         }
208         return state != null && state.equals(EntityOwnershipState.IS_OWNER);
209     }
210
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);
215
216         if (ownershipStatus.isPresent()) {
217             LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
218             return java.util.Optional.of(ownershipStatus.get());
219         }
220         return java.util.Optional.empty();
221     }
222
223     private static Entity createNodeEntity(final String nodeId) {
224         return new Entity(SERVICE_ENTITY_TYPE, nodeId);
225     }
226 }