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