817499eb5f8d25ff30388816cd4ee10026ea3154
[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.flow.topology.discovery.rev130819.LinkDiscoveredBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
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         String finalKey;
150         if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
151             finalKey = LLDPActivator.getLldpSecureKey();
152         } else {
153             finalKey = ManagementFactory.getRuntimeMXBean().getName();
154         }
155         final String pureValue = nodeConnectorId + finalKey;
156
157         final byte[] pureBytes = pureValue.getBytes(StandardCharsets.UTF_8);
158         HashFunction hashFunction = Hashing.md5();
159         Hasher hasher = hashFunction.newHasher();
160         HashCode hashedValue = hasher.putBytes(pureBytes).hash();
161         return hashedValue.asBytes();
162     }
163
164     public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
165         Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
166
167         EntityOwnershipState state = null;
168         Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
169         if (status.isPresent()) {
170             state = status.get();
171         } else {
172             LOG.error("Fetching ownership status failed for node {}", nodeId);
173         }
174         return state != null && state.equals(EntityOwnershipState.IS_OWNER);
175     }
176
177     public static org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819
178             .LinkDiscovered toLLDPLinkDiscovered(Link link) {
179         return new LinkDiscoveredBuilder()
180                 .setSource(getNodeConnectorRefFromLink(link.getSource().getSourceTp(),
181                         link.getSource().getSourceNode()))
182                 .setDestination(getNodeConnectorRefFromLink(link.getDestination().getDestTp(),
183                         link.getDestination().getDestNode()))
184                 .build();
185     }
186
187     private static boolean isLLDP(final byte[] packet) {
188         if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
189             return false;
190         }
191
192         final ByteBuffer bb = ByteBuffer.wrap(packet);
193
194         short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
195
196         if (ethernetType == ETHERNET_TYPE_VLAN) {
197             ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
198         }
199
200         return ethernetType == ETHERNET_TYPE_LLDP;
201     }
202
203     private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
204         final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
205         boolean secAuthenticatorOk = false;
206         if (hashLldptlv != null) {
207             byte[] rawTlvValue = hashLldptlv.getValue();
208             byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
209             byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
210             secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
211         } else {
212             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
213         }
214
215         return secAuthenticatorOk;
216     }
217
218     private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
219             final String nodeId) {
220         Entity entity = createNodeEntity(nodeId);
221         Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
222
223         if (ownershipStatus.isPresent()) {
224             LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
225         }
226         return ownershipStatus;
227     }
228
229     private static Entity createNodeEntity(final String nodeId) {
230         return new Entity(SERVICE_ENTITY_TYPE, nodeId);
231     }
232
233     private static NodeConnectorRef getNodeConnectorRefFromLink(final TpId tpId, final org.opendaylight.yang.gen.v1.urn
234             .tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId) {
235         String nodeConnectorId = tpId.getValue();
236         InstanceIdentifier<NodeConnector> nciid
237                 = InstanceIdentifier.builder(Nodes.class)
238                 .child(
239                         Node.class,
240                         new NodeKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
241                                 .NodeId(nodeId)))
242                 .child(
243                         NodeConnector.class,
244                         new NodeConnectorKey(new NodeConnectorId(nodeConnectorId)))
245                 .build();
246         return new NodeConnectorRef(nciid);
247     }
248 }