forked from stratosphereips/StratosphereLinuxIPS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
profilerProcess.py
2086 lines (1996 loc) · 99.5 KB
/
profilerProcess.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
# Stratosphere Linux IPS. A machine-learning Intrusion Detection System
# Copyright (C) 2021 Sebastian Garcia
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import multiprocessing
import json
from datetime import datetime
from datetime import timedelta
import sys
import configparser
from slips.core.database import __database__
import time
import ipaddress
import traceback
import os
import binascii
import base64
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print(f'\t\033[1;32;40mFunction {method.__name__}() took {(te - ts) * 1000:2.2f}ms\033[00m')
return result
return timed
# Profiler Process
class ProfilerProcess(multiprocessing.Process):
""" A class to create the profiles for IPs and the rest of data """
def __init__(self, inputqueue, outputqueue, config, width):
self.name = 'Profiler'
multiprocessing.Process.__init__(self)
self.inputqueue = inputqueue
self.outputqueue = outputqueue
self.config = config
self.width = width
self.columns_defined = False
self.timeformat = None
self.input_type = False
# Read the configuration
self.read_configuration()
# Start the DB
__database__.start(self.config)
# Set the database output queue
__database__.setOutputQueue(self.outputqueue)
# 1st. Get the data from the interpreted columns
self.id_separator = __database__.getFieldSeparator()
def print(self, text, verbose=1, debug=0):
"""
Function to use to print text using the outputqueue of slips.
Slips then decides how, when and where to print this text by taking all the prcocesses into account
Input
verbose: is the minimum verbosity level required for this text to be printed
debug: is the minimum debugging level required for this text to be printed
text: text to print. Can include format like 'Test {}'.format('here')
If not specified, the minimum verbosity level required is 1, and the minimum debugging level is 0
"""
vd_text = str(int(verbose) * 10 + int(debug))
self.outputqueue.put(vd_text + '|' + self.name + '|[' + self.name + '] ' + str(text))
def read_configuration(self):
""" Read the configuration file for what we need """
# Get the home net if we have one from the config
try:
self.home_net = ipaddress.ip_network(self.config.get('parameters', 'home_network'))
except (configparser.NoOptionError, configparser.NoSectionError, NameError):
# There is a conf, but there is no option, or no section or no
# configuration file specified
self.home_net = False
# Get the time window width, if it was not specified as a parameter
if not self.width:
try:
data = self.config.get('parameters', 'time_window_width')
self.width = float(data)
except ValueError:
# Its not a float
if 'only_one_tw' in data:
# Only one tw. Width is 10 9s, wich is ~11,500 days, ~311 years
self.width = 9999999999
except configparser.NoOptionError:
# By default we use 3600 seconds, 1hs
self.width = 3600
except (configparser.NoOptionError, configparser.NoSectionError, NameError):
# There is a conf, but there is no option, or no section or no
# configuration file specified
self.width = 3600
# Limit any width to be > 0. By default we use 300 seconds, 5minutes
elif self.width < 0:
self.width = 3600
else:
self.width = 3600
# Report the time window width
if self.width == 9999999999:
self.print(f'Time Windows Width used: {self.width} seconds. Only 1 time windows. Dates in the names of files are 100 years in the past.', 4, 0)
else:
self.print(f'Time Windows Width used: {self.width} seconds.', 4, 0)
# Get the format of the time in the flows
try:
self.timeformat = self.config.get('timestamp', 'format')
except (configparser.NoOptionError, configparser.NoSectionError, NameError):
# There is a conf, but there is no option, or no section or no configuration file specified
# This has to be None, beacause we try to detect the time format below, if it is None.
self.timeformat = None
##
# Get the direction of analysis
try:
self.analysis_direction = self.config.get('parameters', 'analysis_direction')
except (configparser.NoOptionError, configparser.NoSectionError, NameError):
# There is a conf, but there is no option, or no section or no configuration file specified
# By default
self.analysis_direction = 'all'
# Get the default label for all this flow. Used during training usually
try:
self.label = self.config.get('parameters', 'label')
except (configparser.NoOptionError, configparser.NoSectionError, NameError):
# There is a conf, but there is no option, or no section or no configuration file specified
# By default
self.label = 'unknown'
def define_type(self, line):
"""
Try to define very fast the type of input
Heuristic detection: dict (zeek from pcap of int), json (suricata), or csv (argus), or TAB separated (conn.log only from zeek)?
Bro actually gives us json, but it was already coverted into a dict
in inputProcess
Outputs can be: zeek, suricata, argus, zeek-tabs
"""
try:
# All lines come as a dict, specifying the name of file and data.
# Take the data
try:
# Did data came with the json format?
data = line['data']
# For now we dont use the file type, but is handy for the future
file_type = line['type']
# Yes
except KeyError:
# No
data = line
self.print('\tData did not arrived in json format from the input', 0, 1)
self.print('\tProblem in define_type()', 0, 1)
return False
# In the case of Zeek from an interface or pcap,
# the structure is a JSON
# So try to convert into a dict
if type(data) == dict:
try:
_ = data['data']
self.separator = ' '
self.input_type = 'zeek-tabs'
except KeyError:
self.input_type = 'zeek'
else:
try:
data = json.loads(data)
if data['event_type'] == 'flow':
self.input_type = 'suricata'
except ValueError:
nr_commas = len(data.split(','))
nr_tabs = len(data.split(' '))
if nr_commas > nr_tabs:
# Commas is the separator
self.separator = ','
if nr_commas > 40:
self.input_type = 'nfdump'
else:
self.input_type = 'argus'
elif nr_tabs > nr_commas:
# Tabs is the separator
# Probably a conn.log file alone from zeek
self.separator = ' '
self.input_type = 'zeek-tabs'
except Exception as inst:
self.print('\tProblem in define_type()', 0, 1)
self.print(str(type(inst)), 0, 1)
self.print(str(inst), 0, 1)
sys.exit(1)
def define_columns(self, new_line):
""" Define the columns for Argus and Zeek-tabs from the line received """
# These are the indexes for later fast processing
line = new_line['data']
self.column_idx = {}
self.column_idx['starttime'] = False
self.column_idx['endtime'] = False
self.column_idx['dur'] = False
self.column_idx['proto'] = False
self.column_idx['appproto'] = False
self.column_idx['saddr'] = False
self.column_idx['sport'] = False
self.column_idx['dir'] = False
self.column_idx['daddr'] = False
self.column_idx['dport'] = False
self.column_idx['state'] = False
self.column_idx['pkts'] = False
self.column_idx['spkts'] = False
self.column_idx['dpkts'] = False
self.column_idx['bytes'] = False
self.column_idx['sbytes'] = False
self.column_idx['dbytes'] = False
try:
nline = line.strip().split(self.separator)
for field in nline:
if 'time' in field.lower():
self.column_idx['starttime'] = nline.index(field)
elif 'dur' in field.lower():
self.column_idx['dur'] = nline.index(field)
elif 'proto' in field.lower():
self.column_idx['proto'] = nline.index(field)
elif 'srca' in field.lower():
self.column_idx['saddr'] = nline.index(field)
elif 'sport' in field.lower():
self.column_idx['sport'] = nline.index(field)
elif 'dir' in field.lower():
self.column_idx['dir'] = nline.index(field)
elif 'dsta' in field.lower():
self.column_idx['daddr'] = nline.index(field)
elif 'dport' in field.lower():
self.column_idx['dport'] = nline.index(field)
elif 'state' in field.lower():
self.column_idx['state'] = nline.index(field)
elif 'totpkts' in field.lower():
self.column_idx['pkts'] = nline.index(field)
elif 'totbytes' in field.lower():
self.column_idx['bytes'] = nline.index(field)
elif 'srcbytes' in field.lower():
self.column_idx['sbytes'] = nline.index(field)
# Some of the fields were not found probably,
# so just delete them from the index if their value is False.
# If not we will believe that we have data on them
# We need a temp dict because we can not change the size of dict while analyzing it
temp_dict = {}
for i in self.column_idx:
if type(self.column_idx[i]) == bool and self.column_idx[i] == False:
continue
temp_dict[i] = self.column_idx[i]
self.column_idx = temp_dict
except Exception as inst:
self.print('\tProblem in define_columns()', 0, 1)
self.print(str(type(inst)), 0, 1)
self.print(str(inst), 0, 1)
sys.exit(1)
def define_time_format(self, time: str) -> str:
time_format: str = None
try:
# Try unix timestamp in seconds.
datetime.fromtimestamp(float(time))
time_format = 'unixtimestamp'
except ValueError:
try:
# Try the default time format for suricata.
datetime.strptime(time, '%Y-%m-%dT%H:%M:%S.%f%z')
time_format = '%Y-%m-%dT%H:%M:%S.%f%z'
except ValueError:
# Let's try the classic time format "'%Y-%m-%d %H:%M:%S.%f'"
try:
datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f')
time_format = '%Y-%m-%d %H:%M:%S.%f'
except ValueError:
try:
datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
time_format = '%Y-%m-%d %H:%M:%S'
except ValueError:
try:
datetime.strptime(time, '%Y/%m/%d %H:%M:%S.%f')
time_format = '%Y/%m/%d %H:%M:%S.%f'
except ValueError:
# We did not find the right time format.
self.outputqueue.put("01|profiler|[Profile] We did not find right time format. Please set the time format in the configuration file.")
return time_format
def get_time(self, time: str) -> datetime:
"""
Take time in string and return datetime object.
The format of time can be completely different. It can be seconds, or dates with specific formats.
If user does not define the time format in configuration file, we have to try most frequent cases of time formats.
"""
if not self.timeformat:
# The time format was not defined from configuration file neither from last flows.
self.timeformat = self.define_time_format(time)
defined_datetime: datetime = None
if self.timeformat:
if self.timeformat == 'unixtimestamp':
# The format of time is in seconds.
defined_datetime = datetime.fromtimestamp(float(time))
else:
try:
# The format of time is a complete date.
defined_datetime = datetime.strptime(time, self.timeformat)
except ValueError:
defined_datetime = None
else:
# We do not know the time format so we can not read it.
self.outputqueue.put(
"01|profiler|[Profile] We did not find right time format. Please set the time format in the configuration file.")
# if defined_datetime is None and self.timeformat:
# There is suricata issue with invalid timestamp for examaple: "1900-01-00T00:00:08.511802+0000"
# pass
return defined_datetime
def process_zeek_tabs_input(self, new_line: str) -> None:
"""
Process the tab line from zeek.
"""
line = new_line['data']
line = line.rstrip()
line = line.split('\t')
# Generic fields in Zeek
self.column_values: dict = {}
# We need to set it to empty at the beginning so any new flow has
# the key 'type'
self.column_values['type'] = ''
try:
self.column_values['starttime'] = self.get_time(line[0])
except IndexError:
self.column_values['starttime'] = ''
try:
self.column_values['uid'] = line[1]
except IndexError:
self.column_values['uid'] = False
try:
self.column_values['saddr'] = line[2]
except IndexError:
self.column_values['saddr'] = ''
try:
self.column_values['daddr'] = line[4]
except IndexError:
self.column_values['daddr'] = ''
if 'conn' in new_line['type']:
self.column_values['type'] = 'conn'
try:
self.column_values['dur'] = float(line[8])
except (IndexError, ValueError):
self.column_values['dur'] = 0
self.column_values['endtime'] = self.column_values['starttime'] + timedelta(
seconds=self.column_values['dur'])
self.column_values['proto'] = line[6]
try:
self.column_values['appproto'] = line[7]
except IndexError:
# no service recognized
self.column_values['appproto'] = ''
try:
self.column_values['sport'] = line[3]
except IndexError:
self.column_values['sport'] = ''
self.column_values['dir'] = '->'
try:
self.column_values['dport'] = line[5]
except IndexError:
self.column_values['dport'] = ''
try:
self.column_values['state'] = line[11]
except IndexError:
self.column_values['state'] = ''
try:
self.column_values['spkts'] = float(line[16])
except (IndexError, ValueError):
self.column_values['spkts'] = 0
try:
self.column_values['dpkts'] = float(line[18])
except (IndexError, ValueError):
self.column_values['dpkts'] = 0
self.column_values['pkts'] = self.column_values['spkts'] + self.column_values['dpkts']
try:
self.column_values['sbytes'] = float(line[9])
except (IndexError, ValueError):
self.column_values['sbytes'] = 0
try:
self.column_values['dbytes'] = float(line[10])
except (IndexError, ValueError):
self.column_values['dbytes'] = 0
self.column_values['bytes'] = self.column_values['sbytes'] + self.column_values['dbytes']
try:
self.column_values['state_hist'] = line[15]
except IndexError:
self.column_values['state_hist'] = self.column_values['state']
# We do not know the indexes of MACs.
self.column_values['smac'] = ''
self.column_values['dmac'] = ''
elif 'dns' in new_line['type']:
self.column_values['type'] = 'dns'
try:
self.column_values['query'] = line[9]
except IndexError:
self.column_values['query'] = ''
try:
self.column_values['qclass_name'] = line[11]
except IndexError:
self.column_values['qclass_name'] = ''
try:
self.column_values['qtype_name'] = line[13]
except IndexError:
self.column_values['qtype_name'] = ''
try:
self.column_values['rcode_name'] = line[15]
except IndexError:
self.column_values['rcode_name'] = ''
try:
self.column_values['answers'] = line[21]
except IndexError:
self.column_values['answers'] = ''
try:
self.column_values['TTLs'] = line[22]
except IndexError:
self.column_values['TTLs'] = ''
elif 'http' in new_line['type']:
self.column_values['type'] = 'http'
try:
self.column_values['method'] = line[7]
except IndexError:
self.column_values['method'] = ''
try:
self.column_values['host'] = line[8]
except IndexError:
self.column_values['host'] = ''
try:
self.column_values['uri'] = line[9]
except IndexError:
self.column_values['uri'] = ''
try:
self.column_values['httpversion'] = line[11]
except IndexError:
self.column_values['httpversion'] = ''
try:
self.column_values['user_agent'] = line[12]
except IndexError:
self.column_values['user_agent'] = ''
try:
self.column_values['request_body_len'] = line[13]
except IndexError:
self.column_values['request_body_len'] = 0
try:
self.column_values['response_body_len'] = line[14]
except IndexError:
self.column_values['response_body_len'] = 0
try:
self.column_values['status_code'] = line[15]
except IndexError:
self.column_values['status_code'] = ''
try:
self.column_values['status_msg'] = line[16]
except IndexError:
self.column_values['status_msg'] = ''
try:
self.column_values['resp_mime_types'] = line[28]
except IndexError:
self.column_values['resp_mime_types'] = ''
try:
self.column_values['resp_fuids'] = line[26]
except IndexError:
self.column_values['resp_fuids'] = ''
elif 'ssl' in new_line['type']:
self.column_values['type'] = 'ssl'
try:
self.column_values['sslversion'] = line[6]
except IndexError:
self.column_values['sslversion'] = ''
try:
self.column_values['cipher'] = line[7]
except IndexError:
self.column_values['cipher'] = ''
try:
self.column_values['resumed'] = line[10]
except IndexError:
self.column_values['resumed'] = ''
try:
self.column_values['established'] = line[13]
except IndexError:
self.column_values['established'] = ''
try:
self.column_values['cert_chain_fuids'] = line[14]
except IndexError:
self.column_values['cert_chain_fuids'] = ''
try:
self.column_values['client_cert_chain_fuids'] = line[15]
except IndexError:
self.column_values['client_cert_chain_fuids'] = ''
try:
self.column_values['subject'] = line[16]
except IndexError:
self.column_values['subject'] = ''
try:
self.column_values['issuer'] = line[17]
except IndexError:
self.column_values['issuer'] = ''
self.column_values['validation_status'] = ''
try:
self.column_values['curve'] = line[8]
except IndexError:
self.column_values['curve'] = ''
try:
self.column_values['server_name'] = line[9]
except IndexError:
self.column_values['server_name'] = ''
elif 'ssh' in new_line['type']:
self.column_values['type'] = 'ssh'
try:
self.column_values['version'] = line[6]
except IndexError:
self.column_values['version'] = ''
# Zeek can put in column 7 the auth success if it has one
# or the auth attempts only. However if the auth
# success is there, the auth attempts are too.
if 'success' in line[7]:
try:
self.column_values['auth_success'] = line[7]
except IndexError:
self.column_values['auth_success'] = ''
try:
self.column_values['auth_attempts'] = line[8]
except IndexError:
self.column_values['auth_attempts'] = ''
try:
self.column_values['client'] = line[10]
except IndexError:
self.column_values['client'] = ''
try:
self.column_values['server'] = line[11]
except IndexError:
self.column_values['server'] = ''
try:
self.column_values['cipher_alg'] = line[12]
except IndexError:
self.column_values['cipher_alg'] = ''
try:
self.column_values['mac_alg'] = line[13]
except IndexError:
self.column_values['mac_alg'] = ''
try:
self.column_values['compression_alg'] = line[14]
except IndexError:
self.column_values['compression_alg'] = ''
try:
self.column_values['kex_alg'] = line[15]
except IndexError:
self.column_values['kex_alg'] = ''
try:
self.column_values['host_key_alg'] = line[16]
except IndexError:
self.column_values['host_key_alg'] = ''
try:
self.column_values['host_key'] = line[17]
except IndexError:
self.column_values['host_key'] = ''
elif 'success' not in line[7]:
self.column_values['auth_success'] = ''
try:
self.column_values['auth_attempts'] = line[7]
except IndexError:
self.column_values['auth_attempts'] = ''
try:
self.column_values['client'] = line[9]
except IndexError:
self.column_values['client'] = ''
try:
self.column_values['server'] = line[10]
except IndexError:
self.column_values['server'] = ''
try:
self.column_values['cipher_alg'] = line[11]
except IndexError:
self.column_values['cipher_alg'] = ''
try:
self.column_values['mac_alg'] = line[12]
except IndexError:
self.column_values['mac_alg'] = ''
try:
self.column_values['compression_alg'] = line[13]
except IndexError:
self.column_values['compression_alg'] = ''
try:
self.column_values['kex_alg'] = line[14]
except IndexError:
self.column_values['kex_alg'] = ''
try:
self.column_values['host_key_alg'] = line[15]
except IndexError:
self.column_values['host_key_alg'] = ''
try:
self.column_values['host_key'] = line[16]
except IndexError:
self.column_values['host_key'] = ''
elif 'irc' in new_line['type']:
self.column_values['type'] = 'irc'
elif 'long' in new_line['type']:
self.column_values['type'] = 'long'
elif 'dhcp' in new_line['type']:
self.column_values['type'] = 'dhcp'
elif 'dce_rpc' in new_line['type']:
self.column_values['type'] = 'dce_rpc'
elif 'dnp3' in new_line['type']:
self.column_values['type'] = 'dnp3'
elif 'ftp' in new_line['type']:
self.column_values['type'] = 'ftp'
elif 'kerberos' in new_line['type']:
self.column_values['type'] = 'kerberos'
elif 'mysql' in new_line['type']:
self.column_values['type'] = 'mysql'
elif 'modbus' in new_line['type']:
self.column_values['type'] = 'modbus'
elif 'ntlm' in new_line['type']:
self.column_values['type'] = 'ntlm'
elif 'rdp' in new_line['type']:
self.column_values['type'] = 'rdp'
elif 'sip' in new_line['type']:
self.column_values['type'] = 'sip'
elif 'smb_cmd' in new_line['type']:
self.column_values['type'] = 'smb_cmd'
elif 'smb_files' in new_line['type']:
self.column_values['type'] = 'smb_files'
elif 'smb_mapping' in new_line['type']:
self.column_values['type'] = 'smb_mapping'
elif 'smtp' in new_line['type']:
self.column_values['type'] = 'smtp'
elif 'socks' in new_line['type']:
self.column_values['type'] = 'socks'
elif 'syslog' in new_line['type']:
self.column_values['type'] = 'syslog'
elif 'tunnel' in new_line['type']:
self.column_values['type'] = 'tunnel'
def process_zeek_input(self, new_line):
"""
Process the line and extract columns for zeek
Its a dictionary
"""
line = new_line['data']
file_type = new_line['type']
# Generic fields in Zeek
self.column_values = {}
# We need to set it to empty at the beggining so any new flow has the key 'type'
self.column_values['type'] = ''
try:
self.column_values['starttime'] = self.get_time(line['ts'])
except KeyError:
self.column_values['starttime'] = ''
try:
self.column_values['uid'] = line['uid']
except KeyError:
self.column_values['uid'] = False
try:
self.column_values['saddr'] = line['id.orig_h']
except KeyError:
self.column_values['saddr'] = ''
try:
self.column_values['daddr'] = line['id.resp_h']
except KeyError:
self.column_values['daddr'] = ''
if 'conn' in file_type:
# {'ts': 1538080852.403669, 'uid': 'Cewh6D2USNVtfcLxZe', 'id.orig_h': '192.168.2.12', 'id.orig_p': 56343, 'id.resp_h': '192.168.2.1', 'id.resp_p': 53, 'proto': 'udp', 'service': 'dns', 'duration': 0.008364, 'orig_bytes': 30, 'resp_bytes': 94, 'conn_state': 'SF', 'missed_bytes': 0, 'history': 'Dd', 'orig_pkts': 1, 'orig_ip_bytes': 58, 'resp_pkts': 1, 'resp_ip_bytes': 122, 'orig_l2_addr': 'b8:27:eb:6a:47:b8', 'resp_l2_addr': 'a6:d1:8c:1f:ce:64', 'type': './zeek_files/conn'}
self.column_values['type'] = 'conn'
try:
self.column_values['dur'] = float(line['duration'])
except KeyError:
self.column_values['dur'] = 0
self.column_values['endtime'] = self.column_values['starttime'] + timedelta(seconds=self.column_values['dur'])
self.column_values['proto'] = line['proto']
try:
self.column_values['appproto'] = line['service']
except KeyError:
# no service recognized
self.column_values['appproto'] = ''
try:
self.column_values['sport'] = line['id.orig_p']
except KeyError:
self.column_values['sport'] = ''
self.column_values['dir'] = '->'
try:
self.column_values['dport'] = line['id.resp_p']
except KeyError:
self.column_values['dport'] = ''
try:
self.column_values['state'] = line['conn_state']
except KeyError:
self.column_values['state'] = ''
try:
self.column_values['spkts'] = line['orig_pkts']
except KeyError:
self.column_values['spkts'] = 0
try:
self.column_values['dpkts'] = line['resp_pkts']
except KeyError:
self.column_values['dpkts'] = 0
self.column_values['pkts'] = self.column_values['spkts'] + self.column_values['dpkts']
try:
self.column_values['sbytes'] = line['orig_bytes']
except KeyError:
self.column_values['sbytes'] = 0
try:
self.column_values['dbytes'] = line['resp_bytes']
except KeyError:
self.column_values['dbytes'] = 0
self.column_values['bytes'] = self.column_values['sbytes'] + self.column_values['dbytes']
try:
self.column_values['state_hist'] = line['history']
except KeyError:
self.column_values['state_hist'] = self.column_values['state']
try:
self.column_values['smac'] = line['orig_l2_addr']
except KeyError:
self.column_values['smac'] = ''
try:
self.column_values['dmac'] = line['resp_l2_addr']
except KeyError:
self.column_values['dmac'] = ''
elif 'dns' in file_type:
#{"ts":1538080852.403669,"uid":"CtahLT38vq7vKJVBC3","id.orig_h":"192.168.2.12","id.orig_p":56343,"id.resp_h":"192.168.2.1","id.resp_p":53,"proto":"udp","trans_id":2,"rtt":0.008364,"query":"pool.ntp.org","qclass":1,"qclass_name":"C_INTERNET","qtype":1,"qtype_name":"A","rcode":0,"rcode_name":"NOERROR","AA":false,"TC":false,"RD":true,"RA":true,"Z":0,"answers":["185.117.82.70","212.237.100.250","213.251.52.107","183.177.72.201"],"TTLs":[42.0,42.0,42.0,42.0],"rejected":false}
self.column_values['type'] = 'dns'
try:
self.column_values['query'] = line['query']
except KeyError:
self.column_values['query'] = ''
try:
self.column_values['qclass_name'] = line['qclass_name']
except KeyError:
self.column_values['qclass_name'] = ''
try:
self.column_values['qtype_name'] = line['qtype_name']
except KeyError:
self.column_values['qtype_name'] = ''
try:
self.column_values['rcode_name'] = line['rcode_name']
except KeyError:
self.column_values['rcode_name'] = ''
try:
self.column_values['answers'] = line['answers']
except KeyError:
self.column_values['answers'] = ''
try:
self.column_values['TTLs'] = line['TTLs']
except KeyError:
self.column_values['TTLs'] = ''
elif 'http' in file_type:
# {"ts":158.957403,"uid":"CnNLbE2dyfy5KyqEhh","id.orig_h":"10.0.2.105","id.orig_p":49158,"id.resp_h":"64.182.208.181","id.resp_p":80,"trans_depth":1,"method":"GET","host":"icanhazip.com","uri":"/","version":"1.1","user_agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.38 (KHTML, like Gecko) Chrome/45.0.2456.99 Safari/537.38","request_body_len":0,"response_body_len":13,"status_code":200,"status_msg":"OK","tags":[],"resp_fuids":["FwraVxIOACcjkaGi3"],"resp_mime_types":["text/plain"]}
self.column_values['type'] = 'http'
try:
self.column_values['method'] = line['method']
except KeyError:
self.column_values['method'] = ''
try:
self.column_values['host'] = line['host']
except KeyError:
self.column_values['host'] = ''
try:
self.column_values['uri'] = line['uri']
except KeyError:
self.column_values['uri'] = ''
try:
self.column_values['httpversion'] = line['version']
except KeyError:
self.column_values['httpversion'] = ''
try:
self.column_values['user_agent'] = line['user_agent']
except KeyError:
self.column_values['user_agent'] = ''
try:
self.column_values['request_body_len'] = line['request_body_len']
except KeyError:
self.column_values['request_body_len'] = 0
try:
self.column_values['response_body_len'] = line['response_body_len']
except KeyError:
self.column_values['response_body_len'] = 0
try:
self.column_values['status_code'] = line['status_code']
except KeyError:
self.column_values['status_code'] = ''
try:
self.column_values['status_msg'] = line['status_msg']
except KeyError:
self.column_values['status_msg'] = ''
try:
self.column_values['resp_mime_types'] = line['resp_mime_types']
except KeyError:
self.column_values['resp_mime_types'] = ''
try:
self.column_values['resp_fuids'] = line['resp_fuids']
except KeyError:
self.column_values['resp_fuids'] = ''
elif 'ssl' in file_type:
# {"ts":12087.045499,"uid":"CdoFDp4iW79I5ZmsT7","id.orig_h":"10.0.2.105","id.orig_p":49704,"id.resp_h":"195.211.240.166","id.resp_p":443,"version":"SSLv3","cipher":"TLS_RSA_WITH_RC4_128_SHA","resumed":false,"established":true,"cert_chain_fuids":["FhGp1L3yZXuURiPqq7"],"client_cert_chain_fuids":[],"subject":"OU=DAHUATECH,O=DAHUA,L=HANGZHOU,ST=ZHEJIANG,C=CN,CN=192.168.1.108","issuer":"O=DahuaTech,L=HangZhou,ST=ZheJiang,C=CN,CN=Product Root CA","validation_status":"unable to get local issuer certificate"}
# {"ts":1382354909.915615,"uid":"C7W6ZA4vI8FxJ9J0bh","id.orig_h":"147.32.83.53","id.orig_p":36567,"id.resp_h":"195.113.214.241","id.resp_p":443,"version":"TLSv12","cipher":"TLS_ECDHE_ECDSA_WITH_RC4_128_SHA","curve":"secp256r1","server_name":"id.google.com.ar","resumed":false,"established":true,"cert_chain_fuids":["FnomJz1vghKIOHtytf","FSvQff1KsaDkRtKXo4","Fif2PF48bytqq6xMDb"],"client_cert_chain_fuids":[],"subject":"CN=*.google.com,O=Google Inc,L=Mountain View,ST=California,C=US","issuer":"CN=Google Internet Authority G2,O=Google Inc,C=US","validation_status":"ok"}
self.column_values['type'] = 'ssl'
try:
self.column_values['sslversion'] = line['version']
except KeyError:
self.column_values['sslversion'] = ''
try:
self.column_values['cipher'] = line['cipher']
except KeyError:
self.column_values['cipher'] = ''
try:
self.column_values['resumed'] = line['resumed']
except KeyError:
self.column_values['resumed'] = ''
try:
self.column_values['established'] = line['established']
except KeyError:
self.column_values['established'] = ''
try:
self.column_values['cert_chain_fuids'] = line['cert_chain_fuids']
except KeyError:
self.column_values['cert_chain_fuids'] = ''
try:
self.column_values['client_cert_chain_fuids'] = line['client_cert_chain_fuids']
except KeyError:
self.column_values['client_cert_chain_fuids'] = ''
try:
self.column_values['subject'] = line['subject']
except KeyError:
self.column_values['subject'] = ''
try:
self.column_values['issuer'] = line['issuer']
except KeyError:
self.column_values['issuer'] = ''
try:
self.column_values['validation_status'] = line['validation_status']
except KeyError:
self.column_values['validation_status'] = ''
try:
self.column_values['curve'] = line['curve']
except KeyError:
self.column_values['curve'] = ''
try:
self.column_values['server_name'] = line['server_name']
except KeyError:
self.column_values['server_name'] = ''
elif 'ssh' in file_type:
self.column_values['type'] = 'ssh'
try:
self.column_values['version'] = line['version']
except KeyError:
self.column_values['version'] = ''
try:
self.column_values['auth_success'] = line['auth_success']
except KeyError:
self.column_values['auth_success'] = ''
try:
self.column_values['auth_attempts'] = line['auth_attempts']
except KeyError:
self.column_values['auth_attempts'] = ''
try:
self.column_values['client'] = line['client']
except KeyError:
self.column_values['client'] = ''
try:
self.column_values['server'] = line['server']
except KeyError:
self.column_values['server'] = ''
try:
self.column_values['cipher_alg'] = line['cipher_alg']
except KeyError:
self.column_values['cipher_alg'] = ''
try:
self.column_values['mac_alg'] = line['mac_alg']
except KeyError:
self.column_values['mac_alg'] = ''
try:
self.column_values['compression_alg'] = line['compression_alg']
except KeyError:
self.column_values['compression_alg'] = ''
try:
self.column_values['kex_alg'] = line['kex_alg']
except KeyError:
self.column_values['kex_alg'] = ''
try:
self.column_values['host_key_alg'] = line['host_key_alg']
except KeyError:
self.column_values['host_key_alg'] = ''
try:
self.column_values['host_key'] = line['host_key']
except KeyError:
self.column_values['host_key'] = ''
elif 'irc' in file_type:
self.column_values['type'] = 'irc'
elif 'long' in file_type:
self.column_values['type'] = 'long'
elif 'dhcp' in file_type:
self.column_values['type'] = 'dhcp'
elif 'dce_rpc' in file_type:
self.column_values['type'] = 'dce_rpc'
elif 'dnp3' in file_type:
self.column_values['type'] = 'dnp3'
elif 'ftp' in file_type:
self.column_values['type'] = 'ftp'
elif 'kerberos' in file_type:
self.column_values['type'] = 'kerberos'
elif 'mysql' in file_type:
self.column_values['type'] = 'mysql'
elif 'modbus' in file_type:
self.column_values['type'] = 'modbus'
elif 'ntlm' in file_type:
self.column_values['type'] = 'ntlm'
elif 'rdp' in file_type:
self.column_values['type'] = 'rdp'
elif 'sip' in file_type:
self.column_values['type'] = 'sip'
elif 'smb_cmd' in file_type:
self.column_values['type'] = 'smb_cmd'
elif 'smb_files' in file_type:
self.column_values['type'] = 'smb_files'
elif 'smb_mapping' in file_type:
self.column_values['type'] = 'smb_mapping'
elif 'smtp' in file_type:
self.column_values['type'] = 'smtp'
elif 'socks' in file_type:
self.column_values['type'] = 'socks'
elif 'syslog' in file_type:
self.column_values['type'] = 'syslog'
elif 'tunnel' in file_type:
self.column_values['type'] = 'tunnel'
def process_argus_input(self, new_line):
"""
Process the line and extract columns for argus
"""
line = new_line['data']
self.column_values = {}
self.column_values['starttime'] = False
self.column_values['endtime'] = False
self.column_values['dur'] = False
self.column_values['proto'] = False
self.column_values['appproto'] = False
self.column_values['saddr'] = False
self.column_values['sport'] = False
self.column_values['dir'] = False
self.column_values['daddr'] = False
self.column_values['dport'] = False
self.column_values['state'] = False
self.column_values['pkts'] = False
self.column_values['spkts'] = False
self.column_values['dpkts'] = False
self.column_values['bytes'] = False
self.column_values['sbytes'] = False
self.column_values['dbytes'] = False
self.column_values['type'] = 'argus'
# Read the lines fast
nline = line.strip().split(self.separator)
try:
self.column_values['starttime'] = self.get_time(nline[self.column_idx['starttime']])
except KeyError:
pass
try:
self.column_values['endtime'] = nline[self.column_idx['endtime']]
except KeyError:
pass
try:
self.column_values['dur'] = nline[self.column_idx['dur']]
except KeyError:
pass
try:
self.column_values['proto'] = nline[self.column_idx['proto']]
except KeyError:
pass
try:
self.column_values['appproto'] = nline[self.column_idx['appproto']]
except KeyError:
pass
try:
self.column_values['saddr'] = nline[self.column_idx['saddr']]
except KeyError: