Skip to content

Commit 36801d8

Browse files
committed
update
1 parent 5541a57 commit 36801d8

File tree

11 files changed

+450
-581
lines changed

11 files changed

+450
-581
lines changed

eval.py

Lines changed: 85 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,19 @@
99
sys.path.append('./KitNET')
1010
from KitNET.model import test_mut
1111

12-
np.set_printoptions(precision=2)
13-
np.set_printoptions(threshold=10000000)
14-
np.set_printoptions(linewidth=140)
15-
np.set_printoptions(suppress=True)
16-
17-
18-
def logarithmic_compress(X, e=16.):
19-
for i in range(X.shape[0]):
20-
for j in range(X.shape[1]):
21-
if X[i][j] <= 1. - e:
22-
X[i][j] = -math.log(-X[i][j] - 1., e)
23-
elif 1. - e < X[i][j] <= e - 1.:
24-
X[i][j] = 1. / (e - 1.) * X[i][j]
25-
else:
26-
X[i][j] = math.log(X[i][j] + 1., e)
27-
return X
28-
2912

3013
def Euclidean_Distance(v1, v2):
3114
dis = np.linalg.norm(v1 - v2)
3215
return dis
3316

3417

3518
class Analyzer:
36-
37-
def __init__(self, org_rmse_file, org_pcap_file, sta_data_file, model_save_path, limit=None):
19+
def __init__(self,
20+
org_rmse_file,
21+
org_pcap_file,
22+
sta_data_file,
23+
model_save_path,
24+
limit=None):
3825

3926
self.del_num = 0
4027

