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
|
local detector = require('waf.detector')
local analyzer = require('waf.analyzer')
local filter = require('waf.filter')
local limits = require('waf.limits')
local config = require('waf.config')
local ban = require('waf.ban')
local log = require('utils.log')
local duration = config.duration
local valid_ips = config.ips
local ban_add = ban.add
local ban_check = ban.check
local headers
local meta
local client_ip = ngx.var.remote_addr
local function answer(reason_module, level)
if not reason_module then return ngx.exit(444) end
local ray_id = string.sub(ngx.md5(ngx.time() .. client_ip), 1, 16)
ngx.header['X-WAF-Ray-ID'] = ray_id
ngx.header['X-WAF-Block-Module'] = reason_module or 'system'
ngx.header['X-WAF-Client-IP'] = client_ip
log.warn('🚨 WAF BLOCK: IP ' .. client_ip .. ' | RayID: ' .. ray_id .. ' | Модуль: ' .. (reason_module or 'unknown'))
return ngx.exit(403)
end
local function valid(ip)
for k=1,#valid_ips do
if valid_ips[k] == ip then return end
end
return false
end
log.name = 'waf'
log.level = 'trace'
if valid(client_ip) then return true end
if ban_check(client_ip) then return ngx.exit(444) end
if ngx.var.is_bot == '1' then return answer('bot_map') end
if not detector then
log.error('Не найден детектор')
else
headers = ngx.req.get_headers()
meta = {
method = ngx.var.request_method,
uri = ngx.var.uri
}
local res,level = detector.check(headers,meta)
if not res then
ban_add(client_ip, duration/level)
if level==1 then return answer('detector') end
end
end
if not limits then
log.error('Не найден лимитизатор')
else
local res,level = limits.check(meta,client_ip)
if not res then
ban_add(client_ip, duration/level)
if level==1 then return answer('rate_limiting') end
end
end
if not analyzer then
log.error('Не найден анализатор')
else
local res,level = analyzer.check()
if not res then
ban_add(client_ip, duration/level)
if level==1 then return answer('uri_analyzer') end
end
end
if not filter then
log.error('Не найден фильтр')
else
local res = filter.check()
if not res then
ban_add(client_ip, duration)
return answer('body_filter')
end
end
|