forked from ngoctint1lvc/waf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.py
388 lines (316 loc) · 9.87 KB
/
tasks.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
from invoke import task, run
import codecs
import shutil
import os
from urllib.parse import quote_plus
import re
from pprint import pprint
def change_dir(dir=None):
working_dir = os.path.abspath(os.path.dirname(__file__))
if dir:
working_dir = os.path.join(working_dir, dir)
os.chdir(working_dir)
change_dir()
def replace_file_regex(filepath, search, replace):
with open(filepath, "r+") as f:
content = f.read()
content = re.sub(search, replace, content)
f.seek(0)
f.write(content)
f.truncate()
def grep_file_regex(filepath, searchRegex):
with open(filepath, "r") as fd:
content = fd.read()
return re.search(searchRegex, content)
@task
def up(c, build=False):
change_dir()
c.run("docker-compose up -d" + (' --build' if build else ''))
dns_reload(c)
config(c)
def get_container_ip(name):
ip = run(
r"docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' " + name, hide='out').stdout
ip = ip.replace("\n", "")
return ip
@task
def ip(c):
'''
Show all current container ips
'''
conainters = c.run(r"docker container ls --format '{{.Names}}'", hide='out').stdout.split("\r\n")[:-1]
for container in conainters:
debug(get_container_ip(container))
@task
def dns_reload(c):
openresty_ip = get_container_ip("openresty-waf")
dvwa_ip = get_container_ip("dvwa-test")
nginx_ip = get_container_ip("nginx-test")
mongodb_ip = get_container_ip("waf-log-db")
# domains = ['dvwa.test', 'nginx.test', 'openresty.docker']
config = f'''
address=/openresty.docker/{openresty_ip}
address=/dvwa.test/{dvwa_ip}
address=/nginx.test/{nginx_ip}
address=/mongo.docker/{mongodb_ip}
'''
c.run(
f"sudo bash -c \"echo '{config}' > /etc/dnsmasq.d/docker-config.conf\"", pty=False)
c.run("sudo systemctl restart dnsmasq", pty=False)
@task
def init_vscode(c):
change_dir()
has_vscode = shutil.which("code")
if not has_vscode:
print("[x] Please install vscode")
return
c.run("code .")
folder_uri = 'vscode-remote://attached-container+' + \
codecs.encode(b'{"containerName":"waf_openresty_1"}',
'hex').decode() + '/opt/modsecurity'
c.run(f"code --folder-uri '{folder_uri}'")
@task
def reload(c, proxy=False, all=False):
change_dir()
if all:
c.run("docker-compose exec openresty nginx -s reload")
c.run("docker-compose exec proxy-server nginx -s reload")
elif proxy:
c.run("docker-compose exec proxy-server nginx -s reload")
else:
c.run("docker-compose exec openresty nginx -s reload")
@task
def restart(c, proxy=False):
change_dir()
c.run("docker-compose exec openresty supervisorctl restart all")
if proxy:
c.run("docker-compose exec proxy-server supervisorctl restart all")
@task
def log(c, all=False, proxy=False, tail=100):
change_dir()
if all:
services = ''
elif proxy:
services = 'proxy-server'
else:
services = 'openresty'
c.run(f'docker-compose logs -f --tail {tail} {services}')
@task
def modsec_log_level(c, level):
change_dir()
level = int(level)
if level < 1 or level > 9:
debug("Invalid level")
return
debug(f"Change modsecurity log level to {level}")
replace_file_regex("./openresty/modsecurity/modsecurity.conf",
'SecDebugLogLevel \\d', f'SecDebugLogLevel {level}')
c.run("docker-compose exec openresty nginx -s reload")
@task
def modsec_rebuild(c):
change_dir()
bash_cmd = 'cd /opt/modsecurity && make -j4 && make install && supervisorctl restart all'
c.run("docker-compose exec openresty bash -c '{}'".format(bash_cmd))
@task(iterable=['domains'])
def gen_ssl(c, domains=[]):
change_dir()
if len(domains) < 1:
domains = [
'google.com',
'*.google.com',
'messenger.com',
'*.messenger.com',
'facebook.com',
'*.facebook.com',
'youtube.com',
'*.youtube.com',
'github.com',
'*.github.com',
'hcmut.edu.vn',
'*.hcmut.edu.vn',
'vzota.com.vn',
'*.vzota.com.vn',
'overleaf.com',
'*.overleaf.com',
'discord.com',
'*.discord.com'
]
c.run('mkcert -cert-file ./openresty/nginx/ssl/localhost.pem -key-file ./openresty/nginx/ssl/localhost-key.pem ' + ' '.join(domains))
c.run('docker-compose exec openresty nginx -s reload')
@task
def test(c, url='https://ntsec.cf', attack=False):
if not attack:
c.run(
f'http_proxy=http://localhost:3004 https_proxy=http://localhost:3004 curl -ik -L {url}')
else:
c.run('http_proxy=http://localhost:3004 curl -ik -v http://ntsec.cf?x=' +
quote_plus('; cat /etc/passwd'))
def waf_mode_update(c, mode):
'''
Update current WAF mode
'''
change_dir()
mode = mode.upper()
support_modes = ['LEARNING_ATTACK', 'LEARNING_NORMAL',
'LEARNING_UNKNOWN', 'PRODUCTION']
if mode not in support_modes:
print("Error: waf mode must be in " + ', '.join(support_modes))
return
debug("Change waf mode to " + mode)
replace_file_regex("./openresty/modsecurity-crs/custom-rules.conf",
'setvar:TX.WAF_MODE=[\\w_]+\\b', f'setvar:TX.WAF_MODE={mode}')
reload(c)
waf_mode(c)
def waf_mode(c):
'''
Show current WAF mode
'''
change_dir()
waf_mode = grep_file_regex(
"./openresty/modsecurity-crs/custom-rules.conf", "setvar:TX.WAF_MODE=([\\w_]+)\\b").group(1)
debug(f"Current waf mode is {waf_mode}")
return waf_mode
@task
def csic_transform(c):
'''
Transform CSIC 2010 dataset by passing it to openresty WAF
Automatically change collection prefix to csic and revert back
'''
old_config = config(c)
pprint(old_config)
change_dir('./tools/gen-traffic')
try:
c.run('MAX_BUFFER_SIZE=10 node run.js csic-transform http://nginx.test -vv')
except:
print("\n")
debug("Interrupted")
finally:
config_update(c, prefix=old_config["prefix"], mode=old_config["mode"])
@task
def ecml_transform(c):
'''
Transform ECML PKDD dataset by passing it to openresty WAF
Automatically change collection prefix to ecml_pkdd and revert back
'''
old_config = config(c)
pprint(old_config)
change_dir('./tools/gen-traffic')
try:
c.run('MAX_BUFFER_SIZE=50 node run.js ecml-transform http://nginx.test -vv')
except:
print("\n")
debug("Interrupted")
finally:
config_update(c, prefix=old_config["prefix"], mode=old_config["mode"])
def update_prefix(c, prefix):
change_dir()
debug(f"Change collection prefix to '{prefix}'")
replace_file_regex('.env', "COLLECTION_PREFIX=.*",
f"COLLECTION_PREFIX={prefix}")
up(c)
get_prefix(c)
def get_prefix(c):
change_dir()
prefix = grep_file_regex(".env", "COLLECTION_PREFIX=(.*)").group(1)
debug(f"Current collection prefix is '{prefix}'")
return prefix
@task
def config_update(c, prefix='', mode='learning_normal'):
'''
Update WAF config
'''
update_prefix(c, prefix)
waf_mode_update(c, mode)
@task
def config(c):
'''
Get WAF config
'''
prefix = get_prefix(c)
mode = waf_mode(c)
debug('Current DNS config')
c.run("cat /etc/dnsmasq.d/docker-config.conf")
return {
"prefix": prefix,
"mode": mode
}
def debug(*msg):
print('[+]', *msg)
@task
def ml_rebuild(c):
'''
Rebuild ML model and restart WAF
'''
change_dir()
c.run("docker-compose exec openresty bash -c 'cd /opt/modsecurity-crs/lua-scripts/ml-model && make'")
restart(c)
@task(help={
'name': 'decision_tree | random_forest'
})
def ml_update(c):
'''
Copy new model code and rebuild
'''
change_dir()
from tools.ml_util.export_model import export_all
export_all()
for name in ['decision_tree', 'random_forest']:
debug(f"Update model {name}")
try:
with open(f"./tools/ml_util/output/{name}.c", "r") as fd:
model_C_code = fd.read()
output_C_code = f'''
{model_C_code}
#define N_FEAFURES 159
#define STR_INDIR(s) #s
#define STR(s) STR_INDIR(s)
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_predict(lua_State *L) {{
int nargs = lua_gettop(L);
if (nargs < 1) {{
lua_pushstring(L, "Missing positional argument: features (table)");
lua_error(L);
}}
// ignore other arguments
lua_settop(L, 1);
luaL_checktype(L, 1, LUA_TTABLE);
int input_table_length = lua_objlen(L, 1);
// printf("Input features: %d\\n", input_table_length);
if (input_table_length != N_FEAFURES) {{
lua_pushstring(L, "Wrong number of features (required " STR(N_FEAFURES) " features)");
lua_error(L);
}}
float features[N_FEAFURES];
int i = 0;
lua_pushnil(L);
while (lua_next(L, 1) != 0) {{
features[i++] = luaL_checknumber(L, -1);
lua_pop(L, 1);
}}
int result = predict(features);
lua_pushnumber(L, result);
return 1;
}}
static const struct luaL_reg funcs[] = {{
{{ "predict", l_predict }},
{{ NULL, NULL }}
}};
int luaopen_{name}(lua_State *L) {{
luaL_register(L, "{name}", funcs);
return 0;
}}
'''
with open(f"./openresty/modsecurity-crs/lua-scripts/ml-model/{name}.c", "w+") as fd:
fd.write(output_C_code)
except Exception as e:
debug("Failed to update model")
debug(e)
ml_rebuild(c)
@task
def pull_drive(c):
change_dir("ml-model")
c.run("rclone copy drive:/project/waf/train.ipynb .")
c.run("rclone copy drive:/project/waf/saved-models ./saved-models")
c.run("rclone copy drive:/project/waf/images ./images")