Update MRI projects for Aluminium
[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.opendaylight.mdsal.eos.binding.api.Entity;
22 import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
23 import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
24 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
25 import org.opendaylight.openflowplugin.libraries.liblldp.Ethernet;
26 import org.opendaylight.openflowplugin.libraries.liblldp.LLDP;
27 import org.opendaylight.openflowplugin.libraries.liblldp.LLDPTLV;
28 import org.opendaylight.openflowplugin.libraries.liblldp.NetUtils;
29 import org.opendaylight.openflowplugin.libraries.liblldp.PacketException;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819.LinkDiscoveredBuilder;
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.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
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     public static boolean isEntityOwned(final EntityOwnershipService eos, final String nodeId) {
164         Preconditions.checkNotNull(eos, "Entity ownership service must not be null");
165
166         EntityOwnershipState state = null;
167         Optional<EntityOwnershipState> status = getCurrentOwnershipStatus(eos, nodeId);
168         if (status.isPresent()) {
169             state = status.get();
170         } else {
171             LOG.error("Fetching ownership status failed for node {}", nodeId);
172         }
173         return state != null && state.equals(EntityOwnershipState.IS_OWNER);
174     }
175
176     public static org.opendaylight.yang.gen.v1.urn.opendaylight.flow.topology.discovery.rev130819
177             .LinkDiscovered toLLDPLinkDiscovered(Link link) {
178         return new LinkDiscoveredBuilder()
179                 .setSource(getNodeConnectorRefFromLink(link.getSource().getSourceTp(),
180                         link.getSource().getSourceNode()))
181                 .setDestination(getNodeConnectorRefFromLink(link.getDestination().getDestTp(),
182                         link.getDestination().getDestNode()))
183                 .build();
184     }
185
186     private static boolean isLLDP(final byte[] packet) {
187         if (packet == null || packet.length < MINIMUM_LLDP_SIZE) {
188             return false;
189         }
190
191         final ByteBuffer bb = ByteBuffer.wrap(packet);
192
193         short ethernetType = bb.getShort(ETHERNET_TYPE_OFFSET);
194
195         if (ethernetType == ETHERNET_TYPE_VLAN) {
196             ethernetType = bb.getShort(ETHERNET_VLAN_OFFSET);
197         }
198
199         return ethernetType == ETHERNET_TYPE_LLDP;
200     }
201
202     private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) {
203         final LLDPTLV hashLldptlv = lldp.getCustomTLV(LLDPTLV.createSecSubTypeCustomTLVKey());
204         boolean secAuthenticatorOk = false;
205         if (hashLldptlv != null) {
206             byte[] rawTlvValue = hashLldptlv.getValue();
207             byte[] lldpCustomSecurityHash = Arrays.copyOfRange(rawTlvValue, 4, rawTlvValue.length);
208             byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
209             secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
210         } else {
211             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
212         }
213
214         return secAuthenticatorOk;
215     }
216
217     private static Optional<EntityOwnershipState> getCurrentOwnershipStatus(final EntityOwnershipService eos,
218             final String nodeId) {
219         Entity entity = createNodeEntity(nodeId);
220         Optional<EntityOwnershipState> ownershipStatus = eos.getOwnershipState(entity);
221
222         if (ownershipStatus.isPresent()) {
223             LOG.debug("Fetched ownership status for node {} is {}", nodeId, ownershipStatus.get());
224         }
225         return ownershipStatus;
226     }
227
228     private static Entity createNodeEntity(final String nodeId) {
229         return new Entity(SERVICE_ENTITY_TYPE, nodeId);
230     }
231
232     private static NodeConnectorRef getNodeConnectorRefFromLink(final TpId tpId, final org.opendaylight.yang.gen.v1.urn
233             .tbd.params.xml.ns.yang.network.topology.rev131021.NodeId nodeId) {
234         String nodeConnectorId = tpId.getValue();
235         InstanceIdentifier<NodeConnector> nciid
236                 = InstanceIdentifier.builder(Nodes.class)
237                 .child(
238                         Node.class,
239                         new NodeKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819
240                                 .NodeId(nodeId)))
241                 .child(
242                         NodeConnector.class,
243                         new NodeConnectorKey(new NodeConnectorId(nodeConnectorId)))
244                 .build();
245         return new NodeConnectorRef(nciid);
246     }
247 }