-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVirtualBotmaster.py
executable file
·1617 lines (1324 loc) · 61.8 KB
/
VirtualBotmaster.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 python
# Copyright (C) 2009 Sebastian Garcia, Veronica Valeros
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# Author:
#
# Changelog
# Description
#
# standard imports
import getopt
import sys
import os
import time
from datetime import datetime
from datetime import timedelta
import multiprocessing
from multiprocessing import Queue
from multiprocessing import JoinableQueue
from collections import deque
import random
try:
import pykov
except ImportError:
print 'You need tht pykov libraries and the sparse libraries. Download from : https://riccardoscalco.github.io/Pykov/, and https://sourceforge.net/projects/pysparse/files/latest/download'
print 'In debian-based systems:'
print '\tpip install pykov'
print '\tapt-get install sparse'
print 'If you don\'t have pip: apt-get install python-pip'
sys.exit(-1)
import operator
import cPickle
import ConfigParser
import math
####################
# Global Variables
debug = 0
vernum = "0.3"
#########
# Print version information and exit
def version():
print "+----------------------------------------------------------------------+"
print "| VirtualBotmaster.py Version "+ vernum +" |"
print "| This program is free software; you can redistribute it and/or modify |"
print "| it under the terms of the GNU General Public License as published by |"
print "| the Free Software Foundation; either version 2 of the License, or |"
print "| (at your option) any later version. |"
print "| |"
print "| Author: Garcia Sebastian, [email protected] |"
print "| UNICEN-ISISTAN, Argentina. CTU, Prague-ATG |"
print "+----------------------------------------------------------------------+"
print
# Print help information and exit:
def usage():
version()
print "\nusage: %s <options>" % sys.argv[0]
print "options:"
print " -h, --help Show this help message and exit"
print " -V, --version Output version information and exit"
print " -D, --debug Debug level. From 0 (no debug) to 5 (more debug)."
print " -x, --accel Acceleration time. 2 for 2x, 10 for 10x"
print " -c, --conf Configuration file. Defaults to ./VirtualBotmaster.conf"
print
sys.exit(1)
class Stop(Exception):
"""
Custom exception to stop the procesess under some conditions such as there are no more states.
"""
pass
# Network Class
###############
class Network(multiprocessing.Process):
"""
A class thread to run the output in the network
"""
global debug
def __init__(self, qnetwork, conf_file):
multiprocessing.Process.__init__(self)
self.qnetwork = qnetwork
self.conf_file = conf_file
self.output_file = ""
def read_conf(self):
"""
Read the conf and load the values
"""
try:
global debug
if debug > 1:
print 'Reading the configuration file.'
try:
self.output_file = self.conf_file.get('Network', 'output_file')
except:
print 'Some critical error reading in the config file for the Network. Maybe some syntax error.'
sys.exit(-1)
except Exception as inst:
if debug:
print '\tProblem with read_conf in Network class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def run(self):
try:
if debug:
print 'Network thread Started'
# Read conf
self.read_conf()
if self.output_file:
output = open(self.output_file, 'w')
while True:
flow = self.qnetwork.get()
# If we are initializing, tell when we are done.
if flow == 'Start':
self.qnetwork.task_done()
if self.output_file:
output.write('StartTime,Dur,Proto,SrcAddr,Sport,Dir,DstAddr,Dport,State,sTos,TotPkts,TotBytes,Label\n')
else:
print 'StartTime,Dur,Proto,SrcAddr,Sport,Dir,DstAddr,Dport,State,sTos,TotPkts,TotBytes,Label'
continue
if flow == 'Stop':
self.qnetwork.task_done()
break
else:
if self.output_file:
output.write(flow+'\n')
else:
print flow
if self.output_file:
output.close()
except KeyboardInterrupt:
if debug:
print 'Network: stopped.'
except Exception as inst:
if debug:
print '\tProblem with Network()'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
# CC Class
##########
class CC(multiprocessing.Process):
"""
A class thread to run a CC
"""
global debug
def __init__(self, accel, qbot_CC, qnetwork, conf_file, srcip, CCname):
multiprocessing.Process.__init__(self)
self.qbot_CC = qbot_CC
self.qnetwork = qnetwork
self.accel = float(accel)
self.conf_file = conf_file
self.CCname = CCname
# The srcip is send by the bot
self.srcaddr = srcip
self.CC_initialized = False
# If this variable is False, the CC will stop alone.
self.running = True
# Botnet time. Starts now.
self.bt = datetime.now()
#self.init_states()
# Hold the models
self.p = -1
self.P = -1
self.stored_state = ""
self.t1 = -1
self.t2 = -1
self.prob_longest_state = -1
# States for this run of the CC
self.states = ""
self.current_state = ""
self.iter_states = ""
self.histograms = []
self.nexts_times_to_wait = deque([])
# If we need to compensate a huge time value with an opposite
self.need_to_compensate = False
# Time that is the max we can substract from to have valids TD. We can not substract more than this because we can not go back in time.
self.max_accumulated_time = 0
self.linux_source_port_range = [32768,61000]
self.windows_vista_7_and_8_port_range = [49152,65535]
self.windows_xp_port_range = [1024,4999]
self.malware = [1030,65535]
self.current_source_port = 1030
self.lower_source_port = 1030
self.upper_source_port = 65535
def go_next_state(self):
"""
Returns the next state the CC should be on.
"""
try:
self.current_state = next(self.iter_states)
except StopIteration:
if debug > 2:
print 'ERROR! No more letters in the states'
raise
def get_flow_state(self):
"""
Get a new source port according to the operating system selected
"""
try:
global debug
if 'UDP' in self.label and 'Attempt' in self.label:
# UDP Attempt
self.protostate = "INT"
elif 'UDP' in self.label: # We don't care if it says establised or not
# UDP Established
self.protostate = "CON"
elif 'TCP' in self.label:
self.protostate = "FSPA_FSPA"
else:
# Assume TCP
self.protostate = "FSPA_FSPA"
except Exception as inst:
if debug:
print '\tProblem with get_flow_state() in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def get_srcdst_ratio(self):
"""
Get the ratio between src and dst from the histogram.
"""
try:
global debug
rh = self.histograms['rh']
rb = self.histograms['rb']
ratio_value = float(self.get_a_value_from_hist(rh, rb, type='srcdstratio'))
if self.ratio_adjustment > 0 and self.ratio_adjustment < 1:
return_value = self.ratio_adjustment
else:
return_value = ratio_value
return return_value
except Exception as inst:
if debug:
print '\tProblem with get_srcdst_ratio() in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def get_source_port(self):
"""
Get a new source port according to the operating system selected
"""
try:
global debug
if self.current_source_port >= self.lower_source_port and self.current_source_port < self.upper_source_port :
self.current_source_port += 1
elif self.current_source_port == self.upper_source_port and self.current_source_port != self.lower_source_port:
self.current_source_port = self.current_source_port + 1
else:
self.current_source_port = self.current_source_port
except Exception as inst:
if debug:
print '\tProblem with get_source_port() in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def get_packets_from_bytes(self,size):
"""
Given an amount of bytes, get the amount of packets
"""
try:
global debug
packets = 1
if size <= 120:
packets = 1
elif size > 120:
# Biggest tcp packet can have 1500 bytes
minimum_packets = int(size / 1500)
# Smallest tcp packet can have 41 bytes
maximum_packets = int(size / 41)
packets = int(math.ceil(float(size * self.rel_median * self.packets_to_bytes_ratio)))
if packets < minimum_packets:
packets = minimum_packets
elif packets > maximum_packets:
packets = maximum_packets
return packets
except Exception as inst:
if debug:
print '\tProblem with get_packets_from_bytes() in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def normalize_hists(self):
"""
Normalize all the hists
"""
try:
global debug
if debug > 1:
print 'Normalizing the hists.'
for hist in self.histograms:
# Get the total amount
total = 0
for bin in self.histograms[hist]:
total += bin
# Normalize
i = 0
while i < len(self.histograms[hist]):
self.histograms[hist][i] = self.histograms[hist][i] / float(total)
i += 1
#print self.histograms[hist]
except Exception as inst:
if debug:
print '\tProblem with normalize_hists in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def get_a_value_from_hist(self,hist,bins,type):
"""
Get a hist and return a value
"""
try:
global debug
if debug > 3:
print 'Getting a value from hist {}, and bins {} for type {}'.format(hist, bins, type)
min = bins[0]
max = bins[-1]
#1 Generate a random value between the min and max
value = False
selected_bin = False
# Repeat until we get a value
while not selected_bin:
value = random.uniform(min, max)
# value (mostly because of time) can not be smaller than the next time to wait.
diff = self.nexts_times_to_wait[-1] + value
if type == 'time' and self.nexts_times_to_wait[-1] >= 0 and diff < 0:
if debug > 6:
print 'Warning: time to wait:{}, value:{}'.format(self.nexts_times_to_wait[-1], value)
continue
# On which bin is the value?
# Start from 0 because some values can be lower than the smallest bin (like time)
b = 0
while b < len(bins):
if value < bins[b]:
selected_bin = b
break
b += 1
if b == len(bins):
# Means that we didn't found a bin for this value. Make it equal to the last bin... means 'more' than the last bin.
# Only used if the bin allows a grater value. Check the bin.
selected_bin = b
#if debug:
#print 'Value generated: {}. Is in bin #{}, Bins Value:{}'.format(value, selected_bin, bins[selected_bin])
#2 Generate a random probability between 0 and 1 for that value. If the prob is higher than the hist number for that value, then pick the value
prob = random.random()
hist_prob = hist[selected_bin - 1]
if debug > 8:
print '\tFor value: {}, Gen Prob: {}, hist prob: {}'.format(value, prob, hist_prob)
# If the value selected is less than the max value
if hist_prob > prob:
if debug > 2:
print '\tValue {} selected with prob {} for type {}'.format(value, prob, type)
return value
else:
selected_bin = False
except Exception as inst:
if debug:
print '\tProblem with get_a_value_from_hist in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def asleep(self,t):
"""
Sleep time that can be accelerated
"""
try:
time.sleep(t/self.accel)
time_diff = timedelta(seconds=t)
self.bt += time_diff
#if debug:
#print 'Real time: {}, Botnet time: {}'.format(datetime.now(), self.bt)
except Exception as inst:
if debug:
print '\tProblem with asleep in CC class. Maybe trying to sleep a negative time?'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def build_netflow(self, duration, size):
"""
Build the netflow and send it to the Network
"""
try:
if self.bidirectional:
# Select the values for each field of the flow according to the Markov Chain
# StartTime Dur Proto SrcAddr Sport Dir DstAddr Dport State sTos dTos TotPkts TotBytes Label
starttime = str(self.bt)
# If we have a duration adjustment, use it
dur = str('{:.3f}'.format(duration * self.duration_adjustment))
proto = self.proto
srcaddr = self.srcaddr
self.get_source_port()
sport = str(self.current_source_port)
dir = "<->"
dstaddr = self.dstaddr
dport = self.dstport
self.get_flow_state()
state = self.protostate
tos = self.tos
# If we have a size adjustment, use it
size_adjusted = int(size * self.size_adjustment)
if size_adjusted <= 41:
size_adjusted = 41
bytes = str(size_adjusted)
packets = str(self.get_packets_from_bytes(size_adjusted))
label = self.label
flow = starttime + self.flow_separator + dur + self.flow_separator + proto + self.flow_separator + srcaddr + self.flow_separator + sport + self.flow_separator + dir + self.flow_separator + dstaddr + self.flow_separator + dport + self.flow_separator + state + self.flow_separator + tos + self.flow_separator + packets + self.flow_separator + bytes + self.flow_separator + label
self.qnetwork.put(flow)
elif not self.bidirectional:
# First flow
starttime = str(self.bt)
# If we have a duration adjustment, use it
dur = str('{:.3f}'.format(duration * self.duration_adjustment / 2))
proto = self.proto
srcaddr = self.srcaddr
self.get_source_port()
sport = str(self.current_source_port)
dir = "->"
dstaddr = self.dstaddr
dport = self.dstport
self.get_flow_state()
if 'TCP' in self.proto:
state = self.protostate.split('_')[0]
else:
state = self.protostate
tos = self.tos
# Find the ratio of src and dst bytes
srcratio = self.get_srcdst_ratio()
# If we have a size adjustment, use it
size_adjusted = int(size * self.size_adjustment * srcratio)
if size_adjusted <= 41:
size_adjusted = 41
bytes = str(size_adjusted)
packets = str(self.get_packets_from_bytes(size_adjusted))
label = self.label
flow = starttime + self.flow_separator + dur + self.flow_separator + proto + self.flow_separator + srcaddr + self.flow_separator + sport + self.flow_separator + dir + self.flow_separator + dstaddr + self.flow_separator + dport + self.flow_separator + state + self.flow_separator + tos + self.flow_separator + packets + self.flow_separator + bytes + self.flow_separator + label
self.qnetwork.put(flow)
# If the label is an attempt, there is no flow comming back.
if not 'Attempt' in self.label:
# Second flow
starttime = str(self.bt)
# If we have a duration adjustment, use it
dur = str('{:.3f}'.format(duration * self.duration_adjustment / 2))
proto = self.proto
# The other ip
srcaddr = self.dstaddr
# The other port
sport = self.dstport
dir = "<-"
# The other ip
dstaddr = self.srcaddr
# The other port
self.get_source_port()
dport = str(self.current_source_port)
self.get_flow_state()
if 'TCP' in self.proto:
state = self.protostate.split('_')[0]
else:
state = self.protostate
tos = self.tos
# Find the ratio of src and dst bytes. This is dst bytes, so it should be 1 - what the hist tell us.
dstratio = 1 - srcratio
# If we have a size adjustment, use it
size_adjusted = int(size * self.size_adjustment * dstratio)
if size_adjusted <= 41:
size_adjusted = 41
bytes = str(size_adjusted)
packets = str(self.get_packets_from_bytes(size_adjusted))
label = self.label
flow = starttime + self.flow_separator + dur + self.flow_separator + proto + self.flow_separator + srcaddr + self.flow_separator + sport + self.flow_separator + dir + self.flow_separator + dstaddr + self.flow_separator + dport + self.flow_separator + state + self.flow_separator + tos + self.flow_separator + packets + self.flow_separator + bytes + self.flow_separator + label
self.qnetwork.put(flow)
# Not compute the counter flow
except Exception as inst:
if debug:
print '\tProblem with build_netflow in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def compute_sleep_time(self, time):
"""
Get a TD and compute the actual time we have to sleep.
"""
try:
global debug
# Sleep time is the implementation of how much we wait, that is, of periodicity and is very important!
# t3 = time + t2
try:
# Next sleeptime
last_time_in_queue = self.nexts_times_to_wait[-1]
self.nexts_times_to_wait.append( time + last_time_in_queue )
# This is the t to wait now
sleep_time = self.nexts_times_to_wait.popleft()
# Do we have a time adjustment from the config file?
sleep_time = sleep_time * self.times_adjustment
# Do not adjust the compensation times.
# Rest the sleep time in minutes to the length also in minutes
self.length_of_state_in_time -= sleep_time
if self.length_of_state_in_time <= 0:
if debug > 0:
print 'Run out of time. Stopping the CC {}.'.format(self.CCname)
self.running = False
return 0
#if debug > 1:
#print 'Sleeping: {}'.format(sleep_time)
if debug > 1:
print 'Going to sleep: {}, TD selected: {}, Queue: {}'.format(sleep_time, time, self.nexts_times_to_wait)
# If the sleep time is huge, we usually need to compensate it with a near equal but opposite value.
if self.need_to_compensate:
try:
sth = self.histograms['sth']
value_to_compensate = -1
while value_to_compensate <= 0:
value_to_compensate = self.get_a_value_from_hist(sth, self.histograms['stb'], type='time')
except:
# No sth stored! So just wait between 5 seconds mu with stdev 1
value_to_compensate = random.gauss(5,1)
self.nexts_times_to_wait.append( value_to_compensate )
self.need_to_compensate = False
if debug > 1:
print 'Compensation Sleep time added: {}'.format( value_to_compensate )
except IndexError:
# There are no more times stored
print 'Error! No more times stored to be used!'
exit(-1)
return sleep_time
except Exception as inst:
if debug:
print '\tProblem with compute_sleep_time in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def read_conf(self):
"""
Read the conf and load the values
"""
try:
global debug
if debug > 1:
print 'Reading the configuration file.'
try:
self.length_of_state_in_flows = self.conf_file.getint(self.CCname, 'length_of_state_in_flows')
self.length_of_state_in_time = self.conf_file.getint(self.CCname, 'length_of_state_in_time') * 60 # Should be minutes.
self.label = self.conf_file.get(self.CCname, 'label')
self.model_folder = self.conf_file.get('DEFAULT', 'markov_models_folder')
self.proto = self.conf_file.get(self.CCname, 'protocol')
self.dstaddr = self.conf_file.get(self.CCname, 'dstip')
self.dstport = self.conf_file.get(self.CCname, 'dstport')
self.flow_separator = self.conf_file.get('DEFAULT', 'flow_separator')
self.bidirectional = self.conf_file.getboolean('DEFAULT', 'bidirectional')
self.srcport = self.conf_file.get(self.CCname, 'srcport')
self.packets_to_bytes_ratio = self.conf_file.getfloat(self.CCname, 'packets_to_bytes_ratio')
self.delay_in_start_vector = self.conf_file.get(self.CCname, 'delay_in_start').split(',')
self.times_adjustment = self.conf_file.getfloat(self.CCname, 'times_adjustment')
self.duration_adjustment = self.conf_file.getfloat(self.CCname, 'duration_adjustment')
self.size_adjustment = self.conf_file.getfloat(self.CCname, 'size_adjustment')
self.ratio_adjustment = self.conf_file.getfloat(self.CCname, 'ratio_adjustment')
except:
print 'Some critical error reading in the config file for the CC. Maybe some syntax error.'
sys.exit(-1)
# Get the label protocol
if 'TCP' in self.label:
label_protocol = "TCP"
elif 'UDP' in self.label:
label_protocol = "UDP"
else:
# By default TCP
label_protocol = "TCP"
if debug:
print 'Warning! No proto in the label {} of CC {}!'.format(self.label, self.CCname)
# Process the proto
if self.proto == 'Default':
self.proto = label_protocol
elif 'TCP' not in self.proto and 'UDP' not in self.proto:
# If we don't know,
self.proto = label_protocol
# define the source port from the operating system
if 'WindowsXP' in self.srcport:
self.lower_source_port = self.windows_xp_port_range[0]
self.upper_source_port = self.windows_xp_port_range[1]
elif 'Windows7' in self.srcport:
self.lower_source_port = self.windows_vista_7_and_8_port_range[0]
self.upper_source_port = self.windows_vista_7_and_8_port_range[1]
elif 'Linux' in self.srcport:
self.lower_source_port = self.linux_source_port_range[0]
self.upper_source_port = self.linux_source_port_range[1]
elif 'Malware' in self.srcport:
self.lower_source_port = self.malware[0]
self.upper_source_port = self.malware[1]
elif type(self.srcport) is str and int(self.srcport) >= 0 and int(self.srcport) <= 65535:
self.lower_source_port = int(self.srcport)
self.upper_source_port = int(self.srcport)
else:
self.lower_source_port = 1030
self.upper_source_port = 1030
self.current_source_port = self.lower_source_port
# For the time being, always 0
self.tos = "0"
# Compute the delay in start
try:
mu = float(self.delay_in_start_vector[0]) * 60 # Should be minutes
stdev = float(self.delay_in_start_vector[1]) * 60 # Should be minutes
self.delay_in_start = random.gauss(mu, stdev)
except:
self.delay_in_start = 0
if debug:
print 'Label for CC {}: {}'.format(self.CCname ,self.label)
except Exception as inst:
if debug:
print '\tProblem with read_conf in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def get_model_values_for_this_state(self):
"""
Get the letter of the state and according to the current label, computes the values of time, duration and size according to the histograms in the model.
"""
try:
global debug
# Time
if self.current_state in '123456789':
# First time histogram
# TD = 0 lets us use the t2 and t1 here.
time = 0
elif self.current_state in 'abcdefghi':
# Second time histogram
try:
sth = self.histograms['sth']
stb = self.histograms['stb']
time = self.get_a_value_from_hist(sth, stb, type='time')
if debug > 2:
print '\tFor 2th time, value generated: {}'.format(time)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (fth).'
elif self.current_state in 'ABCDEFGHI':
# Third time histogram
try:
tth = self.histograms['tth']
ttb = self.histograms['ttb']
time = self.get_a_value_from_hist(tth, ttb, type='time')
if debug > 2:
print '\tFor 3th time, value generated: {}'.format(time)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (sth).'
elif self.current_state in 'rstuvwxyz':
# Fourth time histogram
try:
fth = self.histograms['fth']
ftb = self.histograms['ftb']
time = self.get_a_value_from_hist(fth, ftb, type='time')
# Time can not be smaller that the current time to wait
if debug > 2:
print '\tFor 4th time, value generated: {}'.format(time)
# We need to compensate this huge value if it was positive.
self.need_to_compensate = True
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (fth).'
# Duration
if self.current_state in '147adgADGrux':
# First duration histogram
try:
fdh = self.histograms['fdh']
fdb = self.histograms['fdb']
duration = self.get_a_value_from_hist(fdh, fdb, type='duration')
if debug > 2:
print '\tFor 1th duration, value generated: {}'.format(duration)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (fdh).'
elif self.current_state in '258behBEHsvy':
# Second duration histogram
try:
sdh = self.histograms['sdh']
sdb = self.histograms['sdb']
duration = self.get_a_value_from_hist(sdh, sdb, type='duration')
if debug > 2:
print '\tFor 2th duration, value generated: {}'.format(duration)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (sdh).'
elif self.current_state in '369cfiCFItwz':
# Third duration histogram
try:
tdh = self.histograms['tdh']
tdb = self.histograms['tdb']
duration = self.get_a_value_from_hist(tdh, tdb, type='duration')
if debug > 2:
print '\tFor 3th duration, value generated: {}'.format(duration)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (tdh).'
# Size
if self.current_state in '123abcABCrst':
# First size histogram
try:
fsh = self.histograms['fsh']
fsb = self.histograms['fsb']
size = self.get_a_value_from_hist(fsh, fsb, type='size')
if debug > 2:
print '\tFor 3th size, value generated: {}'.format(size)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (fsh).'
elif self.current_state in '456defDEFuvw':
# Second size histogram
try:
ssh = self.histograms['ssh']
ssb = self.histograms['ssb']
size = self.get_a_value_from_hist(ssh, ssb, type='size')
if debug > 2:
print '\tFor 3th size, value generated: {}'.format(size)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (ssh).'
elif self.current_state in '789ghiGHIxyz':
# Third size histogram
try:
tsh = self.histograms['tsh']
tsb = self.histograms['tsb']
size = self.get_a_value_from_hist(tsh, tsb, type='size')
if debug > 2:
print '\tFor 3th size, value generated: {}'.format(size)
except:
print 'Warning! A letter was generated from the MC that does not have a histogram stored... weird (tsh).'
# Return
try:
return (time,duration,size)
except:
print "\tError. Maybe the label's model is lacking some histogram??? Not enough data to generate flows for this label: {}".format(self.label)
sys.exit(-1)
except Exception as inst:
if debug:
print '\tProblem with get_model_values_for_this_state in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def read_histograms(self):
"""
Get
"""
try:
global debug
if debug > 1:
print 'Reading the histograms...'
try:
file_name = self.model_folder+'/labels.histograms'
if debug > 5:
print 'Reading histogram from file : {}'.format(file_name)
input = open(file_name, 'rb')
histograms = cPickle.load(input)
input.close()
self.histograms = histograms[self.label]
if debug > 2:
print '\tHistograms: {}'.format(self.histograms)
# Not needed anymore, they are already normalized
#self.normalize_hists()
except:
print 'Error. The label {0} has no histogram stored.'.format(self.label)
sys.exit(-1)
if not self.histograms:
print 'Error. There is not histograms to read.'
sys.exit(-1)
except Exception as inst:
if debug:
print '\tProblem with read_histograms in CC class'
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
sys.exit(1)
def read_mcmodels(self):
"""
From the folder name with the markov chain models, prepare the data to be used
The mc matrix and vector
The t1 and t2 values.
"""
try:
global debug
if debug > 1:
print 'Reading the models from folder: {}'.format(self.model_folder)
# Read all the models
list_of_files = os.listdir(self.model_folder)
for file in list_of_files:
try:
file_name = self.model_folder+'/'+file
if self.label in file_name:
input = open(file_name, 'rb')
try:
p = cPickle.load(input)
except:
if debug:
print 'Error. The label {0} has no p stored.'.format(self.label)
try:
P = cPickle.load(input)
except:
if debug:
print 'Error. The label {0} has no P stored.'.format(self.label)
try:
stored_state = cPickle.load(input)
except:
if debug:
print 'Error. The label {0} has no state stored.'.format(self.label)
try: