forked from NLADC/dissector
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ddos_dissector.py
executable file
·1731 lines (1419 loc) · 65.6 KB
/
ddos_dissector.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
# Concordia Project
#
# This project has received funding from the European Union’s Horizon
# 2020 Research and Innovation program under Grant Agreement No 830927.
#
# Maintained by
# Thijs van den Hout (SIDN) - thijs.vandenhout@sidn.nl
###############################################################################
###############################################################################
# Python modules
import time
import threading
import sys
import subprocess
import socket
import signal
import shutil
import requests
import re
import copy
import queue as queue
import pandas as pd
import os
import numpy as np
import logging
import json
import hashlib
import cursor
import configparser
import ipaddr
import argparse
import urllib3
from subprocess import check_output
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter
from pygments import highlight
from io import StringIO
from datetime import datetime
from argparse import RawTextHelpFormatter
###############################################################################
# Program settings
VERBOSE, QUIET, DEBUG, NOVERIFY = False, False, False, False
program_name = os.path.basename(__file__)
version = "3.2"
# GLOBAL parameters
# percentage used to determine correlation between to lists
LOGGER = logging.getLogger(__name__) # Is customized when calling main()
SIMILARITY_THRESHOLD = 80
NONE = -1
FLOW_TYPE = 0
PCAP_TYPE = 1
CARPET_BOMBING_SIMILARITY_THRESHOLD = 20
# define local subnet (CIDR size)
CARPET_BOMBING_SUBNET = 20
###############################################################################
# Subroutines
# ------------------------------------------------------------------------------
def parser_add_arguments():
"""
Parse comamnd line parameters
"""
parser = argparse.ArgumentParser(prog=program_name, usage='%(prog)s [options]',
epilog="Example: ./%(prog)s -f ./pcap_samples/sample1.pcap --summary --upload ",
formatter_class=RawTextHelpFormatter)
parser.add_argument("--version", help="print version and exit", action="store_true")
parser.add_argument("-v", "--verbose", help="print info msg", action="store_true")
parser.add_argument("-d", "--debug", help="print debug info", action="store_true")
parser.add_argument("-q", "--quiet", help="ignore animation", action="store_true")
parser.add_argument("--status", dest='status', help="check available repositories", action="store_true")
parser.add_argument("-s", "--summary", help="present fingerprint evaluation summary", action="store_true")
parser.add_argument("-u", "--upload", help="upload to the selected repository", action="store_true")
parser.add_argument("--log", default='ddos_dissector.log', nargs='?',
help="Log filename. Default =./ddos_dissector.log\"")
parser.add_argument("--fingerprint_dir", default='fingerprints', nargs='?',
help="Fingerprint storage directory. Default =./fingerprints\"")
parser.add_argument("--config", default='ddosdb.conf', nargs='?',
help="Configuration File. Default =./ddosdb.conf\"")
parser.add_argument("--host", nargs='?', help="Upload host. ")
parser.add_argument("--user", nargs='?', help="repository user. ")
parser.add_argument("--passwd", nargs='?', help="repository password.")
parser.add_argument("-n", "--noverify",
help="disable verification of the host certificate (for self-signed certificates)",
action="store_true")
parser.add_argument("-g", "--graph",
help="build dot file (graphviz). It can be used to plot a visual representation\n of the "
"attack using the tool graphviz. When this option is set, youn will\n received "
"information how to convert the generate file (.dot) to image (.png).",
action="store_true")
parser.add_argument('-f', '--filename', required=True, nargs='+')
return parser
# ------------------------------------------------------------------------------
def signal_handler():
"""
Signal handler
"""
sys.stdout.flush()
print('\nCtrl+C detected.')
cursor.show()
sys.exit(0)
# ------------------------------------------------------------------------------
class CustomConsoleFormatter(logging.Formatter):
"""
Log facility format
"""
def format(self, record):
formatter = "%(levelname)s - %(message)s"
if record.levelno == logging.INFO:
green = '\033[32m'
reset = "\x1b[0m"
log_fmt = green + formatter + reset
self._style._fmt = log_fmt
return super().format(record)
if record.levelno == logging.DEBUG:
cyan = '\033[36m'
reset = "\x1b[0m"
log_fmt = cyan + formatter + reset
self._style._fmt = log_fmt
return super().format(record)
if record.levelno == logging.ERROR:
magenta = '\033[35m'
reset = "\x1b[0m"
log_fmt = magenta + formatter + reset
self._style._fmt = log_fmt
return super().format(record)
if record.levelno == logging.WARNING:
yellow = '\033[33m'
reset = "\x1b[0m"
log_fmt = yellow + formatter + reset
self._style._fmt = log_fmt
else:
self._style._fmt = formatter
return super().format(record)
# ------------------------------------------------------------------------------
def get_logger(args):
"""
Instanciate logging facility. By default, info logs are also
stored in the logfile.
param: cmd line args
"""
logger = logging.getLogger(__name__)
# add custom formatter
my_formatter = CustomConsoleFormatter()
# Create handlers
console_handler = logging.StreamHandler()
console_handler.setFormatter(my_formatter)
# enable file logging when verbose/debug is set
if args.debug or args.verbose:
file_handler = logging.FileHandler(args.log)
if args.debug:
logger.setLevel(logging.DEBUG)
file_handler.setLevel(logging.DEBUG)
elif args.verbose:
logger.setLevel(logging.INFO)
file_handler.setLevel(logging.INFO)
f_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)")
file_handler.setFormatter(f_format)
logger.addHandler(file_handler)
# add handlers to the logger
logger.addHandler(console_handler)
return logger
# ------------------------------------------------------------------------------
def upload(json_file, user, passw, host, key):
"""
Upload a fingerprint and attack vector to DDoSDB
:param json_file: path to fingerprint generated file
:param user: DDoSDB username
:param passw: DDoSDB password
:param host: ddosdb instance url
:param key: fingerprint identifier
:return: status_code describing HTTP code received
"""
if not os.path.isfile(json_file):
LOGGER.critical("Could not read the fingerprint json file {}".format(json_file))
files = {
"json": open(json_file, "rb"),
# ignoring pcap file upload for now
"pcap": open(json_file, "rb"),
}
# build headers for repo fingerprint submission
headers = {
"X-Username": user,
"X-Password": passw,
"X-Filename": key
}
try:
urllib3.disable_warnings()
r = requests.post(host + "upload-file", files=files, headers=headers, verify=not NOVERIFY)
except requests.exceptions.SSLError as e:
LOGGER.critical("SSL Certificate verification of the server {} failed".format(host))
print("If you trust {} re-run with --noverify / -n flag to disable certificate verification".format(host))
LOGGER.debug("Cannot connect to the server to upload fingerprint: {}".format(e))
return None
except requests.exceptions.RequestException as e:
LOGGER.critical("Cannot connect to the server to upload fingerprint")
LOGGER.debug("Cannot connect to the server to upload fingerprint: {}".format(e))
print(e)
return None
if r.status_code == 403:
print("Invalid credentials or no permission to upload fingerprints:")
elif r.status_code == 201:
print("Upload success: \n\tHTTP CODE [{}] \n\tFingerprint ID [{}]".format(r.status_code, key))
print("\tURL: {}query?q={}".format(host, key))
else:
print("Internal Server Error. Check repository Django logs.")
print("Error Code: {}".format(r.status_code))
return r.status_code
# ------------------------------------------------------------------------------
def get_repository(args, config):
"""
Check credentials and repository based on configuration file or cmd line args
:param args: cmd args
:param config: configuration file
return: user,pass,host: credentials for the repository
"""
user, passw, host = (None,) * 3
# look for the repository to upload
if not args.host:
LOGGER.info("Upload host not defined. Pick the first one in the configuration file.")
config_host = config.sections()[0]
if not config_host:
LOGGER.critical("Could not find repository configuration. Check configuration file [dddosdb.conf].")
else:
LOGGER.info("Assumming configuration section [{}].".format(config_host))
user = config[config_host]['user']
passw = config[config_host]['passwd']
host = config[config_host]['host']
elif args.host:
host = args.host
if args.user and args.passwd:
user = args.user
passw = args.passwd
# user/pass not defined by cmd line
else:
# try to find in the configuration file
if args.host in config.sections():
LOGGER.info("Host found in the configuration file")
user = config[args.host]['user']
passw = config[args.host]['passwd']
else:
LOGGER.critical("Credentials not found for [{}].".format(args.host))
else:
LOGGER.critical(
"Cannot find repository {} credentials. You should define in the cmd line or configuration file "
"[dddosdb.conf].".format(args.host))
return None
return user, passw, host
# ------------------------------------------------------------------------------
def prepare_tshark_cmd(input_path):
"""
Prepare the tshark command that converts a PCAP to a CSV.
:param input_path: filename
return: tshark command line to be used to convert the file
"""
tshark = shutil.which("tshark")
if not tshark:
LOGGER.error("Tshark software not found. It should be on the path.\n")
return
cmd = [tshark, '-r', input_path, '-T', 'fields']
# fields included in the csv
fields = [
'dns.qry.type', 'ip.dst', 'ip.flags.mf', 'tcp.flags', 'ip.proto',
'ip.src', '_ws.col.Destination', '_ws.col.Protocol', '_ws.col.Source',
'dns.qry.name', 'eth.type', 'frame.len', 'udp.length',
'http.request', 'http.response', 'http.user_agent', 'icmp.type',
'ip.frag_offset', 'ip.ttl', 'ntp.priv.reqcode', 'tcp.dstport',
'tcp.srcport', 'udp.dstport', 'udp.srcport', 'frame.time_epoch',
]
for f in fields:
cmd.append('-e')
cmd.append(f)
# field options
options = ['header=y', 'separator=,', 'quote=d', 'occurrence=f']
for o in options:
cmd.append('-E')
cmd.append(o)
return cmd
# ------------------------------------------------------------------------------
def flow_to_df(ret, filename):
"""
Convert flow file (nfdump) to DataFrame structure.
:param ret: buffer used to return the dataframe itself
:param filename: flow file
return ret: dataframe
"""
nfdump = shutil.which("nfdump")
if not nfdump:
LOGGER.error("NFDUMP software not found. It should be on the path.")
ret.put(NONE)
cmd = [nfdump, '-r', filename, '-o', 'extended', '-o', 'json']
try:
cmd_stdout = check_output(cmd, stderr=subprocess.DEVNULL)
except Exception as e:
ret.put(NONE)
sys.exit(e)
if not cmd_stdout:
ret.put(NONE)
sys.exit()
data = str(cmd_stdout, 'utf-8')
data = StringIO(data)
df = pd.read_json(data).fillna(NONE)
df = df[df.columns.intersection(['t_first', 't_last', 'proto', 'src4_addr', 'dst4_addr',
'src_port', 'dst_port', 'fwd_status', 'tcp_flags',
'src_tos', 'in_packets', 'in_bytes', 'icmp_type',
'icmp_code',
])]
df = df.rename(columns={'dst4_addr': 'ip_dst',
'src4_addr': 'ip_src',
'src_port': 'srcport',
'dst_port': 'dstport',
't_start': 'frame_time_epoch',
})
df.dstport = df.dstport.astype(float).astype(int)
df.srcport = df.srcport.astype(float).astype(int)
# convert protocol number to name
protocol_names = {num: name[8:] for name, num in vars(socket).items() if name.startswith("IPPROTO")}
df['proto'] = df['proto'].apply(lambda x: protocol_names[x])
# convert protocol/port to service
def convert_protocol_service(row):
try:
highest_protocol = socket.getservbyport(row['dstport'], row['proto'].lower()).upper()
return highest_protocol
except (OSError, OverflowError, TypeError):
LOGGER.debug(f"Could not resolve service running {row['proto']} at port {row['dstport']}, using 'UNKNOWN'")
return "UNKNOWN"
df['highest_protocol'] = df[['dstport', 'proto']].apply(convert_protocol_service, axis=1)
# convert to unix epoch (sec)
df['frame_time_epoch'] = pd.to_datetime(df['t_first']).astype(int) / 10 ** 9
df = df.drop(['t_last', 't_first', 'fwd_status'], axis=1)
ret.put(df)
# ------------------------------------------------------------------------------
def pcap_to_df(ret, filename):
"""
Convert pcap file to DataFrame structure.
:param ret: buffer used to return the dataframe itself
:param filename: flow file
return ret: dataframe
"""
cmd = prepare_tshark_cmd(filename)
if not cmd:
ret.put(NONE)
sys.exit()
try:
cmd_stdout = check_output(cmd, stderr=subprocess.DEVNULL)
except Exception as e:
ret.put(NONE)
sys.exit(e)
if not cmd_stdout:
ret.put(NONE)
sys.exit()
data = str(cmd_stdout, 'utf-8')
data = StringIO(data)
df = pd.read_csv(data, low_memory=False, error_bad_lines=False)
# src/dst port
if {'tcp.srcport', 'udp.srcport', 'tcp.dstport', 'udp.dstport'}.issubset(df.columns):
# Combine source and destination ports from tcp and udp
df['srcport'] = df['tcp.srcport'].fillna(df['udp.srcport'])
df['dstport'] = df['tcp.dstport'].fillna(df['udp.dstport'])
df['dstport'] = df['dstport'].fillna(NONE).astype(float).astype(int)
df['srcport'] = df['srcport'].fillna(NONE).astype(float).astype(int)
if {'ip.src', 'ip.dst', '_ws.col.Source', '_ws.col.Destination'}.issubset(df.columns):
# Combine source and destination IP - works for IPv6
df['ip.src'] = df['ip.src'].fillna(df['_ws.col.Source'])
df['ip.dst'] = df['ip.dst'].fillna(df['_ws.col.Destination'])
# rename protocol field
df = df.rename({'_ws.col.Protocol': 'highest_protocol'}, axis=1)
# protocol number to name
protocol_names = {num: name[8:] for name, num in vars(socket).items() if name.startswith("IPPROTO")}
df['ip.proto'] = df['ip.proto'].fillna(NONE).astype(float).astype(int)
df['ip.proto'] = df['ip.proto'].apply(lambda x: protocol_names[x] if (x in protocol_names) else -1)
df['ip.ttl'] = df['ip.ttl'].fillna(NONE).astype(float).astype(int)
df['udp.length'] = df['udp.length'].fillna(NONE).astype(float).astype(int)
df['ntp.priv.reqcode'] = df['ntp.priv.reqcode'].fillna(NONE).astype(float).astype(int)
# timestamp
try:
df['start_timestamp'] = df['frame.time_epoch'].iloc[0]
except IndexError:
LOGGER.info("Could not find a timestamp.")
# Remove columns: 'tcp.srcport', 'udp.srcport','tcp.dstport', 'udp.dstport', _ws.col.Source, _ws.col.Destination
df.drop(['tcp.srcport', 'udp.srcport', 'tcp.dstport', 'udp.dstport', '_ws.col.Source', '_ws.col.Destination'],
axis=1, inplace=True)
# Drop all empty columns (for making the analysis more efficient! less memory.)
df.dropna(axis=1, how='all', inplace=True)
df = df.fillna(NONE)
if 'icmp.type' in df.columns:
df['icmp.type'] = df['icmp.type'].astype(int)
if 'dns.qry.type' in df.columns:
df['dns.qry.type'] = df['dns.qry.type'].astype(int)
if 'ip.frag_offset' in df.columns:
df['ip.frag_offset'] = df['ip.frag_offset'].astype(int)
if 'ip.flags.mf' in df.columns:
df['ip.flags.mf'] = df['ip.flags.mf'].astype(int)
if ('ip.flags.mf' in df.columns) and ('ip.frag_offset' in df.columns):
# Analyse fragmented packets
df['fragmentation'] = (df['ip.flags.mf'] == 1) | (df['ip.frag_offset'] != 0)
df.drop(['ip.flags.mf', 'ip.frag_offset'], axis=1, inplace=True)
df.columns = [c.replace('.', '_') for c in df.columns]
ret.put(df)
# ------------------------------------------------------------------------------
# Function for calculating the TOP 'N' and aggregate the 'others'
# Create a dataframe with the top N values and create an 'others' category
def top_n_dataframe(dataframe_field, df, n_type, top_n=20):
"""
Find top n values in one dataframe
:param dataframe_field: field to be evaluated
:param df: full dataframe
:param n_type: network file type (pcap or flow)
:param top_n: build dataframe with the top_n results
return df: dataframe itself
"""
field_name = dataframe_field.name
if field_name == "frame_time_epoch" or field_name == "start_timestamp":
return pd.DataFrame()
# flow - different heuristic
if n_type == FLOW_TYPE:
if field_name == "in_packets":
return pd.DataFrame()
data = df.groupby(field_name)["in_packets"].sum().sort_values(ascending=False)
top = data[:top_n].reset_index()
top.columns = [field_name, 'count']
new_row = pd.DataFrame(data={
'count': [data[top_n:].reset_index().iloc[:, 1].sum()],
field_name: ['others'],
})
# pcap
else:
top = df[field_name].value_counts().reset_index()[:top_n]
new_row = pd.DataFrame(data={
'count': [df[field_name].value_counts().reset_index()[top_n:][field_name].sum()],
field_name: ['others'],
})
# combine the result dataframe (top_n + aggregated 'others')
top.columns = [field_name, 'count']
top_result = pd.concat([top, new_row], sort=False)
# percentage field
df = top_result.groupby(field_name).sum()
df = df.sort_values(by="count", ascending=False)
df['percent'] = df.transform(lambda x: (x / np.sum(x) * 100).round()).astype(int)
if len(df) < 16:
# z-score useless when few elements
df['zscore'] = NONE
else:
# z-score of 2 indicates that an observation is two standard deviations above the average
# a z-score of zero represents a value that equals the mean.
df['zscore'] = ((df['count'] - df['count'].mean()) / df['count'].std(ddof=0)).round().fillna(NONE)
return df.reset_index()
# ------------------------------------------------------------------------------
def infer_target_ip(df, n_type):
"""
df: dataframe from pcap
n_type: network file type (flows,pcap)
return: list of target IPs
"""
# Check the dst_ip frequency distribution.
# When the second most often dst_ip is grouped in the category "others" (remains)
# this means that we have a high entropy in the set.
# A lot of requests targeting multiple dst_ips
# ip_dst count percent zscore
# 94.198.154.130 2799 50 4.0
# others 1842 33 2.0 <-- not an outlier
# 94.198.154.24 86 2 -0.0
data = top_n_dataframe(df.ip_dst, df, n_type)
data = data[(data.iloc[1, 0] == "others") & (data['zscore'] < 3)].size
if not data:
LOGGER.info("There are several destination IP in the dataset. High entropy. Effectiveness will be low.")
# find outlier
outlier = find_outlier(df['ip_dst'], df, n_type)
if not outlier or len(outlier) < 1:
LOGGER.debug("We cannot find the DDoS target IP address. Not enought info to find the outlier.")
LOGGER.debug("Trying to aggregate top IPs")
data = top_n_dataframe(df['ip_dst'], df, n_type)
# Outlier was not found (i.e the processed attack targeting multiples IP address)
# Check for Carpet Bombing attack (which target multiple IP addresses in the same subnet)
#
# Try to cluster the victim IPs. Usually, there are (IPs) part of the same network block.
# Select IPs responsible for more than 20% of the traffic and try to cluster them.
# If we succeed IPs are in the same range (network mask bigger than 21) we combine than and set as target.
ip_lst = sorted(data[(data['percent'] > CARPET_BOMBING_SUBNET)]['ip_dst'].tolist())
# filter ipv4|ipv6 only
ips = []
for ip in ip_lst:
try:
ipaddr.IPAddress(ip)
except ValueError:
continue
ips.append(ipaddr.IPAddress(ip))
# only one IP address
if len(ips) == 1:
return [str(ips[0])], df
lowest_ip = ips[0]
highest_ip = ips[-1]
# aggregation mask size
mask_length = ipaddr._get_prefix_length(int(lowest_ip), int(highest_ip), lowest_ip.max_prefixlen)
if mask_length > 21:
LOGGER.debug("Top IPs are correlated")
# rewrite to one IP address
for ip in ip_lst[1:]:
df.loc[df['ip_dst'] == ip, "ip_dst"] = ip_lst[0]
return ip_lst[0].split(), df
else:
# return the top 1
return [df['ip_dst'].value_counts().keys()[0]], df
else:
return outlier, df
# ------------------------------------------------------------------------------
def animated_loading(msg="loading ", count=-1):
"""
print loading animation
:param msg: prefix label
:param count: specific character
"""
chars = " ▁▂▃▄▅▆▇▇▇▆▅▄▃▂▁ "
if count == -1:
cursor.hide()
for char in chars:
# sys.stdout.write('\r'+msg+''+char)
sys.stdout.write('\r' + '[' + char + '] ' + msg)
time.sleep(.05)
sys.stdout.flush()
cursor.show()
else:
char = chars[int(count / 2) % len(chars)]
sys.stdout.write('\r' + '[' + char + '] ' + msg)
time.sleep(.05)
sys.stdout.flush()
# ------------------------------------------------------------------------------
def find_outlier(df_filtered, df, n_type, strict=0):
"""
Find outlier based in zscore
:param df_filtered: dataframe filtered by target_ip
:param df: full dataframe used for flows analysis
:param n_type: network file type (flows,pcap)
:param strict: turn the outlier process less flexible (ignore zscore, use frequency)
"""
# summarization dataframe
data = top_n_dataframe(df_filtered, df, n_type)
if data.empty:
return
outlier_field = data.columns[0]
# be more strict in the filter
if strict:
data_ = data[(data['percent'] > SIMILARITY_THRESHOLD) & (data['zscore'] > 2)]
# if the filter does not return anything, check if the df is
# composed by only one field
if data_.size == 0:
# get first line from the summarized dataframe
data = data.head(1)
# ignore zscore, use frequency threshold
data = data[
(data['percent'] > SIMILARITY_THRESHOLD) & (data['zscore'] < 0) & (data[outlier_field] != "others")]
if data.empty:
return
outliers = data.iloc[:, 0].tolist()
LOGGER.debug(
"Outliers for .:{}:. --> {} \n {}".format(outlier_field, outliers, data.head(5).to_string(index=False)))
LOGGER.debug('-' * 60)
return outliers
else:
# return the filtered dataframe saved in aux var
data = data_
# regular process - no strict
else:
data = data[(data['percent'] > SIMILARITY_THRESHOLD) | (data['zscore'] > 2)]
if len(data) == 0:
return None
outliers = data.iloc[:, 0].tolist()
if outliers == [NONE]:
LOGGER.debug("Outliers for .:{}:. --> None \n {}".format(data.columns[0], data.head(5).to_string(index=False)))
return
# remove outlier when dispersion is equal to `others` values, for example:
# srcport count percent zscore
# 443 2157 39 3.0
# others 2135 38 3.0
zscore_others = data.loc[data[outlier_field] == "others", 'zscore'].tolist()
if zscore_others:
# remove all fields with the same values than `others`
outliers = data[data.zscore != zscore_others[0]].iloc[:, 0].tolist()
LOGGER.debug('-' * 60)
if len(outliers) > 0:
LOGGER.debug(
"Outliers for .:{}:. --> {} \n {}".format(data.columns[0], outliers, data.head(5).to_string(index=False)))
return outliers
else:
LOGGER.debug("Outliers for .:{}:. --> None \n {}".format(data.columns[0], data.head(5).to_string(index=False)))
return None
# ------------------------------------------------------------------------------
# Infer the attack based on filtered dataframe
def infer_attack_protocol(df, n_type):
"""
Evaluate protocol distribution and return the used in the attack
:param df: dataframe
:param n_type: network file type (flows,pcap)
return: the list of top protocols and if the framentation protocol has found
TODO: decouple this from fragmentation
"""
target_ip = df['ip_dst'].iloc[0]
LOGGER.info("A total of {} IPs have attacked the victim {}".format(df.ip_src.nunique(), target_ip))
# find protocol outliers
outlier = find_outlier(df['highest_protocol'], df, n_type)
# there is no outlier
if not outlier:
# top protocol in the distribution
top1_protocol = df["highest_protocol"].value_counts().keys()[0]
# IPv4 and IPv6 as highest_protocol denotes a fragmentation attack
if bool(re.search('ipv[46]', top1_protocol.lower())): # IPv4/6 is top protocol
frag = True
data = top_n_dataframe(df['highest_protocol'], df, n_type)
# fragmentation attack (top protocol) is bigger than 50% of the provided traffic (empirical value)
if data['percent'].iloc[0] > 50:
LOGGER.debug("Frag Attack: a large fraction of traffic {}% is related to fragmentation attack".format(
data['percent'].iloc[0]))
# remove fragmentation protocol from the dataframe
data = top_n_dataframe(df['highest_protocol'], df[df['highest_protocol'] != top1_protocol], n_type)
# find outlier again by ignoring top (fragmentation) protocol (just removed)
outlier = find_outlier(data['highest_protocol'], data, n_type)
if outlier: # TODO: Verify correct behavior
return outlier, frag
else:
# still no outlier. It seems that we have an even protocol distribution
# this may be caused by multi-vector attack
# If remains protocols have a simmilar distribution (+-30%) use them as outliers - empirical
data = data[(data['percent'] > 30) & (data['highest_protocol'] != "others")]
protocol_list = data.sort_values(by="percent", ascending=False)['highest_protocol'].tolist()
return protocol_list, frag
else: # TODO: Verify correct behavior
data = data[(data['percent'] > 30) & (data['highest_protocol'] != "others")]
protocol_list = data.sort_values(by="percent", ascending=False)['highest_protocol'].tolist()
return protocol_list, frag
else:
# did not get outliers and it is not fragmentation attack
# multiprotocol attack with no fragmentation
frag = False
data = top_n_dataframe(df['highest_protocol'], df, n_type)
# If remains protocols have a similar distribution (+-30%) use them as outliers - empirical
data = data[(data['percent'] > 30) & (data['highest_protocol'] != "others")]
protocol_list = data.sort_values(by="percent", ascending=False)['highest_protocol'].tolist()
return protocol_list, frag
else:
# outlier found
LOGGER.debug("Protocol outlier found: {}".format(outlier))
# return the top1
LOGGER.debug("Top1 protocol could be classified as outlier")
top1_protocol = df["highest_protocol"].value_counts().reset_index().head(1)['index'].tolist()
frag = False
return top1_protocol, frag
# ------------------------------------------------------------------------------
def determine_file_type(input_file):
"""
Determine what sort of file the input is.
:param input_file: The path to the file, e.g. /home/user/example.pcap
:return: The file type of the input file as a string
:raises UnsupportedFileTypeError: If input file is not recognised or not supported
"""
file_ = shutil.which("file")
if not file_:
LOGGER.error("File software not found. It should be on the path.\n")
return NONE
file_info, error = subprocess.Popen([file_, input_file], stdout=subprocess.PIPE).communicate()
file_type = file_info.decode("utf-8").split(': ')[1].split()[0]
if file_type == "tcpdump":
return "pcap"
if file_type == "pcap":
return "pcap"
elif file_type == "pcap-ng" or file_type == "pcapng":
return "pcapng"
elif b"nfdump" in file_info or b"nfcapd" in file_info:
return "nfdump"
else:
LOGGER.critical("The file [{}] type [{}] is not supported.".format(input_file, file_type))
sys.exit(0)
# ------------------------------------------------------------------------------
def load_file(filename):
"""
Function to load attack capture file as pandas dataframe
:param filename: path to file to load
:return n_type: network file type (flows,pcap)
:return df: dataframe itself
"""
file_type = determine_file_type(filename)
if file_type == NONE:
return NONE, NONE
if re.search(r'nfdump', file_type):
load_function = flow_to_df
n_type = FLOW_TYPE
elif re.search(r'pcap', file_type):
load_function = pcap_to_df
n_type = PCAP_TYPE
else:
LOGGER.debug(f"invalid file format: {file_type}")
return NONE, NONE
# load dataframe using threading
ret = queue.Queue()
the_process = threading.Thread(name='process', target=load_function, args=(ret, filename))
the_process.start()
msg = "Loading network file: `{}' ".format(filename)
try:
count = 0
cursor.hide()
while the_process.is_alive():
if the_process:
animated_loading(msg, count=count) if not QUIET else 0
count += 1
cursor.show()
the_process.join()
except (KeyboardInterrupt, SystemExit):
cursor.show()
signal_handler()
df = ret.get()
# not a dataframe
if not isinstance(df, pd.DataFrame):
print("\n")
return NONE, NONE
sys.stdout.write('\r' + '[' + '\u2713' + '] ' + msg + '\n')
return n_type, df
# ------------------------------------------------------------------------------
def multi_attack_vector_heuristic(df_filtered, n_type):
"""
Generic heuristic to deal with low accuracy ratio fingerprint
:param df_filtered: dataframe filtered by target_ip
:param n_type: network file type (flows,pcap)
:return fingerprint: json file
"""
LOGGER.debug("ATTACK TYPE 3: NON MULTIFRAG FRAGMENTATION ATTACK")
fields = df_filtered.columns.tolist()
if "eth_type" in fields:
fields.remove("eth_type")
fingerprint = {}
for field in fields:
outlier = find_outlier(df_filtered[field], df_filtered, n_type, True)
if outlier and outlier != [NONE]:
fingerprint.update({field: outlier})
return fingerprint
# ------------------------------------------------------------------------------
def multifragmentation_heuristic(df_filtered, n_type):
"""
Determine if multiple protocols were used for fragmentation attack
:param df_filtered: dataframe filtered by target_ip
:param n_type: network file type (flows,pcap)
:return fingerprint: json file
"""
# flow does not have fragmentation info
if n_type == FLOW_TYPE:
return None
fingerprint = {}
df_ = df_filtered.fragmentation.value_counts(normalize=True).mul(100).reset_index()
# value = df_.loc[:, "fragmentation"].values[0]
df_['index'] = df_['index'].astype(bool)
# percentage of packets with fragmentation
try:
frag_percentage = \
df_[(df_['fragmentation'] > SIMILARITY_THRESHOLD) & df_['index'].values[0]].values[0][1]
except (ValueError, IndexError):
return None
# high chances to have multi protocol frag attack
if frag_percentage > SIMILARITY_THRESHOLD:
LOGGER.debug("ATTACK TYPE 2: MULTIPROTOCOL FRAGMENTATION ATTACK")
# find protocols responsible for that fragmentation
df_ = df_filtered.groupby(['highest_protocol', 'fragmentation'])['fragmentation'].count().to_frame(). \
rename(columns={'fragmentation': 'count'}).reset_index()
# may have more than one protocol responsible for that fragmentation percentage per group
# then, find the percentage of frag per protocol
df_['percent_frag'] = df_.groupby(['highest_protocol'])['count'].transform(lambda x: (x / x.sum()).mul(100))
df_['percent'] = (df_['count'] / df_['count'].sum()) * 100
df_['fragmentation'] = df_['fragmentation'].astype(bool)
# protocol with high percentage of frag
protocols = df_[df_.fragmentation & (df_.percent > SIMILARITY_THRESHOLD) &
(df_.percent_frag > SIMILARITY_THRESHOLD)]['highest_protocol'].tolist()
if not protocols:
return
# find respective src_port
LOGGER.info("Reprocessing attack based on protocols: {}".format(protocols))
df_filtered = df_filtered[df_filtered.highest_protocol.isin(protocols)]
srcports_frag = df_filtered[df_filtered.highest_protocol.isin(protocols)]['srcport'].unique().tolist()
outlier = find_outlier(df_filtered[df_filtered.highest_protocol.isin(protocols)]['srcport'],
df_filtered, n_type)
if NONE not in srcports_frag and outlier:
# add srcport to the fingerprint
fingerprint.update({"srcport": srcports_frag})
fields = df_filtered.columns.tolist()
if "eth_type" in fields:
fields.remove("eth_type")
for field in fields:
outlier = find_outlier(df_filtered[field], df_filtered, n_type)
if outlier:
if outlier != [NONE]:
fingerprint.update({field: outlier})
# revome fields the may overlap srcports outliers
if 'ip_proto' in fingerprint:
del fingerprint['ip_proto']
if 'ip_ttl' in fingerprint:
del fingerprint['ip_ttl']
return fingerprint
# ------------------------------------------------------------------------------
def generate_dot_file(df_fingerprint, df, filename):
"""
Build .dot file that is used to generate a png file showing the
fingerprint match visualization
:param df_fingerprint: dataframe filtered based on matched fingerprint
:param df: dataframe itself
:param filename: filename to save the dotfile (with .dot extension)
"""
# sum up dataframe to plot
df_fingerprint = df_fingerprint[['ip_src', 'ip_dst']].drop_duplicates(keep="first")
df_fingerprint['match'] = 1
df_remain = df[['ip_src', 'ip_dst']].drop_duplicates(keep="first")
df_remain['match'] = 0
df_plot = pd.concat([df_fingerprint, df_remain], ignore_index=True)
# anonymize plot data
df_plot.reset_index(inplace=True)
df_plot.drop('ip_src', axis=1, inplace=True)
df_plot = df_plot.rename(columns={"index": "ip_src"})
df_plot['ip_dst'] = "victim"
LOGGER.debug("Distribution of filtered traffic: \n{}".format(df_plot.match.value_counts(normalize=True).mul(100)))
filename, file_extension = os.path.splitext(filename)
with open(filename + ".dot", 'w+', encoding='utf-8') as f:
f.write("graph {\n")
for index, row in df_plot.iterrows():
if row['match'] == 0:
f.write("\t {} -- {}[color=green,penwidth=1.0];\n".format(row["ip_src"], row["ip_dst"]))
else:
f.write("\t {} -- {}[color=red,penwidth=2.0];\n".format(row["ip_src"], row["ip_dst"]))
f.write("}\n")
print("Use the following command to generate an image:")
print("\t sfdp -x -Goverlap=scale -Tpng {}.dot > {}.png".format(filename, filename))
# print ("\t convert {}.png -gravity North -background YellowGreen -splice 0x18 -annotate +0+2 'Dissector'
# {}.gif ".format(filename,filename))
# ------------------------------------------------------------------------------