@@ -53,7 +40,6 @@ def __init__(self, org_rmse_file, org_pcap_file, sta_data_file, model_save_path,
5340
self.grp_size = self.X_list[0].mal.shape[0]
5441

5542
feature_list = []
56-
# print("feature_list",np.array(self.feature_list).shape)
5743
for i in self.feature_list:
5844
for j in i:
5945
feature_list.append(j)
@@ -66,7 +52,7 @@ def __init__(self, org_rmse_file, org_pcap_file, sta_data_file, model_save_path,
6652
self.feature_list[:, 82:99:4] = 0.
6753

6854
# compiling mutated features
69-
self.rmse_list = test_mut(self.feature_list,model_save_path)
55+
self.rmse_list = test_mut(self.feature_list, model_save_path)
7056
self.rmse_list = np.array(self.rmse_list)
7157

7258
# Analyzing partial data
@@ -79,7 +65,8 @@ def __init__(self, org_rmse_file, org_pcap_file, sta_data_file, model_save_path,
7965
self.glb_dis_list = self.glb_dis_list[:self.len]
8066

8167
if len(self.rmse_list) < len(self.org_rmse_list) or limit is not None:
82-
print("Warning: Statistics are incomplete !", len(self.rmse_list), "<", len(self.org_rmse_list))
68+
print("Warning: Statistics are incomplete !", len(self.rmse_list),
69+
"<", len(self.org_rmse_list))
8370
self.org_pcap = self.org_pcap[:self.len]
8471
self.org_rmse_list = self.org_rmse_list[:self.len]
8572

@@ -88,7 +75,8 @@ def del_outlier(self, extend=2):
8875
# print(self.feature_list.shape)
8976
org_rmse_mean = np.mean(self.org_rmse_list)
9077
for i in range(self.len):
91-
if self.rmse_list[i] > self.org_rmse_list[i] * extend or self.rmse_list[i] > org_rmse_mean * extend:
78+
if self.rmse_list[i] > self.org_rmse_list[
79+
i] * extend or self.rmse_list[i] > org_rmse_mean * extend:
9280
self.rmse_list[i] = 0.
9381
del_list.append(i)
9482
for j in range(self.feature_list.shape[1]):
@@ -113,7 +101,12 @@ def save_mutated_traffic(self, mut_pcap_path):
113101
print("Total #pkts in mutated traffic:", len(pkt_List))
114102
wrpcap(mut_pcap_path, pkt_List)
115103

116-
def eval(self, AD_threshold, mimic_set_file, test_feat_file, knormer_file, need_mmr=False):
104+
def eval(self,
105+
AD_threshold,
106+
mimic_set_file,
107+
test_feat_file,
108+
knormer_file,
109+
need_mmr=False):
117110

118111
print("1.Time elapse:")
119112
b = self.org_pcap[-1].time - self.org_pcap[0].time
@@ -142,7 +135,7 @@ def eval(self, AD_threshold, mimic_set_file, test_feat_file, knormer_file, need_
142135
a = np.mean(self.rmse_list)
143136
print(" original:", b, "mutated:", a)
144137
print(" PDR:", (b - a) / b)
145-
print("-"*64)
138+
print("-" * 64)
146139

147140
print("# Detected:")
148141
b = self.org_rmse_list[self.org_rmse_list > AD_threshold].shape[0]
@@ -166,14 +159,16 @@ def eval(self, AD_threshold, mimic_set_file, test_feat_file, knormer_file, need_
166159
mut_dis = 0.
167160

168161
for i in range(mal_feat.shape[0]):
169-
org_dis += max(np.linalg.norm(mal_feat[i] - mimic_feat, axis=1))
170-
mut_dis += min(np.linalg.norm(mut_feat[i] - mimic_feat, axis=1))
162+
org_dis += max(np.linalg.norm(mal_feat[i] - mimic_feat,
163+
axis=1))
164+
mut_dis += min(np.linalg.norm(mut_feat[i] - mimic_feat,
165+
axis=1))
171166
MMR = 1. - mut_dis / org_dis
172167
print("Feature Changed:")
173168
print(" Before:", org_dis, "After:", mut_dis)
174169
print(" MMR:", MMR)
175170

176-
def plt_rmse(self,AD_threshold): # 对比原来的rmse和现在的rmse
171+
def plt_rmse(self, AD_threshold):
177172

178173
x = np.arange(0, self.len, 1)
179174
plt.figure()
@@ -182,11 +177,30 @@ def plt_rmse(self,AD_threshold): # 对比原来的rmse和现在的rmse
182177
# plt.plot(x,[np.mean(np.log(self.org_rmse_list))]*self.len,c='#8A977B',alpha=0.5)
183178
# plt.plot(x,[np.mean(np.log(self.rmse_list))]*self.len, c='#FE4365',alpha=0.5)
184179

185-
plt.scatter(x, self.org_rmse_list, s=12, c='#8A977B', alpha=0.5, label="Before")
186-
plt.scatter(x, self.rmse_list, s=12, c='#FE4365', alpha=0.5, label="After")
187-
plt.plot(x, [np.mean(self.org_rmse_list)] * self.len, c='#8A977B', alpha=0.3, linewidth=4)
188-
plt.plot(x, [np.mean(self.rmse_list)] * self.len, c='#FE4365', alpha=0.3, linewidth=4)
189-
plt.plot(x, [AD_threshold] * self.len, c='black', linewidth=2,label="AD_threshold")
180+
plt.scatter(x,
181+
self.org_rmse_list,
182+
s=12,
183+
c='#8A977B',
184+
alpha=0.5,
185+
label="Before")
186+
plt.scatter(x,
187+
self.rmse_list,
188+
s=12,
189+
c='#FE4365',
190+
alpha=0.5,
191+
label="After")
192+
plt.plot(x, [np.mean(self.org_rmse_list)] * self.len,
193+
c='#8A977B',
194+
alpha=0.3,
195+
linewidth=4)
196+
plt.plot(x, [np.mean(self.rmse_list)] * self.len,
197+
c='#FE4365',
198+
alpha=0.3,
199+
linewidth=4)
200+
plt.plot(x, [AD_threshold] * self.len,
201+
c='black',
202+
linewidth=2,
203+
label="AD_threshold")
190204
plt.title("RMSE change and mean")
191205
plt.xlabel('pkt no.')
192206
plt.ylabel('RMSE in Kitsune')
@@ -196,28 +210,49 @@ def plt_rmse(self,AD_threshold): # 对比原来的rmse和现在的rmse
196210
plt.show()
197211

198212

199-
200-
201213
if __name__ == "__main__":
202214

203215
parse = argparse.ArgumentParser()
204-
parse.add_argument('-op', '--org_pcap_file', type=str, required=True,
216+
parse.add_argument('-op',
217+
'--org_pcap_file',
218+
type=str,
219+
required=True,
205220
help="original malicious (test) traffic (.pcap)")
206221

207-
parse.add_argument('-or', '--org_rmse_file', type=str, required=True,
208-
help="original RMSE file of test malicious traffic (.pkl)")
222+
parse.add_argument(
223+
'-or',
224+
'--org_rmse_file',
225+
type=str,
226+
required=True,
227+
help="original RMSE file of test malicious traffic (.pkl)")
209228

210-
parse.add_argument('-of', '--org_feat_file', type=str,
229+
parse.add_argument('-of',
230+
'--org_feat_file',
231+
type=str,
211232
help="original (test) feature (.npy)")
212233

213-
parse.add_argument('-b', '--mimic_set', type=str, required=True, help="benign features to mimic (.npy)")
214-
215-
parse.add_argument('-n', '--normalizer', type=str, required=True, help="compiled feature normalizer (.pkl)")
216-
217-
parse.add_argument('-sf', '--sta_file', type=str, default='./example/statistics.pkl',
234+
parse.add_argument('-b',
235+
'--mimic_set',
236+
type=str,
237+
required=True,
238+
help="benign features to mimic (.npy)")
239+
240+
parse.add_argument('-n',
241+
'--normalizer',
242+
type=str,
243+
required=True,
244+
help="compiled feature normalizer (.pkl)")
245+
246+
parse.add_argument('-sf',
247+
'--sta_file',
248+
type=str,
249+
default='./example/statistics.pkl',
218250
help="statistics to read(.pkl)")
219251

220-
parse.add_argument('-mf', '--model_file_path', type=str, default='./example/model.pkl',
252+
parse.add_argument('-mf',
253+
'--model_file_path',
254+
type=str,
255+
default='./example/model.pkl',
221256
help="model_file after training")
222257

223258
arg = parse.parse_args()
@@ -237,15 +272,9 @@ def plt_rmse(self,AD_threshold): # 对比原来的rmse和现在的rmse
237272
AD_threshold = pkl.load(f)
238273
print("AD_threshold:", AD_threshold)
239274

240-
a.eval(AD_threshold,arg.mimic_set,arg.org_feat_file,arg.normalizer,need_mmr=True)
275+
a.eval(AD_threshold,
276+
arg.mimic_set,
277+
arg.org_feat_file,
278+
arg.normalizer,
279+
need_mmr=True)
241280
a.plt_rmse(AD_threshold)
242-
243-
244-
245-
246-
247-
248-
249-
250-
251-

initializer.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,43 +20,45 @@ def decide_has_pkt(crafted_pkt_prob):
2020

2121

2222
def initialize(
23-
grp_size, # Number of pkts in each group
24-
last_end_time,
25-
groupList, # Pcap info in current group
26-
max_time_extend, # maximum time overhead (l_t)
27-
max_cft_pkt, # maximum crafted traffic overhead (l_c)
28-
min_time_extend,
29-
max_crafted_pkt_prob,
30-
):
23+
grp_size, # Number of pkts in each group
24+
last_end_time,
25+
groupList, # Pcap info in current group
26+
max_time_extend, # maximum time overhead (l_t)
27+
max_cft_pkt, # maximum crafted traffic overhead (l_c)
28+
min_time_extend,
29+
max_crafted_pkt_prob,
30+
):
3131

32-
X = Unit(grp_size,max_cft_pkt) # position vector
32+
X = Unit(grp_size, max_cft_pkt) # position vector
3333

34-
ics_time = 0 # accumulated increased ITA
34+
ics_time = 0 # accumulated increased ITA
3535

3636
for i in range(grp_size):
3737
if i == 0:
3838
itv = groupList[i].time - last_end_time
3939
else:
40-
itv = groupList[i].time - groupList[i-1].time
40+
itv = groupList[i].time - groupList[i - 1].time
4141
# ics_time += random.uniform(0,max_time_extend)*itv
42-
ics_time += random.uniform(min_time_extend,max_time_extend)*itv
42+
ics_time += random.uniform(min_time_extend, max_time_extend) * itv
4343
X.mal[i][0] = groupList[i].time + ics_time
4444

4545
max_mal_itv = (groupList[-1].time - last_end_time) * (max_time_extend + 1)
4646

4747
# building slot map
4848
slot_num = grp_size * max_cft_pkt
49-
slot_itv = max_mal_itv/slot_num
49+
slot_itv = max_mal_itv / slot_num
5050

5151
# initializing crafted pkts
5252
crafted_pkt_prob = random.uniform(0, max_crafted_pkt_prob)
5353
nxt_mal_no = 0
5454

5555
proto_max_lmt = [] # maximum protocol layer number
5656
for i in range(grp_size):
57-
if groupList[i].haslayer(TCP) or groupList[i].haslayer(UDP) or groupList[i].haslayer(ICMP):
57+
if groupList[i].haslayer(TCP) or groupList[i].haslayer(
58+
UDP) or groupList[i].haslayer(ICMP):
5859
proto_max_lmt.append(3.)
59-
elif groupList[i].haslayer(IP) or groupList[i].haslayer(IPv6) or groupList[i].haslayer(ARP):
60+
elif groupList[i].haslayer(IP) or groupList[i].haslayer(
61+
IPv6) or groupList[i].haslayer(ARP):
6062
proto_max_lmt.append(2.)
6163
elif groupList[i].haslayer(Ether):
6264
proto_max_lmt.append(1.)
@@ -69,12 +71,13 @@ def initialize(
6971
nxt_mal_no += 1
7072
if nxt_mal_no == grp_size:
7173
break
72-
if (not decide_has_pkt(crafted_pkt_prob)) or X.mal[nxt_mal_no][1] == max_cft_pkt:
74+
if (not decide_has_pkt(crafted_pkt_prob)
75+
) or X.mal[nxt_mal_no][1] == max_cft_pkt:
7376
continue
7477
cft_no = int(round(X.mal[nxt_mal_no][1]))
7578

7679
if proto_max_lmt[nxt_mal_no] == 3.:
77-
X.craft[nxt_mal_no][cft_no][1] = random.choice([1.,2.,3.])
80+
X.craft[nxt_mal_no][cft_no][1] = random.choice([1., 2., 3.])
7881
mtu = 1460
7982
elif proto_max_lmt[nxt_mal_no] == 2.:
8083
X.craft[nxt_mal_no][cft_no][1] = random.choice([1., 2.])
@@ -90,5 +93,4 @@ def initialize(
9093

9194
X.mal[nxt_mal_no][1] += 1.
9295

93-
return X,proto_max_lmt
94-
96+
return X, proto_max_lmt

main.py

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,38 +5,55 @@
55
from manipulator import Manipulator
66

77
parse = argparse.ArgumentParser()
8-
parse.add_argument('-m', '--mal_pcap', type=str, required=True, help="input malicious traffic (.pcap)")
9-
10-
parse.add_argument('-b', '--mimic_set', type=str, required=True, help="benign features to mimic (.npy)")
11-
12-
parse.add_argument('-n', '--normalizer', type=str, required=True, help="compiled feature normalizer (.pkl)")
13-
14-
parse.add_argument('-i', '--init_pcap', type=str, default='./_empty.pcap',
8+
parse.add_argument('-m',
9+
'--mal_pcap',
10+
type=str,
11+
required=True,
12+
help="input malicious traffic (.pcap)")
13+
14+
parse.add_argument('-b',
15+
'--mimic_set',
16+
type=str,
17+
required=True,
18+
help="benign features to mimic (.npy)")
19+
20+
parse.add_argument('-n',
21+
'--normalizer',
22+
type=str,
23+
required=True,
24+
help="compiled feature normalizer (.pkl)")
25+
26+
parse.add_argument('-i',
27+
'--init_pcap',
28+
type=str,
29+
default='./_empty.pcap',
1530
help="preparatory traffic (ignore this if you don't need)")
1631

17-
parse.add_argument('-o', '--sta_file', type=str, default='./example/statistics.pkl',
32+
parse.add_argument('-o',
33+
'--sta_file',
34+
type=str,
35+
default='./example/statistics.pkl',
1836
help="file saving the final statistics (.pkl)")
1937

2038
arg = parse.parse_args()
2139

22-
# 创建Manipulator
2340
m = Manipulator(arg.mal_pcap, arg.mimic_set, arg.normalizer, arg.init_pcap)
2441

25-
# 选择配置参数
2642
max_iter, particle_num, local_grp_size = 3, 6, 3
2743
# max_iter,particle_num,local_grp_size = 4,8,4
2844
# max_iter,particle_num,local_grp_size = 5,10,5
2945
# max_iter,particle_num,local_grp_size = 3,10,5
3046

3147
m.change_particle_params(w=0.7298, c1=1.49618, c2=1.49618)
32-
m.change_pso_params(max_iter=max_iter, particle_num=particle_num, grp_size=local_grp_size)
48+
m.change_pso_params(max_iter=max_iter,
49+
particle_num=particle_num,
50+
grp_size=local_grp_size)
3351
m.change_manipulator_params(grp_size=100,
3452
min_time_extend=3.,
3553
max_time_extend=6.,
3654
max_cft_pkt=1,
3755
max_crafted_pkt_prob=0.01)
3856

39-
# 保存配置参数
4057
# m.save_configurations('./configurations.txt')
4158

4259
# tmp_pcap_file = "_crafted.pcap"

0 commit comments

Comments
 (0)