-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmalwareClustering.py
410 lines (324 loc) · 21.6 KB
/
malwareClustering.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
import argparse
from src.config import *
from src.dataAnalyzer import DataAnalyzer
from src.dataClusterer import DataClusterer
from src.dataProcessor import DataProcessor, Log
from src.fileReader import read_files_in_folder
from src.util import log_stats, serialize_data, recompute_stats, get_most_important_malware_families
# FOLDER SETTINGS FOR PROCESSING AND DATA OUTPUT
folder_lookup_name = 'drebin-'
cache_folder = 'cache/'
export_stats_folder_name = 'stats'
evaluation_file_name = 'stats'
input_drebin_directory = '/drebin/'
output_directory = '/output_dir/'
clustering_method = 'all'
operation_mode = ''
feature_vector_directory = '/path_to_feature_vector_folder/*'
labeled_apk_csv_file_path = '/labeled_csv_path'
clustering_range = (2, 180)
sample_threshold = None
downsample = -1
include_benign = False
downsample_threshold = -1
extract_existing_feature = False
def main(argv):
"""
Main function in which all the settings are configured by console input.
The main process directives are here, telling the program which type of clustering to use and what to output.
"""
global operation_mode, input_drebin_directory, labeled_apk_csv_file_path, clustering_method, \
output_directory, feature_vector_directory, folder_lookup_name, evaluation_file_name, clustering_range, \
sample_threshold, downsample, include_benign, downsample_threshold, extract_existing_feature
# general runtime settings
initialize_settings()
if argv.output_directory is not None:
output_directory = argv.output_directory[0]
if argv.input_directory is not None:
input_drebin_directory = argv.input_directory[0]
if argv.operation_mode is not None:
operation_mode = argv.operation_mode
if argv.drebin_pattern is not None:
folder_lookup_name = argv.drebin_pattern[0]
if argv.drebin_csv_location is not None:
labeled_apk_csv_file_path = argv.drebin_csv_location[0]
if argv.feature_vector_directory is not None:
feature_vector_directory = argv.feature_vector_directory[0]
if argv.threshold_samples is not None:
sample_threshold = argv.threshold_samples[0]
if len(argv.threshold_samples) > 1:
downsample = bool(argv.threshold_samples[1])
if argv.downsample_threshold is not None:
downsample_threshold = argv.downsample_threshold[0]
if argv.num_clusters is not None:
clustering_range = []
if '|' in argv.num_clusters[0]:
bits = argv.num_clusters[0].split('|')
clustering_range = (int(bits[0]), int(bits[1]))
elif ',' in argv.num_clusters[0]:
clustering_range.extend(int(x) for x in argv.num_clusters[0].split(','))
elif argv.num_clusters[0] == 'adaptive':
clustering_range = argv.num_clusters[0]
else:
clustering_range = [int(argv.num_clusters[0])]
if argv.clustering_method is not None:
clustering_method = argv.clustering_method[0].split(',')
c_range_str_conversion = "_cluster_range_" + "_".join([str(i) for i in clustering_range]) \
if clustering_range != 'adaptive' else clustering_range
stats = []
if argv.load_previous_stats is not None:
stats = read_files_in_folder(lookup_files=argv.load_previous_stats[0], is_binary=True)
data_processor = DataProcessor(input_drebin_directory, output_directory, folder_lookup_name,
labeled_apk_csv_file_path, feature_vector_directory)
data_analyzer = DataAnalyzer()
data_classifier = None
for op_mode in operation_mode:
if op_mode == 'include_benign':
include_benign = True
elif op_mode == 'extract_apk_feature':
data_processor.extract_data()
elif op_mode == 'extract_existing_feature':
extract_existing_feature = True
data_processor.extract_data(get_existing_feature_vectors_only=extract_existing_feature,
include_all_samples=include_benign)
elif op_mode == 'analyze_data':
if data_processor.feature_vectors_subset and data_processor.labeled_apk_csv is not None:
if include_benign:
data_analyzer.record_feature_presence(feature_vectors=
dict(data_processor.feature_vectors_subset,
**data_processor.benign_feature_vectors),
feature_reduction=True)
else:
data_analyzer.record_feature_presence(feature_vectors=data_processor.feature_vectors_subset,
feature_reduction=True)
if data_analyzer.vectorized_data is not None and data_processor.labeled_apk_csv is not None:
if include_benign:
data_classifier = DataClusterer(data=data_analyzer.truncated_data_pca,
labels=data_processor.labeled_apk_csv_subset,
apk_names=list(data_processor.feature_vectors_subset.keys()),
clustering_method=clustering_method,
benign_included=include_benign)
else:
data_classifier = DataClusterer(data=data_analyzer.vectorized_data,
labels=data_processor.labeled_apk_csv_subset,
apk_names=list(data_processor.feature_vectors_subset.keys()),
clustering_method=clustering_method,
benign_included=include_benign)
elif op_mode == 'clustering':
if include_benign:
data_classifier.label_numbers, data_classifier.family_label_numbers = \
data_classifier.convert_labels_to_numbers \
(no_labels_malicious=len(data_processor.feature_vectors_subset),
no_labels_bening=len(data_processor.benign_feature_vectors))
else:
data_classifier.label_numbers, data_classifier.family_label_numbers = \
data_classifier.convert_labels_to_numbers()
if data_analyzer.vectorized_data is not None and data_processor.labeled_apk_csv is not None:
if include_benign:
data_classifier.compute_similarity_distances(data_classifier.data, disable_distances=False)
else:
data_classifier.compute_similarity_distances(data_classifier.data, disable_distances=False)
stats = []
stats1, stats2 = [], []
if type(clustering_range) is tuple:
Log.log_message(log_level="INFO",
log_message="Considering cluster range specified by user, cluster range:" +
str(clustering_range))
for i in range(clustering_range[0], clustering_range[1]):
stat_p = data_classifier.perform_unsupervised_clustering(n_clusters=i,
parallel_algo_only=True, )
stats1.extend([stat_p])
for i in range(clustering_range[0], clustering_range[1]):
stat_np = data_classifier.perform_unsupervised_clustering(n_clusters=i,
non_parallel_algo_only=True)
stats2.extend([stat_np])
elif clustering_range == 'adaptive':
adaptive_range = range(2, len(data_processor.labeled_apk_csv_subset.keys()) + 1)
Log.log_message(log_level="INFO",
log_message="Considering adaptive cluster range baesd on "
"number of malware classes/families considered"
" in the dataset, cluster range:" +
str(adaptive_range))
for i in adaptive_range:
stat = data_classifier.perform_unsupervised_clustering(n_clusters=i,
parallel_algo_only=True)
stats1.extend([stat])
for i in adaptive_range:
stat = data_classifier.perform_unsupervised_clustering(n_clusters=i,
non_parallel_algo_only=True)
stats2.extend([stat])
else:
for i in clustering_range:
stat = data_classifier.perform_unsupervised_clustering(n_clusters=i,
parallel_algo_only=True)
stats1.extend([stat])
stat = data_classifier.perform_unsupervised_clustering(n_clusters=i,
non_parallel_algo_only=True)
stats2.extend([stat])
stats.extend(stats1)
stats.extend(stats2)
log_stats(stats)
elif op_mode == 'cache_all':
if stats:
if sample_threshold:
if downsample_threshold != -1 and downsample != -1:
serialize_data(stats, file_name=export_stats_folder_name + "/" +
evaluation_file_name +
"_sample_threshold_" + str(sample_threshold) + "_"
+ "_".join(clustering_method) + "_" + c_range_str_conversion + "_downsampled_to_" + str(downsample_threshold))
else:
serialize_data(stats, file_name=export_stats_folder_name + "/" +
evaluation_file_name +
"_sample_threshold_" + str(sample_threshold) + "_"
+ "_".join(clustering_method) + "_" + c_range_str_conversion)
else:
serialize_data(stats, file_name=export_stats_folder_name + "/" +
evaluation_file_name +
"_full_data_set" + "_"
+ "_".join(clustering_method) + c_range_str_conversion)
if data_processor is not None:
serialize_data(data_processor, file_name=cache_folder + 'data_processor', ignore_timestamp=True)
if data_analyzer is not None:
serialize_data(data_analyzer, file_name=cache_folder + 'data_analyzer', ignore_timestamp=True)
if data_classifier is not None:
serialize_data(data_classifier, file_name=cache_folder + 'data_classifier', ignore_timestamp=True)
elif op_mode == 'load_cache':
data_processor = read_files_in_folder(input_folder=output_directory + cache_folder,
lookup_files='data_processor.bin',
is_binary=True)
data_analyzer = read_files_in_folder(input_folder=output_directory + cache_folder,
lookup_files='data_analyzer.bin',
is_binary=True)
data_classifier = read_files_in_folder(input_folder=output_directory + cache_folder,
lookup_files='data_classifier.bin',
is_binary=True)
elif op_mode == 'threshold_dataset':
if data_processor.labeled_apk_csv is not None and sample_threshold and not include_benign:
th_data = get_most_important_malware_families(data_processor.labeled_apk_csv,
sample_count_threshold=sample_threshold)
apk_list = []
for malware_family_name in th_data['threshold_samples'].keys():
if downsample > 0:
if sample_threshold < 0:
if downsample_threshold > 0:
apk_list.extend(
data_processor.labeled_apk_csv[malware_family_name][:downsample_threshold])
else:
apk_list.extend(
data_processor.labeled_apk_csv[malware_family_name][:abs(sample_threshold)])
elif len(data_processor.labeled_apk_csv[malware_family_name]) >= abs(sample_threshold):
if downsample_threshold > 0:
apk_list.extend(
data_processor.labeled_apk_csv[malware_family_name][:downsample_threshold])
else:
apk_list.extend(
data_processor.labeled_apk_csv[malware_family_name][:abs(sample_threshold)])
else:
if sample_threshold < 0 and len(data_processor.labeled_apk_csv[malware_family_name]) <= abs(sample_threshold):
apk_list.extend(data_processor.labeled_apk_csv[malware_family_name])
else:
apk_list.extend(data_processor.labeled_apk_csv[malware_family_name])
if data_processor:
data_processor.extract_data(get_existing_feature_vectors_only=extract_existing_feature,
drebin_apk_file_list=apk_list,
include_all_samples=include_benign)
else:
Log.log_message(log_level="ERROR",
log_message='Please perform data processing before attempting to threshold.')
else:
Log.log_message(log_level="ERROR",
log_message='Please perform data processing before attempting to threshold.'
'Labeled apk csv not found or sample_treshold undefined.')
elif op_mode == 'plot_data':
if stats:
data_analyzer.export_stats_to_csv(stats, sample_threshold)
data_analyzer.plot_important_metrics(stats, sample_threshold)
if sample_threshold is not None:
data_analyzer.plot_sample_data_histogram(full_samples=data_processor.labeled_apk_csv,
samples=data_processor.labeled_apk_csv_subset,
sample_threshold=sample_threshold,
downsample_threshold=downsample_threshold)
elif op_mode == 'recompute_stats':
if stats:
stats = recompute_stats(stats, data_classifier.data, data_classifier.data_dense,
data_classifier.label_numbers)
elif op_mode == 'visualize_dataset':
if data_classifier is not None:
if sample_threshold is not None:
data_analyzer.dataset_visualisation(label_numbers=data_classifier.label_numbers,
sample_threshold=sample_threshold,
family_label_numbers=data_classifier.family_label_numbers)
elif downsample_threshold > 0 and sample_threshold is not None:
data_analyzer.dataset_visualisation(label_numbers=data_classifier.label_numbers,
sample_threshold=sample_threshold,
downsample_threshold=downsample_threshold,
family_label_numbers=data_classifier.family_label_numbers)
else:
data_analyzer.dataset_visualisation(label_numbers=data_classifier.label_numbers,
family_label_numbers=data_classifier.family_label_numbers)
print("############################################################## \n")
c = input('all finished, close?')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=
'Performs clustering given the DREBIN dataset of malware on Android '
'apks. \n '
'Arguments: -i input directory for the DREBIN dataset , (zip files '
'only) \n '
'-m should the application only be used to '
'extract data from APKs (feature vectors),'
' apply machine learning on existing feature vectors \n'
' or simply process data from APKs or all 3 options \n'
'-o output directory for cluster statistics and data. \n '
'-c classification method type (e.g All, k-means , dbscan, etc) \n'
'-p folder names (if any) of where the drebin APKs are stored,'
' will be used as pattern for searching'
', default: drebin- '
'(will search in all folders that start with "drebin-" \n'
'-f feature vector directory location '
'-drebin_csv /--drebin_csv_location '
'location of the drebin csv that contains the labels of all APK samples \n'
)
parser.add_argument('-p', '--drebin_pattern', type=str, nargs=1,
help='-p folder names (if any) of where the drebin APKs are stored,'
' will be used as pattern for searching e.g: drebin- (optional) \n')
parser.add_argument('-odir', '--output_directory', type=str, nargs=1,
help='-i input directory for the DREBIN APKS, (zip containing the '
'manifest files only) \n')
parser.add_argument('-idir', '--input_directory', type=str, nargs=1,
help='-o output directory for cluster statistics and data. \n')
parser.add_argument('-dcsv', '--drebin_csv_location', type=str, nargs=1,
help='-drebin_csv /--drebin_csv_location '
'location of the drebin csv that contains the labels of all APK samples \n')
parser.add_argument('-f', '--feature_vector_directory', type=str, nargs=1,
help='-f feature vector directory \n')
parser.add_argument('-m', '--operation_mode', type=str, nargs='*', required=False,
choices=['extract_apk_feature',
'extract_existing_feature',
'learning',
'analyze_data',
'clustering',
'cache_all',
'load_cache',
'plot_data',
'visualize_dataset',
'threshold_dataset', 'recompute_stats', 'include_benign'],
help='-m operation mode, meaning extract data from APKs,'
' apply machine learning on existing feature vectors'
' or simply process data from APKs (features vectors)'
'default: none \n')
parser.add_argument('-ls', '--load_previous_stats', type=str, nargs=1,
help='-ls load previous stats from file \n')
parser.add_argument('-dhs', '--downsample_threshold', type=int, nargs='*',
help='only consider X number of sample from the thresholded number of classes,'
' must be used in conjuction with -ths argument , -ths X 1, 1 means enable downsampling')
parser.add_argument('-ths', '--threshold_samples', type=int, nargs='*',
help='only consider malware classes that have above X samples,'
' can be downsampled to the X samples passed if a second param is added : 1 or 0')
parser.add_argument('-nc', '--num_clusters', type=str, nargs=1,
help='-num_clusters number of clusters to be used in unsupervised methods, range (n, m)'
'n,m >= 2, eg -nc "2|166" will iteratively cluster from 2 to 166 clusters in range '
'(will take some time),'
' -nc 23 44 66 will cluster only with 23 44 and 66 clusters \n')
parser.add_argument('-c', '--clustering_method', type=str, nargs='*',
help='-c clustering_method method type (e.g All, k-means , dbscan, etc \n')
main(parser.parse_args())