Skip to content

Commit f2cc3f0

Browse files
author
Nicolas@Thor
committed
Merge branch 'dev'
2 parents 726dc4b + e6a6f1d commit f2cc3f0

8 files changed

Lines changed: 555 additions & 22 deletions

File tree

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,5 @@ __pycache__
77
*.csv
88
# Plot files
99
*.png
10+
# Log files
11+
*.log

config.yaml

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,48 @@ options:
1818
windows: [30, 60, 120, 150, 180, 300, 360] # number of datapoints of the non-overlapping windows
1919
infected: [0, 1, 5, 6, 7, 8, 9] # positions of the infected datasets
2020
healthy: [2] # position of the healthy dataset
21-
functions: ['mean'] # aggragation functions
21+
functions: ['mean'] # aggragation functions
22+
23+
24+
# policy creation
25+
## general
26+
windowSize: 360 # define the window size for which the policy should be generated
27+
aggregateFunctions: ['mean', 'min', 'max']
28+
29+
seed: 10 # random seed to obtain the same policies in the random approach
30+
randomPolicyCreation: False # enable random policy creation
31+
randomNumberOfPolicyRules: False
32+
maxNumberOfPolicyRules: 6
33+
minNumberOfPolicyRules: 3
34+
exactNumberOfPolicyRules: 4
35+
36+
completePolicyCreation: True # enable complete policy creation
37+
38+
expertPolicyCreation: False
39+
40+
#
41+
threshholds: [1, 3, 5]
42+
43+
# policy selection
44+
interval: 60
45+
countMalwareIndicators: False
46+
countMalwareTypeIndicators: False
47+
countMalwareIndicatorsRelatively: True
48+
modes:
49+
- name: sensitive
50+
letter: S
51+
detectionTreshold: 0.05
52+
- name: average
53+
letter: A
54+
detectionTreshold: 0.05
55+
- name: robust
56+
letter: R
57+
detectionTreshold: 0.80
58+
mode:
59+
- name: robust
60+
letter: R
61+
detectionTreshold: 0.80
62+
63+
64+
dstatCommand: ['dstat', '-t', '--cpu', '--mem', '-d', '--disk-tps', '-n', '--tcp', '-y', '-p', '-N', 'eth0', '1', '2']
65+
ipFinderCommand: ['hostname', '-I']

observer/observer-dstat.sh

100644100755
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ sudo apt-get install dstat
1919
'
2020
cd /root/MTDPolicy/data/csv/
2121

22-
iterations=60
22+
iterations=1
2323
delay=1
24-
observations=30
24+
observations=1800
2525
for ((i = 0 ; i < $iterations ; i++)); do
2626
now=`date +%F-%H-%M-%S`
2727
suffix="-log.csv"

