summaryrefslogtreecommitdiff
path: root/haircontrol/discovery.py
blob: 991abc38408f2b9cba8aa94a0d71d4beba0bf16d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
from haircontrol.data import *
from haircontrol.inspectors import *

class Discovery:

    def __init__(self): #, inspector):
        self.net = EtherDomain()
        self.dummy_inspector = DummyInspector()
        self.linux_inspector = LinuxInspector()
        self.ubnt_inspector = UbntInspector()
        self.toughswitch_inspector = ToughSwitchInspector()
        self.edgemax_inspector = EdgeMaxInspector()
        self.netonix_inspector = NetonixInspector()
        self.mikrotik_inspector = MikrotikInspector()
        self.openwrt_inspector = OpenWRTInspector()

        self.inspector_by_mac = {
                # Mikrotik
                'd4:ca:6d': self.mikrotik_inspector,
                'e4:8d:8c': self.mikrotik_inspector,
                # Netonix
                'ec:13:b2': self.netonix_inspector,
                'ec:13:b3': self.netonix_inspector,
                # PC
                '0c:c4:7a': self.linux_inspector, # SuperMicro
                '52:54:00': self.linux_inspector, # VM
                # TP-Link
                '10:fe:ed': self.openwrt_inspector,
                '14:cc:20': self.openwrt_inspector,
                '30:b5:c2': self.openwrt_inspector,
                '54:e6:fc': self.openwrt_inspector,
                '60:e3:27': self.openwrt_inspector,
                '64:66:b3': self.openwrt_inspector,
                '64:70:02': self.openwrt_inspector,
                '90:f6:52': self.openwrt_inspector,
                'a0:f3:c1': self.openwrt_inspector,
                'b0:48:7a': self.openwrt_inspector,
                'c0:4a:00': self.openwrt_inspector,
                'c4:6e:1f': self.openwrt_inspector,
                'c4:e9:84': self.openwrt_inspector,
                'f4:ec:38': self.openwrt_inspector,
                'f8:1a:67': self.openwrt_inspector,
                'f8:d1:11': self.openwrt_inspector,
                # Ubnt
                '00:15:6d':    self.ubnt_inspector,
                '00:27:22':    self.ubnt_inspector,
                '04:18:d6:07': self.toughswitch_inspector,
                '04:18:d6':    self.ubnt_inspector,
                '06:18:d6':    self.ubnt_inspector, # Non globaly unique ?!
                '24:a4:3c:05': self.toughswitch_inspector,
                '24:a4:3c:06': self.toughswitch_inspector,
                '24:a4:3c:07': self.toughswitch_inspector,
                '24:a4:3c:3c': self.toughswitch_inspector,
                '24:a4:3c:3d': self.toughswitch_inspector,
                '24:a4:3c:b3': self.toughswitch_inspector,
                '24:a4:3c':    self.ubnt_inspector,
                '44:d9:e7':    self.edgemax_inspector,
                'dc:9f:db:80': self.toughswitch_inspector,
                'dc:9f:db:81': self.toughswitch_inspector,
                'dc:9f:db':    self.ubnt_inspector,
        }


    def inspector(self, mac):
        if mac:
            return self.inspector_by_mac.get(mac[:11]) \
                    or self.inspector_by_mac.get(mac[:8]) \
                    or self.dummy_inspector
        else:
            return self.dummy_inspector


    def discover_static_hinting(self, name_ip_tuples):
        for name, ip in name_ip_tuples:
            self.net.add_equipment(Equipment(name, ip))


    def discover_lldp_hinting(self, e_lldp):
        self.net.add_equipment(e_lldp)
        self.linux_inspector.connect(e_lldp)

        # Learn local interfaces of e_lldp
        result = self.linux_inspector.command('ip-link')
        for (ifname, mac) in result:
            if ifname not in [ 'lo' ]: # XXX configurable filter
                e_lldp.add_iface(ifname, mac)

        # Create equipments and ifaces from LLDP neighbour discovery
        result = self.linux_inspector.command('lldpctl')
        for (local_ifname, local_mac, remote_name, remote_ipmgmt, ports) in result:
            e = Equipment(remote_name, remote_ipmgmt)
            self.net.add_equipment(e)
            # lldp returns logical port, not physicial port for remote bridges
            for remote_ifname in ports:
                if remote_ifname not in [ 'br0' ]: # XXX configurable filter
                    e.add_seen_mac(remote_ifname, local_mac)

        self.linux_inspector.disconnect()


    def discover_from_root(self, e_root):
        self.net.add_equipment(e_root)
        self.linux_inspector.connect(e_root)

        # Learn root neighbours (directly or indirectly connected via trasparent bridges)
        result = self.linux_inspector.command('ip-neigh')
        for (ip, ifname, mac) in result:
            self.net.index_mac_ip(mac, ip)
            e_root.add_seen_mac(ifname, mac)

        self.linux_inspector.disconnect()

        # Create/Update Equipment object for all neighbours
        # (could be already created by hinting)
        for iface in e_root.ifaces.values():
            local_ifname = iface.name
            local_mac = iface.mac
            for remote_mac in iface.mac_seen:
                remote_ip = self.net.mac2ip.get(remote_mac)
                if remote_ip:
                    e = self.net.equipments.get(remote_ip)
                    if e and not e.ifaces:
                        e.add_iface(None, remote_mac)
                    elif not e:
                        e = Equipment('?', remote_ip)
                        e.add_iface('?', remote_mac)
                        self.net.add_equipment(e)

        
        # Inspect all non-already inspected equipement
        done = False
        while not done:
            done = True
            for ip,e in self.net.equipments.items():
                if not e.inspected:
                    done = False

                    # Find the right inspector from equipment's first iface mac address
                    if e.ifaces:
                        e_first_mac = next(iter(e.ifaces.values())).mac
                        i = self.inspector(e_first_mac)
                    else:
                        # XXX Custom hack
                        if e.mgmtip.startswith('172.16.1'):
                            i = self.ubnt_inspector
                        elif e.mgmtip == '172.16.30.23':
                            i = self.edgemax_inspector
                        elif e.mgmtip.startswith('172.16.3'):
                            i = self.toughswitch_inspector
                        else:
                            i = self.dummy_inspector

                    i.connect(e)

                    # Inspect antennas
                    if isinstance(i, UbntInspector):
                        # Learn local interfaces
                        result = i.command('status.cgi')
                        for (ifname, mac) in result:
                            if ifname not in [ 'lo', 'wifi0', 'br0' ]: # XXX configurable filter
                                e.add_iface(ifname, mac)
                        # Learn bridge tables
                        result = i.command('brmacs.cgi')
                        for (ifname, mac) in result:
                            e.add_seen_mac(ifname, mac)

                    # Inspect switches
                    elif isinstance(i, ToughSwitchInspector):
                      result = i.command('ip-link')
                      switch_mac = '?'
                      for (ifname, mac) in result:
                          if ifname == 'br0': # XXX configurable filter
                              switch_mac = mac
                      result = i.command('mactable_data.cgi')
                      for (ifname, mac) in result:
                        e.add_iface(ifname, switch_mac) # XXX many non-usefull calls
                        e.add_seen_mac(ifname, mac)

                    elif isinstance(i, EdgeMaxInspector):
                        switch_mac = '?'
                        result = i.command('show-version')
                        for (key, value) in result:
                            if key == 'Burned In MAC Address':
                                switch_mac = value
                        result = i.command('mac-addr-table')
                        for (mac, ifname) in result:
                            e.add_iface(ifname, switch_mac) # XXX many non-usefull calls
                            e.add_seen_mac(ifname, mac)
                    else:
                        print("Notice: Nothing inspected on %s"%e)
                    i.disconnect()

    def compute_neighbourhood(self):

        ### Configuration

        # GATEWAY_IP and GATEWAY_IFACE_NAME define information about
        # the gateway, i.e., the center of the network.
        #
        # IGNORE_IP lists all IP that should not appear in the network
        # representation.
        gateway_ip = '172.16.0.254'
        gateway_iface_name = 'eth1'
        ignore_ip = ['172.16.0.253']

        ### State variables

        # FIXME: mac2ip() method is incomplete so it sometimes fail
        # finding the IP from the MAC of some interface. Meanwhile, we
        # build our own database.
        mac_to_ip = {}
        for (ip, equipment) in self.net.equipments.items():
            for interface in equipment.ifaces.values():
                mac_to_ip[interface.mac] = ip
        equipments = { ip: eq for ip, eq in self.net.equipments.items()
                       if (ip not in ignore_ip) and (ip != gateway_ip) }
        outer_net = []          # IP belonging to external levels.
        with_uplink = []        # IP already attached to an interface.

        ### Helper functions

        def is_outer_interface (interface):
            # Return True when INTERFACE is looking towards leaves of
            # the network.
            return all(mac not in mac_to_ip or # Ignore unknown eq
                       mac_to_ip[mac] in outer_net
                       for mac in interface.mac_seen)

        def is_at_next_level (equipment):
            # Return True when EQUIPMENT is adjacent to outer network.
            # This happens when it doesn't belong to outer network and
            # when all but one of its interfaces can only see MAC from
            # outer network. Return False otherwise. Assume EQUIPMENT
            # is not the gateway.
            if equipment.mgmtip in outer_net: return False
            exit_interface_flag = False
            for interface in equipment.ifaces.values():
                if is_outer_interface(interface): continue
                if exit_interface_flag: return False
                exit_interface_flag = True
            return True

        def set_uplink (ip, interface):
            # Set IP as a direct neighbour of INTERFACE, if it doesn't
            # have an uplink already.
            if ip not in with_uplink:
                interface.direct_neighbours.append(ip)
                with_uplink.append(ip)

        def link_to_outer_net (equipment):
            # Link EQUIPMENT with outer network. Orphans in the
            # outer network seen by an interface are linked to it.
            for interface in equipment.ifaces.values():
                if is_outer_interface(interface):
                    for mac in interface.mac_seen:
                        if mac in mac_to_ip:
                            set_uplink(mac_to_ip[mac], interface)

        ### Main

        # Walk the the network from the outside, i.e., leaves, to the
        # inside, i.e., the gateway, peeling the onion one layer at
        # a time.
        #
        # We know that an equipment is the current level when all but
        # one of its interfaces only see MAC from inferior levels (the
        # interface left being attached to uplink). This assumes that
        # all direct children of an equipment, at the very least, are
        # seen by the equipment. Unknown equipment, i.e., a MAC that
        # cannot be associated to an equipment in the network, is
        # ignored altogether.
        #
        # Once an equipment is known to be at the current level, we
        # attach it to the external network by linking every orphan
        # there to the equipment interface seeing it, if any.
        #
        # At the end of the process, we do the same for the gateway.
        # This requires a special step since there is no guarantee
        # that gateway sees all of its direct neighbours. However, all
        # orphans left in outer network are necessarily directly
        # attached to it.
        while equipments:
            current_level = []
            for (ip, equipment) in equipments.items():
                if is_at_next_level(equipment):
                    link_to_outer_net(equipment)
                    current_level.append(equipment.mgmtip)
            outer_net.extend(current_level)
            for ip in current_level: del equipments[ip]
        exit_iface = self.net.equipments[gateway_ip].ifaces[gateway_iface_name]
        for ip in outer_net: set_uplink(ip, exit_iface)