-
Notifications
You must be signed in to change notification settings - Fork 1
/
MTA.py
1613 lines (1477 loc) · 67.3 KB
/
MTA.py
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import meraki as mer
import pandas as pd
import pickle
import numpy as np
import multiprocessing
import argparse
import random
import math
import time
import netaddr
import csv
import os
import urllib.request
from scapy.layers.inet import IP, TCP, UDP
from tqdm import tqdm
from tqdm.utils import _term_move_up
from netaddr import *
from tabulate import tabulate
from multiprocessing import Pool
from scapy.all import *
from openpyxl import load_workbook
# For the DNS query we may have to do
import dns.resolver
from dns.exception import DNSException
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Verbosity
global VERBOSE
VERBOSE = False
# Border for our progress bars
global TERMSIZE
TERMSIZE = 1
try:
TERMSIZE = int((os.get_terminal_size()).columns)
except OSError as e:
# Couldnt get the size of the terminal so leaving it at the default of 15
TERMSIZE = 15
# Multiprocessing speeds
SLOW, MEDIUM, FAST, HOLDONTOYOURBUTTS = 1, 1, 1, 1
coreCount = multiprocessing.cpu_count()
if coreCount == 1:
SLOW, MEDIUM, FAST, HOLDONTOYOURBUTTS = 1, 1, 1, 1
else:
if coreCount <= 8:
SLOW = 1
MEDIUM = math.floor(coreCount * .5)
FAST = math.floor(coreCount * .75)
HOLDONTOYOURBUTTS = coreCount - 1
else:
SLOW = 4
MEDIUM = 6
FAST = 8
# I have found that by doing -1 I am making sure to leave room for the overhead and thus improving performance
HOLDONTOYOURBUTTS = coreCount - 1
# Logs go into a log directory and are $(unix time).log
LOGDIR = os.path.join(os.getcwd(), "logs")
LOGFILEPATH = os.path.join(LOGDIR, str(int(time.time())) + ".log")
# Meraki api calls generate a lot of cruff so we will jam them into here
MERLOGDIR = os.path.join(os.getcwd(), "meraki_logs")
if not os.path.isdir(LOGDIR):
os.mkdir(LOGDIR)
LOGFILE = open(LOGFILEPATH, "w")
else:
LOGFILE = open(LOGFILEPATH, "w")
if not os.path.isdir(MERLOGDIR):
os.mkdir(MERLOGDIR)
# Creating Excel Directory
if not os.path.isdir('excel'):
os.mkdir('excel')
# Controls verbose output
# Thanks to this stack overflow post I am able to upgrade this function to handle tqdm progress bars
# https://stackoverflow.com/questions/53874150/python-tqdm-is-there-a-way-to-print-something-between-a-progress-bar-and-what
def printv(m, pbar=None):
if type(m) is list:
m = "[" + ', '.join(str(x) for x in m) + "]"
if VERBOSE:
if pbar is not None:
border = "=" * (TERMSIZE)
clear_border = _term_move_up() + "\r" + " " * len(border) + "\r"
pbar.write(clear_border + "VERBOSE: %s" % m)
pbar.write(border)
else:
print("VERBOSE: " + m)
LOGFILE.write("VERBOSE: " + m + "\n")
else:
LOGFILE.write("VERBOSE: " + m + "\n")
# This saves an incredible amount of time as gathering client data can take 5-10 minutes on a larger scale
def load_sites(filename):
sites = pickle.load(open(filename, "rb"))
return sites
# Used when checking if a string is an int
def is_int(x):
try:
num = int(x)
except ValueError:
return False
return True
# client data is the only actual data that can go stale, saving our site variable to a file saves time in future runs
def save_sites(filename, sites):
pickle.dump(sites, open(filename, "wb"))
def get_vpn_rules(dashboard, organizationId, pbar=None):
orgRules = []
printv("Gathering Site-to-Site firewall rules for the organization", pbar)
try:
for x, acl in enumerate(
dashboard.appliance.getOrganizationApplianceVpnVpnFirewallRules(organizationId)['rules'][:-1]):
# Cleaning up the dict and formatting it accordingly
tmp = {'#': "VPN-" + str(x + 1).zfill(2), 'comment': acl['comment'], 'policy': acl['policy']}
# Formatting values
if 'any' in acl['srcCidr'].lower():
tmp['srcCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['srcCidr'] = [IPNetwork(network) for network in acl['srcCidr'].split(",")]
if 'any' in acl['destCidr'].lower():
tmp['dstCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['dstCidr'] = [IPNetwork(network) for network in acl['destCidr'].split(",")]
orgRules.append(tmp)
except mer.exceptions.APIError as e:
orgRules = None
return orgRules
def get_org_remote_vpn_participants(dashboard, organizationId, networkId):
# This shows us what each site is connected to on the S2S VPN
orgVpnData = dashboard.appliance.getOrganizationApplianceVpnStats(organizationId=organizationId)
siteVpnData = None
siteVpnData = [network for network in orgVpnData if network['networkId'] == networkId]
if siteVpnData is not None:
siteVpnData = siteVpnData[0]
peers = [(peer['networkId'], peer['networkName']) for peer in siteVpnData['merakiVpnPeers']]
peers.append((siteVpnData['networkId'], siteVpnData['networkName']))
return peers
def get_device_clients(dashboard, device, clientsPBar, n=1.0):
clientsPBar.set_description("Gathering client data on %s" % device['name'])
clientData = [c for c in dashboard.devices.getDeviceClients(device['serial'])]
clientsPBar.update(n)
clientsPBar.set_description("Gathering LLDP/CDP data on %s" % device['name'])
portData = dashboard.devices.getDeviceLldpCdp(device['serial'])
if 'ports' in portData:
for port, data in portData['ports'].items():
client = {
'description': None,
'dhcpHostname': None,
'id': None,
'ip': None,
'mac': None,
'mdnsName': None,
'switchport': port,
'usage': {'sent': 0.0, 'recv': 0.0},
'user': None,
'vlan': None
}
# Checking for any LLDP data
if 'lldp' in portData['ports']:
if 'managementAddress' in portData['ports'][port]['lldp']:
client['ip'] = portData['ports'][port]['lldp']['managementAddress']
if 'systemName' in portData['ports'][port]['lldp']:
client['description'] = portData['ports'][port]['lldp']['systemName']
if 'portId' in portData['ports'][port]['lldp']:
if ":" in portData['ports'][port]['lldp']['portId']:
macAddr = portData['ports'][port]['lldp']['portId']
macAddr = str(':'.join(macAddr[i:i + 2] for i in range(0, 12, 2))).upper()
client['mac'] = macAddr
# Checking for any CDP data
if 'cdp' in portData['ports'][port]:
if client['mac'] is None and 'deviceId' in portData['ports'][port]['cdp']:
macAddr = portData['ports'][port]['cdp']['deviceId']
macAddr = str(':'.join(macAddr[i:i + 2] for i in range(0, 12, 2))).upper()
client['mac'] = macAddr
else:
if 'deviceId' in portData['ports'][port]['cdp'] and client['description'] is None:
macAddr = portData['ports'][port]['cdp']['deviceId']
macAddr = str(':'.join(macAddr[i:i + 2] for i in range(0, 12, 2))).upper()
client['description'] = macAddr
if client['ip'] is None and 'address' in portData['ports'][port]['cdp']:
client['ip'] = portData['ports'][port]['cdp']['address']
if client['ip'] is not None:
clientData.append(client)
device['clients'] = clientData
clientsPBar.update(n)
return device
def get_acls(dashboard, networkId, pbar=None):
# MS ACLs
msACL = []
printv("Gathering ACL rules on the MS switches", pbar)
try:
for x, acl in enumerate(dashboard.switch.getNetworkSwitchAccessControlLists(networkId)['rules']):
# Cleaning up the dict and formatting it accordingly
tmp = {}
tmp['#'] = "MS-" + str(x + 1).zfill(2)
tmp['comment'] = acl['comment']
tmp['policy'] = acl['policy']
# Formatting values
if 'any' in acl['srcCidr'].lower():
tmp['srcCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['srcCidr'] = [IPNetwork(network) for network in acl['srcCidr'].split(",")]
if 'any' in acl['dstCidr'].lower():
tmp['dstCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['dstCidr'] = [IPNetwork(network) for network in acl['dstCidr'].split(",")]
msACL.append(tmp)
except mer.exceptions.APIError as e:
# printv("meraki.exceptions.APIError: MX L3 firewall, getNetworkL3FirewallRules - 4prompt Not Found")
# printi("This network does not have an MX appliance")
msACL = []
# MX Firewall
mxFW = []
printv("Gathering Firewalls rules on the MX appliances", pbar)
try:
for x, acl in enumerate(
dashboard.appliance.getNetworkApplianceFirewallL3FirewallRules(networkId)['rules'][:-1]):
# Cleaning up the dict and formatting it accordingly
tmp = {}
tmp['#'] = "MX-" + str(x + 1).zfill(2)
tmp['comment'] = acl['comment']
tmp['policy'] = acl['policy']
# Formatting values
if 'any' in acl['srcCidr'].lower():
tmp['srcCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['srcCidr'] = [IPNetwork(network) for network in acl['srcCidr'].split(",")]
if 'any' in acl['destCidr'].lower():
tmp['dstCidr'] = [IPNetwork('0.0.0.0/0')]
else:
tmp['dstCidr'] = [IPNetwork(network) for network in acl['destCidr'].split(",")]
mxFW.append(tmp)
except mer.exceptions.APIError as e:
# printv("meraki.exceptions.APIError: MX L3 firewall, getNetworkL3FirewallRules - 4prompt Not Found")
# printi("This network does not have an MX appliance")
mxFW = []
return msACL, mxFW
def get_vlan_name(v, sites):
if v == '6.6.6.6/6':
return "Internet"
for site in sites:
for vlan in site['VLANS']:
if vlan['subnet'] in IPNetwork(v):
return vlan['name']
return 'Unknown'
# Next we get our service names from ports csv from iana
# The functionality and purpose of this did not make it to v1.0 but may in the future
def get_port_data(filename):
columns = ['Port Number', 'Transport Protocol', 'Description']
url = 'https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv'
portData = pd.read_csv(url, usecols=columns)
pickle.dump(portData, open('portData.pkl', "wb"))
return portData
# https://stackoverflow.com/questions/55929578/python-using-pyshark-to-parse-pcap-file
# https://github.com/secdevopsai/Packet-Analytics/blob/master/Packet-Analytics.ipynb
# Modifying the code found in this guide to get our PCAP changed into a dataframe
def pcap_to_csv(filename: str):
pcap = rdpcap(filename)
# Collect field names from IP/TCP/UDP (These will be columns in DF)
ip_fields = [field.name for field in IP().fields_desc]
tcp_fields = [field.name for field in TCP().fields_desc]
udp_fields = [field.name for field in UDP().fields_desc]
dataframe_fields = ip_fields + ['time'] + tcp_fields
# Create blank DataFrame
df = pd.DataFrame(columns=dataframe_fields)
for packet in pcap[IP]:
# Field array for each row of DataFrame
field_values = []
# Add all IP fields to dataframe
for field in ip_fields:
if field == 'options':
# Retrieving number of options defined in IP Header
field_values.append(len(packet[IP].fields[field]))
else:
field_values.append(packet[IP].fields[field])
field_values.append(packet.time)
layer_type = type(packet[IP].payload)
for field in tcp_fields:
try:
if field == 'options':
field_values.append(len(packet[layer_type].fields[field]))
else:
field_values.append(packet[layer_type].fields[field])
except:
field_values.append(None)
# Add row to DF
df_append = pd.DataFrame([field_values], columns=dataframe_fields)
df = pd.concat([df, df_append], axis=0)
# Adjusting the time values
df['time'] = df['time'].apply(lambda x: float(x))
df.reset_index(drop=True, inplace=True)
df.sort_values('time')
df.reset_index(drop=True, inplace=True)
# Converting the protocol numbers to name
# https://stackoverflow.com/questions/37004965/how-to-turn-protocol-number-to-name-with-python
table = {num: name[8:] for name, num in vars(socket).items() if name.startswith("IPPROTO")}
df['proto'] = df['proto'].apply(lambda x: x if x not in table else table[x])
# Renaming our columns to match the names we will eventually expect
columnMap = {
'src': 'Source address',
'dst': 'Destination address',
'dport': 'Destination Port',
'proto': 'IP Protocol',
'time': 'Receive Time',
}
df.rename(columns=columnMap, inplace=True)
df['Application'] = 'None'
# Saving the dataframe to CSV
f = filename.split(".")[0] + ".csv"
df.to_csv(f, index=False)
return f
# Setting up our multiprocessing speed
def get_speed(length: int) -> int:
if length < 1000:
return SLOW
elif 1000 <= length < 50000:
return MEDIUM
elif 50000 <= length <= 500000:
return FAST
else:
return HOLDONTOYOURBUTTS
def convert_to_bytes(dfBytes, to, bsize=1024):
a = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
r = float(dfBytes)
return dfBytes / (bsize ** a[to])
def get_ip_data_caller(chunk):
sites = pickle.load(open('sites.pkl', "rb"))
discovered = dict()
chunk['temp'] = chunk.apply(get_ip_data, sites=sites, discovered=discovered, axis=1)
chunk[['SrcSite', 'SrcLocation', 'SrcVlanID', 'SrcVlanName',
'SrcVlanSubnet', 'SrcVlanLocation', 'DstSite', 'DstLocation',
'DstVlanID', 'DstVlanName', 'DstVlanSubnet', 'DstVlanLocation']] = \
chunk.temp.str.split(";", expand=True)
del chunk['temp']
return chunk
# This will take the IP and output which site (network) they are in, their vlan info, and their location if possible
def get_ip_data(row, sites, discovered):
# Information that we need
srcDone = False
srcData = {
'srcIp': row['SrcIP'],
'srcSite': None,
'srcLocation': None,
'srcVlanId': None,
'srcVlanName': None,
'srcVlanSubnet': None,
'srcVlanLocation': None
}
dstDone = False
dstData = {
'dstIp': row['DstIP'],
'dstSite': None,
'dstLocation': None,
'dstVlanId': None,
'dstVlanName': None,
'dstVlanSubnet': None,
'dstVlanLocation': None
}
# Checking if we already discovered source
if row['SrcIP'] in discovered:
srcData = {
'srcSite': discovered[row['SrcIP']]['Site'],
'srcLocation': discovered[row['SrcIP']]['Location'],
'srcVlanId': discovered[row['SrcIP']]['VlanId'],
'srcVlanName': discovered[row['SrcIP']]['VlanName'],
'srcVlanSubnet': discovered[row['SrcIP']]['VlanSubnet'],
'srcVlanLocation': discovered[row['SrcIP']]['VlanLocation']
}
srcDone = True
# Checking if we already discovered destination
if row['DstIP'] in discovered:
dstData = {
'dstSite': discovered[row['DstIP']]['Site'],
'dstLocation': discovered[row['DstIP']]['Location'],
'dstVlanId': discovered[row['DstIP']]['VlanId'],
'dstVlanName': discovered[row['DstIP']]['VlanName'],
'dstVlanSubnet': discovered[row['DstIP']]['VlanSubnet'],
'dstVlanLocation': discovered[row['DstIP']]['VlanLocation']
}
dstDone = True
# First thing that we need to handle are the public IP-es
# (addr.dst notin 10.0.0.0/8) OR (addr.dst notin 172.16.0.0/12) OR (addr.dst notin 192.168.0.0/16)
if not srcDone and not srcData['srcIp'].is_private():
srcData['srcSite'] = 'Internet'
srcData['srcLocation'] = 'None'
srcData['srcVlanId'] = 'None'
srcData['srcVlanName'] = 'None'
# For when we build out our firewall rules we will use this IPNetwork to define the internet
srcData['srcVlanSubnet'] = IPNetwork('6.6.6.6/32')
srcData['srcVlanLocation'] = 'None'
srcDone = True
if not dstDone and not dstData['dstIp'].is_private():
dstData['dstSite'] = 'Internet'
dstData['dstLocation'] = 'None'
dstData['dstVlanId'] = 'None'
dstData['dstVlanName'] = 'Internet'
# For when we build out our firewall rules we will use this IPNetwork to define the internet
dstData['dstVlanSubnet'] = IPNetwork('6.6.6.6/32')
dstData['dstVlanLocation'] = 'None'
dstDone = True
# If for some reason both the source and destination are internet addresses then this row is done
# This will also trigger if we have already processed the previous two IPes
if srcDone and dstDone:
if 'dstIp' in dstData:
del dstData['dstIp']
if 'srcIp' in srcData:
del srcData['srcIp']
return ';'.join([str(v) for v in srcData.values()] + [str(v) for v in dstData.values()])
for site in sites:
# Checking to see if we need to even look at this site
skipSrc = False
skipDst = False
if not srcDone:
if not any(cidr for cidr in site['Cidrs'] if srcData['srcIp'] in cidr):
skipSrc = True
else:
skipSrc = True
if not dstDone:
if not any(cidr for cidr in site['Cidrs'] if dstData['dstIp'] in cidr):
skipDst = True
else:
skipDst = True
if skipSrc and skipDst:
continue
# First thing we will go through are our VLANs since those yield the most amount of information
for vlan in site['VLANS']:
if (srcData['srcVlanName'] is not None or skipSrc) and (dstData['dstVlanName'] is not None or skipDst):
# printv("breaking 1")
break
# Source VLAN Information
if not skipSrc and srcData['srcVlanName'] is None:
# printv("checking source")
if srcData['srcIp'] in vlan['subnet']:
# printv("%s is in the vlan" % str(srcData['srcIp']))
srcData['srcSite'] = site['Name']
srcData['srcVlanId'] = vlan['vlanId']
srcData['srcVlanName'] = vlan['name'].strip()
srcData['srcVlanSubnet'] = vlan['subnet']
srcData['srcVlanLocation'] = vlan['location']
# Destination VLAN Information
if not skipDst and dstData['dstVlanName'] is None:
# printv("checking dest")
if dstData['dstIp'] in vlan['subnet']:
# printv("%s is in the vlan" % str(dstData['dstIp']))
dstData['dstSite'] = site['Name']
dstData['dstVlanId'] = vlan['vlanId']
dstData['dstVlanName'] = vlan['name'].strip()
dstData['dstVlanSubnet'] = vlan['subnet']
dstData['dstVlanLocation'] = vlan['location']
# Now we can try and get the location of the device by using the site client data
for device in site['Devices']:
srcLocation = []
dstLocation = []
if (srcData['srcLocation'] is not None or skipSrc) and (dstData['dstLocation'] is not None or skipDst):
break
for client in device['clients']:
if (srcData['srcLocation'] is not None or skipSrc) and (dstData['dstLocation'] is not None or skipDst):
break
# Source Location
if not skipSrc and srcData['srcLocation'] is None and \
client['ip'] is not None and \
srcData['srcIp'] == IPNetwork(client['ip']):
srcLocation.append(str(device['name'] + "-" + str(client['switchport'])))
# Destination Location
if not skipDst and dstData['dstLocation'] is None and \
client['ip'] is not None and \
dstData['dstIp'] == IPNetwork(client['ip']):
dstLocation.append(str(device['name'] + "-" + str(client['switchport'])))
if len(srcLocation) != 0:
srcData['srcLocation'] = " / ".join(srcLocation)
if len(dstLocation) != 0:
dstData['dstLocation'] = " / ".join(dstLocation)
# Lastly we check if we have all the information we need and thus can stop checking other sites
if (srcData['srcLocation'] is not None) and (dstData['dstLocation'] is not None) and \
(srcData['srcVlanName'] is not None) and (dstData['dstVlanName'] is not None):
break
# Now we do one final check before we return our data
# If we were unable to get the information we needed then we will replace the None values with 'Unknown'
for k, v in dstData.items():
if v is None:
# printv("dst %s was None" % k)
if k == 'dstSite':
# Because the ACL/FW/VPN section requires this to actually be set we are going to make a few assumptions
# If this was a public IP then it would have been caught above
# Thus this has to be a private IP and thus it has to be within the same site as the Source
# This is of course not 100%. Maybe the IP is supposed to be in another site
# However, it is safer to assume it is in the same site then guess which one it is
dstData['dstSite'] = srcData['srcSite']
else:
dstData[k] = 'Unknown'
for k, v in srcData.items():
if v is None:
# printv("src %s was None" % k)
if k == 'srcSite':
# See above
srcData['srcSite'] = dstData['dstSite']
else:
srcData[k] = 'Unknown'
# Lastly, since we are capturing from WDC, if both are unknown then they both are WDC
if dstData['dstSite'] is None and srcData['srcSite'] is None:
dstData['dstSite'] = 'WDC'
srcData['srcSite'] = 'WDC'
if 'dstIp' in dstData:
del dstData['dstIp']
if 'srcIp' in srcData:
del srcData['srcIp']
discovered[row['SrcIP']] = {
'Site': srcData['srcSite'],
'Location': srcData['srcLocation'],
'VlanId': srcData['srcVlanId'],
'VlanName': srcData['srcVlanName'],
'VlanSubnet': srcData['srcVlanSubnet'],
'VlanLocation': srcData['srcVlanLocation']
}
discovered[row['DstIP']] = {
'Site': dstData['dstSite'],
'Location': dstData['dstLocation'],
'VlanId': dstData['dstVlanId'],
'VlanName': dstData['dstVlanName'],
'VlanSubnet': dstData['dstVlanSubnet'],
'VlanLocation': dstData['dstVlanLocation']
}
ipData = ';'.join([str(v) for v in srcData.values()] + [str(v) for v in dstData.values()])
return ipData
def update_port_info_caller(chunk):
portData = pickle.load(open('portData.pkl', 'rb'))
chunk['PortData'] = chunk.apply(update_port_info, portData=portData, axis=1)
return chunk
# Making sure port info is correct
def update_port_info(row, portData):
app = []
app = [
p for p in portData
if str(p['Port Number']) == str(row['DstPort']) and str(p['Transport Protocol']) == str(row['Protocol'])
]
if len(app) == 0:
return 'Unknown'
else:
app = app[0]
if app['Description'] == 'Unassigned':
return 'Unknown'
else:
return app['Description']
return 'Unknown'
def get_packet_path_data_caller(chunk):
sites = pickle.load(open('sites.pkl', 'rb'))
chunk = chunk.apply(get_packet_path_data, sites=sites, axis=1)
return chunk
def get_packet_path_data(row, sites):
# Import Information:
# There is a gotcha here that we need to be looking out for and that is the fact that ACL is stateless
# This means that the ACL rule list needs to explicitly allow for the communication to go both ways
# The MX FW and S2S VPN is stateful so if it allows the packet in then it will allow it back out
'''
# Source ACL Out
# Source ACL In
# Source Firewall
# Organization Site to Site
# Destination Firewall
# Destination ACL In
# Destination ACL Out
'''
src = row['SrcSite']
dst = row['DstSite']
srcIp = row['SrcIP']
dstIp = row['DstIP']
# External to Internal or External to External
if src == "Internet":
if dst != "Internet":
# In this case the packet will go through the MX FW and then the MS ACL
site = [site for site in sites if site['Name'] == dst][0]
aclList = site['ACL']
fwList = site['Firewall']
outImpact, outRuleNumber = get_rule_list_impact(srcIp, dstIp, aclList)
inImpact, inRuleNumber = get_rule_list_impact(dstIp, srcIp, aclList)
fwImpact, fwRuleNumber = get_rule_list_impact(srcIp, dstIp, fwList)
data = "External -> Internal; None; None; None; None; None; None; None; None; %s; %s; %s; %s; %s; %s" % \
(fwImpact, fwRuleNumber, inImpact, inRuleNumber, outImpact, outRuleNumber)
row['temp'] = data
return row
else:
# I honestly have no clue how to handle this one. Ima just put None.
# Yeah....1 week later still no clue
data = "External -> External; None; None; None; None; None; None; None; None; None; None; None; None; " \
"None; None "
row['temp'] = data
return row
# Internal to Internal
elif src == dst:
# Since the source and destination are in the same site we only need to feed the aux function one ACL list
aclList = [site for site in sites if site['Name'] == src][0]['ACL']
outImpact, outRuleNumber = get_rule_list_impact(srcIp, dstIp, aclList)
inImpact, inRuleNumber = get_rule_list_impact(dstIp, srcIp, aclList)
data = "Internal -> Internal; %s; %s; %s; %s; None; None; None; None; None; None; %s; %s; %s; %s" % \
(outImpact, outRuleNumber, inImpact, inRuleNumber, outImpact, outRuleNumber, inImpact, inRuleNumber)
row['temp'] = data
return row
# Internal to External
elif src != "Internet" and dst == "Internet":
# In this case the packet will go through the MS ACL and then the MX FW
site = [site for site in sites if site['Name'] == src]
if len(site) == 0:
printv("------")
printv(src)
printv(dst)
printv(srcIp)
printv(dstIp)
printv("------")
raise Exception('SOMETHING BAD HAS HAPPENED')
else:
site = site[0]
aclList = site['ACL']
fwList = site['Firewall']
outImpact, outRuleNumber = get_rule_list_impact(srcIp, dstIp, aclList)
inImpact, inRuleNumber = get_rule_list_impact(dstIp, srcIp, aclList)
fwImpact, fwRuleNumber = get_rule_list_impact(srcIp, dstIp, fwList)
data = "Internal -> External; %s; %s; %s; %s; %s; %s; None; None; None; None; None; None; None; None" % \
(outImpact, outRuleNumber, inImpact, inRuleNumber, fwImpact, fwRuleNumber)
row['temp'] = data
return row
# Site to Site
else:
# Site to Site will involve the most amount of processing as it has to hit every bump on the road
srcSite = [site for site in sites if site['Name'] == src]
if len(srcSite) == 0:
printv("------")
printv(src)
printv(dst)
printv(srcIp)
printv(dstIp)
printv("------")
raise Exception('SOMETHING BAD HAS HAPPENED')
else:
srcSite = srcSite[0]
dstSite = [site for site in sites if site['Name'] == dst]
if len(dstSite) == 0:
printv("------")
printv(src)
printv(dst)
printv(srcIp)
printv(dstIp)
printv("------")
raise Exception('SOMETHING BAD HAS HAPPENED')
else:
dstSite = dstSite[0]
organization = [site for site in sites if site['Name'] == 'Organization'][0]
srcAclList = srcSite['ACL']
srcFwList = srcSite['Firewall']
dstAclList = dstSite['ACL']
dstFwList = dstSite['Firewall']
s2sList = organization['VPN Rules']
# Source ACL out and in
srcOutImpact, srcOutRuleNumber = get_rule_list_impact(srcIp, dstIp, srcAclList)
srcInImpact, srcInRuleNumber = get_rule_list_impact(dstIp, srcIp, srcAclList)
# Source FW
srcFwImpact, srcFwRuleNumber = get_rule_list_impact(srcIp, dstIp, srcFwList)
# Organization S2S VPN
orgImpact, orgRuleNumber = get_rule_list_impact(srcIp, dstIp, s2sList)
# Destination FW
dstFwImpact, dstFwRuleNumber = get_rule_list_impact(srcIp, dstIp, dstFwList)
# Destination ACL in and out
dstInImpact, dstInRuleNumber = get_rule_list_impact(srcIp, dstIp, dstAclList)
dstOutImpact, dstOutRuleNumber = get_rule_list_impact(dstIp, srcIp, dstAclList)
data = "Site -> Site; %s; %s; %s; %s; %s; %s; %s; %s; %s; %s; %s; %s; %s; %s" % \
(
srcOutImpact, srcOutRuleNumber, srcInImpact, srcInRuleNumber, srcFwImpact, srcFwRuleNumber,
orgImpact, orgRuleNumber,
dstFwImpact, dstFwRuleNumber, dstInImpact, dstInRuleNumber, dstOutImpact, dstOutRuleNumber
)
row['temp'] = data
return row
def get_rule_list_impact(source, destination, ruleList):
for rule in ruleList:
# If the source is impacted by the rule then we check the destination
if any(network for network in rule['srcCidr'] if source in network):
# If the destination is also impacted then the rule has impact
if any(network for network in rule['dstCidr'] if destination in network):
return rule['policy'], rule['#'].split("-")[1]
# One way or another it should hit a rule so it hitting this return is actually really bad
return None, None
def format_df_values_caller(chunk, networks=None):
# Let's say you have a VLAN that the people in HR use, 10.10.10.0/24
# These people are going to be talking out to the internet constantly
# If you want to reduce clutter you can change all the public IP-es talking to and from those VLANs to 1 network
# So instead of having 10.10.10.0/24 listed as talking to 100s of public IP-es
# it will instead be listed in the data as talking to 6.6.6.6/6
# For me I did not care if certain VLANs were talking to the internet only that they were in the first place
# Using the example above we would set ipes to [IPNetwork(10.10.10.0/24)]
# Maybe someday I will make this a command line argument but alas 24 hours in the day
ipes = None
# We have to make this array like this because of how pandas .isin function works
if ipes is not None:
ipes = [str(ip) for network in networks for ip in list(network)]
else:
ipes = []
return format_df_values(chunk, ipes)
# See https://github.com/picnicsecurity/Meraki-Traffic-Analyzer#Tailoring-the-Code for an explaination on this code and its purpose
def format_df_values(chunk, ipes):
col = 'SrcIP'
# Look...dont judge. This is just something you are going to have to accept and move on
chunk.loc[
(chunk[col].isin(ipes)),
'DstIP'
] = chunk.loc[
(chunk[col].isin(ipes)),
'DstIP'
].apply(
lambda x: IPNetwork('6.6.6.6/32') if not IPNetwork(x).is_private() else x
)
col = 'DstIP'
# Keep moving
chunk.loc[
(chunk[col].isin(ipes)),
'SrcIP'
] = chunk.loc[
(chunk[col].isin(ipes)),
'SrcIP'
].apply(
lambda x: IPNetwork('6.6.6.6/32') if not IPNetwork(x).is_private() else x
)
chunk['SrcIP'] = chunk['SrcIP'].apply(lambda x: IPNetwork(x))
chunk['DstIP'] = chunk['DstIP'].apply(lambda x: IPNetwork(x))
return chunk
def resolve_ip_caller(chunk):
# This is where we will store previously looked up values
discovered = dict()
if os.path.isfile('dns_servers.pkl'):
servers = pickle.load(open('dns_servers.pkl', "rb"))
else:
servers = ['1.1.1.1', '1.0.0.1']
chunk = chunk.apply(resolve_ip, discovered=discovered, servers=servers, axis=1)
return chunk
def resolve_ip(row, discovered, servers):
resolver = dns.resolver.Resolver()
resolver.nameservers = servers
resolver.timeout = 1
resolver.lifetime = 1
src = row['SrcIP']
dst = row['DstIP']
# SOURCE
tmp = str(src).strip().split("/")[0].split(".")
tmp.reverse()
inaddr = ".".join(tmp) + ".in-addr.arpa"
if inaddr in discovered:
row['SrcName'] = discovered[inaddr]
else:
try:
result = resolver.query(inaddr, 'PTR')
name = str(result[0].to_text())[:-1]
row['SrcName'] = name
# discovered[inaddr] = name
except DNSException as e:
row['SrcName'] = 'Unknown'
# discovered[inaddr] = 'Unknown'
# DESTINATION
tmp = str(dst).strip().split("/")[0].split(".")
tmp.reverse()
inaddr = ".".join(tmp) + ".in-addr.arpa"
if inaddr in discovered:
row['DstName'] = discovered[inaddr]
else:
try:
result = resolver.query(inaddr, 'PTR')
name = str(result[0].to_text())[:-1]
row['DstName'] = name
discovered[inaddr] = name
except DNSException as e:
row['DstName'] = 'Unknown'
discovered[inaddr] = 'Unknown'
return row
# This is where the true magic happens. Without this function, our program would take literally forever to finish
# In the next version I will add support for **kwargs so that we can bypass the need to have these "caller" functions. Itll also give us a lot more features
def parallelize_workload(data, function, n_cores):
printv("%s is being called with %d cores" % (function.__name__, n_cores))
if n_cores == 1:
pbar = tqdm(total=n_cores + 2)
pbar.set_description('Parallel Workload Status')
data = function(data)
while pbar.n < pbar.total:
pbar.update()
pbar.close()
return data
else:
pbar = tqdm(total=n_cores + 2)
pbar.set_description('Parallel Workload Status')
dfSplit = np.array_split(data, n_cores)
pool = Pool(n_cores)
poolMap = []
# Inner function to help display status
def status_update(retval):
poolMap.append(retval)
pbar.update()
for chunk in dfSplit:
pool.apply_async(func=function, args=[chunk], callback=status_update)
pool.close()
pool.join()
pbar.update()
data = pd.concat(poolMap)
while pbar.n < pbar.total:
pbar.update()
pbar.close()
return data
# A site is defined as a Meraki network
# This loads up a bunch of data about all of the sites of the organization into a variable for use throughout the script
def get_sites(dashboard, organizationId, networks, get_clients=False):
sites = []
# First thing we do is gather some globals
organization = dashboard.organizations.getOrganization(organizationId)
s2sRules = get_vpn_rules(dashboard, organizationId, None)
organizationWide = {
'Name': 'Organization',
'Organization Name': organization['name'],
'VPN Rules': s2sRules,
'NetworkID': organization['id'],
'Devices': [],
'Clients': [],
'VLANS': [],
'Peers': [],
'VPNSubnets': [],
'ACL': [],
'Firewall': [],
'Cidrs': []
}
sites.append(organizationWide)
for network in networks:
sitesPBar = tqdm(range(0, 100), leave=True)
sitesPBar.set_description("Processing %s" % network['name'])
# Site Name and ID
printv("Gathering identifiers", sitesPBar)
siteName = network['name']
networkId = network['id']
sitesPBar.update(20)
# VPN Subnets
if "appliance" in network["productTypes"]:
tic = time.perf_counter()
printv("Gathering VPN data", sitesPBar)
peers = get_org_remote_vpn_participants(dashboard, organizationId, networkId)
sitesPBar.update(10)
vpnSubnets = [
IPNetwork(subnet['localSubnet'])
for subnet in dashboard.appliance.getNetworkApplianceVpnSiteToSiteVpn(networkId)['subnets']
if subnet['useVpn']
]
toc = time.perf_counter()
printv(f"Gathering VPN data took {toc - tic:0.4f} seconds to process", sitesPBar)
sitesPBar.update(10)
else:
sitesPBar.update(20)
# VLANs
if "switch" in network["productTypes"]:
tic = time.perf_counter()
printv("Gathering VLAN data from switch stacks", sitesPBar)
vlanList = []
checkedSerials = []
cidrList = []
# Grabbing VLANs from any MS series switches starting with switch stacks
try:
for stack in dashboard.switch.getNetworkSwitchStacks(networkId):
for serial in stack['serials']:
checkedSerials.append(serial)
for vlan in dashboard.switch.getNetworkSwitchStackRoutingInterfaces(networkId=networkId,
switchStackId=stack['id']):
vlan['subnet'] = IPNetwork(vlan['subnet'])
if vlan['subnet'] in vpnSubnets:
vlan['inVpn'] = True
else:
vlan['inVpn'] = False
vlan['MS'] = True
vlan['location'] = stack['name']
cidrList.append(vlan['subnet'])
vlanList.append(vlan)
except mer.exceptions.APIError as e:
# This error will be thrown when dealing with networks that do not have switch stacks
# In the context of my organization this is our AWS Virtual MX
printv("No switch stacks in this network", sitesPBar)
sitesPBar.update(2.5)
# Next we check for any layer 3 interfaces on switches that are not in stacks
# Gathering the devices
ttic = time.perf_counter()
printv("Gathering VLAN data from switches", sitesPBar)
devices = [device for device in dashboard.networks.getNetworkDevices(networkId=networkId)
if 'MS' in device['model'] or 'MR' in device['model']]
for device in devices:
if 'name' not in device:
device['name'] = device['mac']
devices.sort(key=lambda x: x['name'], reverse=True)
sitesPBar.update(2.5)
ttoc = time.perf_counter()
printv(f"Gathering devices took {ttoc - ttic:0.4f} seconds to process", sitesPBar)
# Checking for layer 3 interfaces
for device in devices:
if device['serial'] in checkedSerials or 'MS' not in device['model']:
continue
else:
for vlan in dashboard.switch.getDeviceSwitchRoutingInterfaces(device['serial']):
vlan['subnet'] = IPNetwork(vlan['subnet'])
if vlan['subnet'] in vpnSubnets:
vlan['inVpn'] = True
else:
vlan['inVpn'] = False
vlan['MS'] = True
vlan['location'] = device['name']
cidrList.append(vlan['subnet'])
vlanList.append(vlan)
sitesPBar.update(2.5)
else:
sitesPBar.update(7.5)
# Lastly we get any VLANs that might be on the MX
if "appliance" in network["productTypes"]: