Add blueprint wiring for the TopologyLldpDiscovery app
[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.hash.HashCode;
11 import com.google.common.hash.HashFunction;
12 import com.google.common.hash.Hasher;
13 import com.google.common.hash.Hashing;
14 import java.lang.management.ManagementFactory;
15 import java.nio.charset.Charset;
16 import java.security.NoSuchAlgorithmException;
17 import java.util.Arrays;
18 import org.apache.commons.lang3.ArrayUtils;
19 import org.opendaylight.controller.liblldp.BitBufferHelper;
20 import org.opendaylight.controller.liblldp.CustomTLVKey;
21 import org.opendaylight.controller.liblldp.Ethernet;
22 import org.opendaylight.controller.liblldp.LLDP;
23 import org.opendaylight.controller.liblldp.LLDPTLV;
24 import org.opendaylight.controller.liblldp.NetUtils;
25 import org.opendaylight.openflowplugin.applications.topology.lldp.LLDPActivator;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38
39 public class LLDPDiscoveryUtils {
40     private static final Logger LOG = LoggerFactory.getLogger(LLDPDiscoveryUtils.class);
41
42     public static String macToString(byte[] mac) {
43         StringBuilder b = new StringBuilder();
44         for (int i = 0; i < mac.length; i++) {
45             b.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
46         }
47
48         return b.toString();
49     }
50
51     /**
52      * @param payload
53      * @return nodeConnectorId - encoded in custom TLV of given lldp
54      * @see LLDPDiscoveryUtils#lldpToNodeConnectorRef(byte[], boolean)
55      */
56     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload)  {
57         return lldpToNodeConnectorRef(payload, false);
58     }
59
60     /**
61      * @param payload
62      * @param useExtraAuthenticatorCheck make it more secure (CVE-2015-1611 CVE-2015-1612)
63      * @return nodeConnectorId - encoded in custom TLV of given lldp
64      */
65     public static NodeConnectorRef lldpToNodeConnectorRef(byte[] payload, boolean useExtraAuthenticatorCheck)  {
66         Ethernet ethPkt = new Ethernet();
67         try {
68             ethPkt.deserialize(payload, 0,payload.length * NetUtils.NumBitsInAByte);
69         } catch (Exception e) {
70             LOG.warn("Failed to decode LLDP packet {}", e);
71         }
72
73         NodeConnectorRef nodeConnectorRef = null;
74
75         if (ethPkt.getPayload() instanceof LLDP) {
76             LLDP lldp = (LLDP) ethPkt.getPayload();
77
78             try {
79                 NodeId srcNodeId = null;
80                 NodeConnectorId srcNodeConnectorId = null;
81
82                 final LLDPTLV systemIdTLV = lldp.getSystemNameId();
83                 if (systemIdTLV != null) {
84                     String srcNodeIdString = new String(systemIdTLV.getValue(),Charset.defaultCharset());
85                     srcNodeId = new NodeId(srcNodeIdString);
86                 } else {
87                     throw new Exception("Node id wasn't specified via systemNameId in LLDP packet.");
88                 }
89
90                 final LLDPTLV nodeConnectorIdLldptlv = lldp.getCustomTLV(
91                         new CustomTLVKey(BitBufferHelper.getInt(LLDPTLV.OFOUI), LLDPTLV.CUSTOM_TLV_SUB_TYPE_NODE_CONNECTOR_ID[0]));
92                 if (nodeConnectorIdLldptlv != null) {
93                     srcNodeConnectorId = new NodeConnectorId(LLDPTLV.getCustomString(
94                             nodeConnectorIdLldptlv.getValue(), nodeConnectorIdLldptlv.getLength()));
95                 } else {
96                     throw new Exception("Node connector wasn't specified via Custom TLV in LLDP packet.");
97                 }
98
99                 if (useExtraAuthenticatorCheck) {
100                     boolean secure = checkExtraAuthenticator(lldp, srcNodeConnectorId);
101                     if (! secure) {
102                         LOG.warn("SECURITY ALERT: there is probably a LLDP spoofing attack in progress.");
103                         throw new Exception("Attack. LLDP packet with inconsistent extra authenticator field was received.");
104                     }
105                 }
106
107                 InstanceIdentifier<NodeConnector> srcInstanceId = InstanceIdentifier.builder(Nodes.class)
108                         .child(Node.class,new NodeKey(srcNodeId))
109                         .child(NodeConnector.class, new NodeConnectorKey(srcNodeConnectorId))
110                         .toInstance();
111                 nodeConnectorRef = new NodeConnectorRef(srcInstanceId);
112             } catch (Exception e) {
113                 LOG.debug("Caught exception while parsing out lldp optional and custom fields: {}", e.getMessage(), e);
114             }
115         }
116         return nodeConnectorRef;
117     }
118
119     /**
120      * @param nodeConnectorId
121      * @return extra authenticator for lldp security
122      * @throws NoSuchAlgorithmException
123      */
124     public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId) throws NoSuchAlgorithmException {
125         String finalKey;
126         if(LLDPActivator.getLldpSecureKey() !=null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
127             finalKey = LLDPActivator.getLldpSecureKey();
128         } else {
129             finalKey = ManagementFactory.getRuntimeMXBean().getName();
130         }
131         final String pureValue = nodeConnectorId + finalKey;
132
133         final byte[] pureBytes = pureValue.getBytes();
134         HashFunction hashFunction = Hashing.md5();
135         Hasher hasher = hashFunction.newHasher();
136         HashCode hashedValue = hasher.putBytes(pureBytes).hash();
137         return hashedValue.asBytes();
138     }
139
140     /**
141      * @param lldp
142      * @param srcNodeConnectorId
143      * @throws NoSuchAlgorithmException
144      */
145     private static boolean checkExtraAuthenticator(LLDP lldp, NodeConnectorId srcNodeConnectorId) throws NoSuchAlgorithmException {
146         final LLDPTLV hashLldptlv = lldp.getCustomTLV(
147                 new CustomTLVKey(BitBufferHelper.getInt(LLDPTLV.OFOUI), LLDPTLV.CUSTOM_TLV_SUB_TYPE_CUSTOM_SEC[0]));
148         boolean secAuthenticatorOk = false;
149         if (hashLldptlv != null) {
150             byte[] rawTlvValue = hashLldptlv.getValue();
151             byte[] lldpCustomSecurityHash = ArrayUtils.subarray(rawTlvValue, 4, rawTlvValue.length);
152             byte[] calculatedHash = getValueForLLDPPacketIntegrityEnsuring(srcNodeConnectorId);
153             secAuthenticatorOk = Arrays.equals(calculatedHash, lldpCustomSecurityHash);
154         } else {
155             LOG.debug("Custom security hint wasn't specified via Custom TLV in LLDP packet.");
156         }
157
158         return secAuthenticatorOk;
159     }
160 }