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