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