-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
271 lines (214 loc) · 7.8 KB
/
utils.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
import numpy as np
import pandas as pd
import torch
from torch_geometric.data import Data
from sklearn.model_selection import train_test_split
def get_data_info(data):
"""
0: Normal
1: Extortion Virus
2: Mining Program
3: DDoS Trojan Horse
4: Worm Virus
5: Infectious Virus
6: Backdoor Program
7: Trojan horse Program
"""
label = data.groupby(['file_id', 'label'])['label'].unique()
counts = label.value_counts()
apis = data['api'].unique()
files = data['file_id'].unique()
nb_files = len(files)
nb_data = len(data)
nb_labels = len(counts)
nb_apis = len(apis)+1
print('-----| Get Data Information |-----')
print(f"- Files : {nb_files:<6}\n"
f"- Data : {nb_data:<6}\n"
f"- Labels : {nb_labels:<6}\n"
f"- APIs : {nb_apis:<6}\n"
)
#print(counts)
#print()
return nb_files, nb_data, nb_labels, nb_apis
def print_progress(cur, total):
print(f"## Progress: {cur+1}/{total} ##", end='\r')
def split_per_id(data, nb_files):
split_per_flie_id = []
print('-----| Split Per File ID |-----')
for i in range(nb_files):
split_per_flie_id.append(data[data['file_id']==i+1])
print_progress(i, nb_files)
print('\n')
return split_per_flie_id
def creat_api2idx(data):
api_names = data['api'].unique()
api2idx = {}
api2idx['[UNK]'] = 0
for i, api_name in enumerate(api_names):
api2idx[api_name] = i+1
return api2idx
def encode_api_name(data_split_per_id, api2idx):
file_len = len(data_split_per_id)
files = []
labels = []
print('-----| Encode API Name |-----')
for i, datas in enumerate(data_split_per_id):
encoded_data = datas.copy()
encoded_apis = (encoded_data['api'].map(api2idx)).fillna(0).astype(int).to_list()
label = encoded_data['label'].to_list()[0]
files.append(encoded_apis)
labels.append(label)
"""
if len(encoded_apis) != len(label):
print("[!!!ERORR!!!] nb_Data != nb_Label")
print(f'{len(datas)}, {len(label)}')
"""
print_progress(i, file_len)
print('\n')
return files, labels
def get_adj(nb_feature, srcs, dsts):
adj = np.zeros((nb_feature, nb_feature))
for i in range(len(srcs)):
adj[srcs[i], dsts[i]] += 1
return adj
def norm_adj(adj_mat, f_type):
if f_type=='Normal':
a0 = 0.5 * (adj_mat + adj_mat.T)
max_value = np.max(a0)
if max_value == 0:
max_value = 1
adj_mat = a0 / max_value
elif f_type=='Aggregation':
sum_adj = adj_mat.sum(axis=0, keepdims=True)
sum_adj[sum_adj == 0] = 1
a1 = adj_mat / sum_adj
max_value = np.max(a1)
if max_value == 0:
max_value = 1
adj_mat = a1 / max_value
elif f_type=='Propagation':
sum_adj = adj_mat.sum(axis=0, keepdims=True)
sum_adj[sum_adj == 0] = 1
a2 = adj_mat / sum_adj
a02 = 0.5 * (a2 + a2.T)
max_value = np.max(a02)
if max_value == 0:
max_value = 1
adj_mat = a02 / max_value
return adj_mat
def create_feature_matrix(edge_idx, labels, api2idx, f_type='LDP'):
file_len = len(edge_idx)
nb_apis = len(api2idx)
print('-----| Create Feature Matrix |-----')
results_features = []
results_labels = []
for i, edge in enumerate(edge_idx):
srcs = edge[0]
dsts = edge[1]
label = labels[i]
if f_type=='LDP':
# degree
degrees = np.zeros((nb_apis))
for dst in dsts:
degrees[dst] += 1
degrees = degrees.reshape(-1, 1).tolist()
# neighboring nodes
features = []
for api_number in range(len(degrees)):
feature = []
indices = np.where(dsts == api_number)
neighboring = np.unique(srcs[indices])
# local degree proflie, LDP
if len(neighboring) == 0:
min_degree = 0
max_degree = 0
avg_degree = 0
std_degree = 0
else:
targets = np.array(degrees)[neighboring]
min_degree = np.min(targets)
max_degree = np.max(targets)
avg_degree = np.mean(targets)
std_degree = np.std(targets)
feature.append(degrees[api_number][0])
feature.append(min_degree)
feature.append(max_degree)
feature.append(avg_degree)
feature.append(std_degree)
features.append(feature)
nb_features = len(feature)
elif f_type=='Normal':
features = get_adj(nb_apis, srcs, dsts)
a0 = 0.5 * (features + features.T)
max_value = np.max(a0)
if max_value == 0:
max_value = 1
features = a0 / max_value
nb_features = len(features)
elif f_type=='Aggregation':
features = get_adj(nb_apis, srcs, dsts)
sum_features = features.sum(axis=0, keepdims=True)
sum_features[sum_features == 0] = 1
a1 = features / sum_features
max_value = np.max(a1)
if max_value == 0:
max_value = 1
features = a1 / max_value
nb_features = len(features)
elif f_type=='Propagation':
features = get_adj(nb_apis, srcs, dsts)
sum_features = features.sum(axis=0, keepdims=True)
sum_features[sum_features == 0] = 1
a2 = features / sum_features
a02 = 0.5 * (a2 + a2.T)
max_value = np.max(a02)
if max_value == 0:
max_value = 1
features = a02 / max_value
nb_features = len(features)
elif f_type=='One-Hot':
features = np.eye(nb_apis, nb_apis)
nb_features = len(features)
results_features.append(features)
cur_label = np.full((nb_apis), -1)
if len(dsts) != 0:
cur_label[dsts] = label
results_labels.append(cur_label)
print_progress(i, file_len)
print('\n')
return np.array(results_features), results_labels, nb_features
def create_edge_index(files):
print('-----| Create Edge Index |-----')
file_len = len(files)
results = []
for i, nodes in enumerate(files):
nb_edge = len(nodes)-1
src, dst = nodes[:-1], nodes[1:]
edge_idx = np.array([src, dst])
results.append(edge_idx)
print_progress(i, file_len)
print('\n')
return results
def create_geometric(feature_mat, edge_idx, labels):
print('-----| Create Geometric Data |-----')
nb_data = len(labels)
results = []
for i in range(nb_data):
x = torch.tensor(feature_mat[i], dtype=torch.float)
edge_index = torch.tensor(edge_idx[i], dtype=torch.int)
y = torch.tensor(labels[i], dtype=torch.long)
results.append(Data(x=x, edge_index=edge_index, y=y))
print_progress(i, nb_data)
print('\n')
return results
def preprocessing_graph_data(data, nb_files, f_type='LDP'):
data_split_per_id = split_per_id(data, nb_files)
api2idx = creat_api2idx(data)
files, labels = encode_api_name(data_split_per_id, api2idx)
edge_idx = create_edge_index(files)
feature_mat, labels, nb_features = create_feature_matrix(edge_idx, labels, api2idx, f_type)
processed = create_geometric(feature_mat, edge_idx, labels)
train, test = train_test_split(processed, test_size=0.1, random_state=1019, shuffle=False)
train, val = train_test_split(train, test_size=0.1, random_state=1019, shuffle=False)
return train, val, test, nb_features