policyCreator.py

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import glob
2+
import pandas as pd
3+
import numpy as np
4+
import yaml
5+
import random
6+
import utils
7+
8+
# load config
9+
with open('config.yaml') as stream:
10+
config = yaml.safe_load(stream)
11+
12+
windowSize = config['windowSize']
13+
randomPolicyCreation = config['randomPolicyCreation']
14+
randomNumberOfPolicyRules = config['randomNumberOfPolicyRules']
15+
minNumberOfPolicyRules = config['minNumberOfPolicyRules']
16+
maxNumberOfPolicyRules = config['maxNumberOfPolicyRules']
17+
exactNumberOfPolicyRules = config['exactNumberOfPolicyRules']
18+
completePolicyCreation = config['completePolicyCreation']
19+
expertPolicyCreation = config['expertPolicyCreation']
20+
aggregateFunctions = config['aggregateFunctions'] # avg, min, max
21+
22+
AGGREGATEFUNCTION = aggregateFunctions[0]
23+
SEED = config['seed']
24+
POLICYCOLUMNS = utils.POLICYCOLUMNS
25+
26+
# set seed
27+
random.seed(SEED)
28+
print(random.random())
29+
30+
31+
def createPolicy():
32+
33+
# load the csv with windowSize
34+
filenames = [file for file in glob.glob(
35+
'./*.csv') if 'policy({}).csv'.format(windowSize) in file]
36+
csvPolicy = pd.read_csv(filenames[0], header=None)
37+
38+
# postprocess: set header and group by malwaretype
39+
csvPolicy.columns = POLICYCOLUMNS
40+
# print(malwareGroup.get_group('httpbackdoor')) # DEBUG
41+
malwareGroup = csvPolicy.groupby(['malware'])
42+
43+
# policy creation
44+
policy = pd.DataFrame()
45+
46+
# random policy creation
47+
# iterate over all malware groups and add some (random or defined) rules (row) for each malware type
48+
if randomPolicyCreation == True:
49+
method = 'random'
50+
if randomNumberOfPolicyRules == True:
51+
method += '({}-{})'.format(minNumberOfPolicyRules,
52+
maxNumberOfPolicyRules)
53+
else:
54+
method += '({})'.format(exactNumberOfPolicyRules)
55+
56+
for malware in malwareGroup:
57+
# malware is a tuple: (name, df)
58+
rows = malware[1].shape[0] # number of rows for that malware type
59+
60+
# random number of rules
61+
if randomNumberOfPolicyRules == True:
62+
63+
# define random number between min/max number of policy rules
64+
random.seed(SEED)
65+
nRules = random.choice(
66+
[minNumberOfPolicyRules, maxNumberOfPolicyRules])
67+
68+
# defined number of rules
69+
else:
70+
nRules = exactNumberOfPolicyRules
71+
72+
# make sure we don't have more rules than rows
73+
while(rows < nRules):
74+
nRules -= 1
75+
76+
# print(malware[1].sample(n = nRules)) # DEBGUG
77+
# add defined rules to policy
78+
# todo check what happens if nRules > n when set
79+
policy = policy.append(
80+
malware[1].sample(n=nRules, random_state=SEED))
81+
policy = policy.drop_duplicates(subset=['metric'])
82+
83+
# complete policy creation
84+
# iterate over all malware groups and all rules (row) for each malware type
85+
elif completePolicyCreation == True:
86+
method = 'complete'
87+
policy = csvPolicy
88+
89+
# expert policy creation
90+
elif expertPolicyCreation == True:
91+
method = 'expert'
92+
pass
93+
# to be done
94+
95+
# postprocessing
96+
# remove aggregate function string for all rows
97+
policy['metric'] = policy['metric'].str.replace(
98+
'-{}'.format(AGGREGATEFUNCTION), '')
99+
policyName = 'policy({})-{}-{}'.format(windowSize,
100+
AGGREGATEFUNCTION, method)
101+
policy.to_csv('{}.csv'.format(policyName), index=False)
102+
103+
return policy
104+
105+
106+
def malwareDistribution(policy):
107+
# init
108+
CNCMALWARE = utils.CNC
109+
RKMALWALRE = utils.ROOTKIT
110+
RWMALWARE = utils.RANSOMWARE
111+
MALWARECATEGORIES = utils.MALWARECATEGORIES
112+
113+
conditions = [
114+
(policy['malware'].isin(CNCMALWARE)),
115+
(policy['malware'].isin(RKMALWALRE)),
116+
(policy['malware'].isin(RWMALWARE))
117+
]
118+
# classify each malware by type and add type column
119+
policy['malwaretype'] = np.select(conditions, MALWARECATEGORIES)
120+
121+
# count different malware types and create a dict
122+
malwareTypes = policy['malwaretype'].value_counts().index.tolist()
123+
malwareOccurrences = policy['malwaretype'].value_counts().values.tolist()
124+
malwareTypeOcc = {malwareTypes[i]: malwareOccurrences[i]
125+
for i in range(len(malwareTypes))}
126+
127+
# count total occurences of all malware types
128+
totalOccurences = sum(malwareOccurrences)
129+
'''
130+
malwareTypeOcc: {
131+
'Rootkit': 3
132+
'CnC': 7
133+
'Ransomware: 3
134+
}
135+
totalOccurences: 13
136+
array([0.53846154, 0.23076923, 0.23076923])
137+
'''
138+
139+
return [malwareTypeOcc, totalOccurences, np.divide(malwareOccurrences, totalOccurences)]

prePolicy.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import glob
2+
import os
3+
from cv2 import detail_BestOf2NearestRangeMatcher
4+
import pandas as pd
5+
import numpy as np
6+
import matplotlib.pyplot as plt
7+
import seaborn as sns
8+
import statsmodels.api as sm
9+
import shutil
10+
import csv
11+
import yaml
12+
import random
13+
14+
COLS = ['malware', 'metric', 'sign', 'threshold']
15+
with open('config.yaml') as stream:
16+
config = yaml.safe_load(stream)
17+
18+
print(config['policy'])
19+
20+
file = [i for i in glob.glob('./*.csv') if str(config['policy']) in i]
21+
22+
thresholds = pd.read_csv(file[0], header = None)
23+
thresholds.columns = COLS
24+
th = thresholds.groupby(['malware'])
25+
26+
#print(th.get_group('httpbackdoor'))
27+
28+
policy = pd.DataFrame()
29+
for malware in th:
30+
if config['random'] == True:
31+
# malware is a tuple: (name, df)
32+
rows = malware[1].shape[0]
33+
nRules = random.choice([config['MIN_TH'], config['MAX_TH']])
34+
while(rows < nRules):
35+
nRules = random.choice([config['MIN_TH'], config['MAX_TH']])
36+
37+
else:
38+
nRules = config['NUMBER_TH']
39+
print('false')
40+
print(malware[1].sample(n = nRules))
41+
policy = policy.append(malware[1].sample(n = nRules))
42+
43+
print(policy)
44+
policy.to_csv('policy.csv', index=False)

0 commit comments

Comments
 (0)