-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathinit.lua
495 lines (449 loc) · 14.2 KB
/
init.lua
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
require 'config'
require 'country_check'
local b64 = require 'ngx.base64'
local match = string.match
local ngxmatch=ngx.re.match
local unescape=ngx.unescape_uri
local get_headers = ngx.req.get_headers
local optionIsOn = function (options) return options == "on" and true or false end
logpath = logdir
rulepath = RulePath
UrlDeny = optionIsOn(UrlDeny)
PostCheck = optionIsOn(PostMatch)
CookieCheck = optionIsOn(CookieMatch)
WhiteCheck = optionIsOn(whiteModule)
WhiteHostCheck = optionIsOn(whiteHostModule)
PathInfoFix = optionIsOn(PathInfoFix)
attacklog = optionIsOn(attacklog)
CCDeny = optionIsOn(CCDeny)
Redirect = optionIsOn(Redirect)
CountryLimit = optionIsOn(CountryLimit)
FileContentCheck = optionIsOn(FileContentCheck)
--验证码
function WafCaptcha()
html_file = io.open("waf_captcha/waf-captcha.html","r")
html_v = html_file:read("*a")
say_html(html_v)
end
--获取客户端IP,支持代理
function getClientIp()
local headers = ngx.req.get_headers()
local reip = headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr
if reip == nil then
local reip = "unknown"
end
--检查返回的IP是否是多个值,如果是,只取最后一个
if string.find(reip, ',') then
local table_ip = split(reip,",")
local table_len = table.getn(table_ip)
local reip = table_ip[table_len]
end
return reip
end
function write(logfile,msg)
local fd = io.open(logfile,"ab")
if fd == nil then return end
fd:write(msg)
fd:flush()
fd:close()
end
function log(data,ruletag)
local request_method = ngx.req.get_method()
local url = ngx.var.request_uri
if attacklog then
local realIp = getClientIp()
local ua = ngx.var.http_user_agent
--local servername=ngx.var.server_name
local servername=ngx.var.host
local time=ngx.localtime()
local filename = logpath..'/'..servername.."_"..ngx.today().."_sec.log"
if ua then
local line = realIp.." ["..time.."] \""..request_method.." "..servername..url.."\" \""..data.."\" \""..ua.."\" \""..ruletag.."\"\n"
write(filename,line)
else
local line = realIp.." ["..time.."] \""..request_method.." "..servername..url.."\" \""..data.."\" - \""..ruletag.."\"\n"
write(filename,line)
end
end
end
--记录上传的文件
function Filelog(logfilename,fn,finfo)
local request_method = ngx.req.get_method()
local url = ngx.var.request_uri
if attacklog then
local realIp = getClientIp()
local ua = ngx.var.http_user_agent
--local servername=ngx.var.server_name
local servername=ngx.var.host
local time=ngx.localtime()
local filename = logpath..'/'..servername.."_"..ngx.today().."_"..logfilename..".log"
if ua then
local line = realIp.." ["..time.."] \""..request_method.." "..servername..url.."\" \""..fn.."\" \""..ua.."\" \""..finfo.."\"\n"
write(filename,line)
else
local line = realIp.." ["..time.."] \""..request_method.." "..servername..url.."\" \""..fn.."\" - \""..finfo.."\"\n"
write(filename,line)
end
end
end
function ipToDecimal(ckip)
local n = 4
local decimalNum = 0
local pos = 0
for s, e in function() return string.find(ckip, '.', pos, true) end do
n = n - 1
decimalNum = decimalNum + string.sub(ckip, pos, s-1) * (256 ^ n)
pos = e + 1
if n == 1 then decimalNum = decimalNum + string.sub(ckip, pos, string.len(ckip)) end
end
return decimalNum
end
------------------------------------规则读取函数-------------------------------------------------------------------
function read_rule(var)
file = io.open(rulepath..'/'..var,"r")
if file==nil then
return
end
t = {}
for line in file:lines() do
table.insert(t,line)
end
file:close()
return(t)
end
urlrules=read_rule('url')
argsrules=read_rule('args')
uarules=read_rule('user-agent')
whiteuarules=read_rule('white-user-agent')
wturlrules=read_rule('whiteurl')
postrules=read_rule('post')
ckrules=read_rule('cookie')
function say_html(v)
if not v then
if Redirect then
ngx.header.content_type = "text/html; charset=UTF-8"
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say(html)
ngx.exit(ngx.status)
end
else
ngx.header.content_type = "text/html; charset=UTF-8"
ngx.status = ngx.HTTP_FORBIDDEN
ngx.say(say2_html(string.format(html,v)))
ngx.exit(ngx.status)
end
end
function say2_html(var)
return var
end
function whiteurl()
if WhiteCheck then
if wturlrules ~=nil then
for _,rule in pairs(wturlrules) do
if ngxmatch(ngx.var.request_uri,rule,"isjo") then
return true
end
end
end
end
return false
end
function whitehost()
if WhiteHostCheck then
local items = Set(hostWhiteList)
for host in pairs(items) do
if ngxmatch(ngx.var.host, host, "isjo") then
log("-","white host: ".. host)
return true
end
end
end
return false
end
function args()
for _,rule in pairs(argsrules) do
if ngxmatch(unescape(ngx.var.request_uri),rule,"isjo") then
log("-",rule)
say_html("URL请求异常")
return true
end
local args = ngx.req.get_uri_args()
for key, val in pairs(args) do
if type(val)=='table' then
local t={}
for k,v in pairs(val) do
if v == true then
v=""
end
table.insert(t,v)
end
data=table.concat(t, " ")
else
data=val
end
if data and type(data) ~= "boolean" and rule ~="" and ngxmatch(unescape(data),rule,"isjo") then
log("-", "args in attack rules: " .. rule .. " data: " .. tostring(data))
say_html("URL参数异常")
return true
end
end
end
return false
end
function url()
if UrlDeny then
for _,rule in pairs(urlrules) do
if rule ~="" and ngxmatch(ngx.var.request_uri,rule,"isjo") then
log("-", "url in attack rules: " .. rule)
say_html("URL拦截命中")
return true
end
end
end
return false
end
function ua()
local ua = ngx.var.http_user_agent
if ua ~= nil then
for _,rule in pairs(uarules) do
if rule ~="" and ngxmatch(ua,rule,"isjo") then
log("-", "ua in attack rules: " .. rule)
say_html("UA拦截命中")
return true
end
end
end
return false
end
--body内容检查
function body(data)
if not FileContentCheck then
return false
end
for _,rule in pairs(postrules) do
if rule ~="" and data~="" and ngxmatch(unescape(data),rule,"isjo") then
log(data,rule)
say_html("Body POST拦截命中")
return true
end
end
return false
end
function cookie()
local ck = ngx.var.http_cookie
if CookieCheck and ck then
for _,rule in pairs(ckrules) do
if rule ~="" and ngxmatch(ck,rule,"isjo") then
log("-", "cookie in attack rules: " .. rule)
say_html("Cookie异常,疑似攻击")
return true
end
end
end
return false
end
--[[
@comment cc攻击匹配
@param
@return
]]
function denycc()
if CCDeny then
--local uri = ngx.var.uri
--改用request_uri,并且进行base64,以防特殊符号出问题。解决使用URL传参导致触发CC异常
--base64url是Base64编码的一种改进形式,它用“-”和“_”替代了“+”和“/”,编码后长度不是4的倍数时也不使用“=”填补,可以安全地用在URL 里。
local uri = b64.encode_base64url(tostring(ngx.var.request_uri))
local CCcount = tonumber(string.match(urlCCrate, "(.*)/"))
local CCseconds = tonumber(string.match(urlCCrate, "/(.*)"))
local ipCCcount = tonumber(string.match(ipCCrate, "(.*)/"))
local ipCCseconds = tonumber(string.match(ipCCrate, "/(.*)"))
local now_ip = getClientIp()
local token = now_ip .. '.' ..uri
local urllimit = ngx.shared.urllimit
local iplimit = ngx.shared.iplimit
local req, _ = urllimit:get(token)
local ipreq, _ = iplimit:get(now_ip)
if req then -- ip访问url频次检测
if req > CCcount then
log("-", "IP get url over times. ")
say_html("IpURL频繁访问限制,请稍后再试")
-- say_html(token)
return true
else
urllimit:incr(token, 1)
end
else
urllimit:set(token, 1, CCseconds)
end
if ipreq then -- 访问ip频次检测
if ipreq > ipCCcount then
log("-", "IP get host over times. ")
say_html("IP频繁访问限制,请稍后再试")
return true
else
iplimit:incr(now_ip, 1)
end
else
iplimit:set(now_ip, 1, ipCCseconds)
end
end
return false
end
function whiteua()
local ua = ngx.var.http_user_agent
if ua ~= nil then
for _,rule in pairs(whiteuarules) do
if rule ~="" and ngxmatch(ua,rule,"isjo") then
return true
end
end
end
return false
end
function get_boundary()
local header = get_headers()["content-type"]
if not header then
return nil
end
if type(header) == "table" then
header = header[1]
end
local m = match(header, ";%s*boundary=\"([^\"]+)\"")
if m then
return m
end
return match(header, ";%s*boundary=([^\",;]+)")
end
--数字转换为八位二进制
function byte2bin(n)
local t = {}
for i=7,0,-1 do
t[#t+1] = math.floor(n / 2^i)
n = n % 2^i
end
return table.concat(t)
end
--拼接IP每部分的二进制,返回IP完整的二进制
function IP2bin(ip_s)
local IP_p1,IP_p2,IP_p3,IP_p4=string.match(ip_s, "(%d+).(%d+).(%d+).(%d+)")
ip_str = byte2bin(IP_p1)..byte2bin(IP_p2)..byte2bin(IP_p3)..byte2bin(IP_p4)
return ip_str
end
--判断二进制IP是否在属于某网段
function IpBelongToNetwork(bin_ip,bin_network,mask)
if (string.sub(bin_ip,1,mask) == string.sub(bin_network,1,mask)) then
return true
else
return false
end
end
--字符串分割函数
function split(str,delimiter)
local dLen = string.len(delimiter)
local newDeli = ''
for i=1,dLen,1 do
newDeli = newDeli .. "["..string.sub(delimiter,i,i).."]"
end
local locaStart,locaEnd = string.find(str,newDeli)
local arr = {}
local n = 1
while locaStart ~= nil
do
if locaStart>0 then
arr[n] = string.sub(str,1,locaStart-1)
n = n + 1
end
str = string.sub(str,locaEnd+1,string.len(str))
locaStart,locaEnd = string.find(str,newDeli)
end
if str ~= nil then
arr[n] = str
end
return arr
end
function blockip()
if next(ipBlocklist) ~= nil then
local cIP = getClientIp()
local numIP = 0
if cIP ~= "unknown" then
numIP = tonumber(ipToDecimal(cIP))
end
for _,ip in pairs(ipBlocklist) do
local s, e = string.find(ip, '-', 0, true)
local x, j = string.find(ip, '/', 0, true)
--IP字符串中不存在"-"、"/"等划分网段标识
if s == nil and x == nil and cIP == ip then
ngx.exit(403)
return true
--范围划分法
elseif s ~= nil then
sIP = tonumber(ipToDecimal(string.sub(ip, 0, s - 1)))
eIP = tonumber(ipToDecimal(string.sub(ip, e + 1, string.len(ip))))
if numIP >= sIP and numIP <= eIP then
ngx.exit(403)
return true
end
--掩码划分法
elseif x ~= nil then
local ip_list = split(ip, "/")
if IpBelongToNetwork(IP2bin(cIP),IP2bin(ip_list[1]),ip_list[2]) then
ngx.exit(403)
return true
end
end
end
end
return false
end
--上传文件白名单后缀检查
function fileExtCheck(ext,fn,finfo)
local items = Set(white_fileExt)
local ext = string.lower(ext)
if ext then
for rule in pairs(items) do
if string.lower(rule) == ext then
Filelog('UploadFile',fn,finfo)
return true
end
end
Filelog('UploadFileFailed',fn,finfo)
say_html('该类型文件不允许上传:'..ext)
end
return false
end
function Set (list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
function whiteip()
if next(ipWhitelist) ~= nil then
local cIP = getClientIp()
local numIP = 0
if cIP ~= "unknown" then
numIP = tonumber(ipToDecimal(cIP))
end
for _,ip in pairs(ipWhitelist) do
local s, e = string.find(ip, '-', 0, true)
local x, j = string.find(ip, '/', 0, true)
--IP字符串中不存在"-"、"/"等划分网段标识
if s == nil and x == nil and cIP == ip then
return true
--范围划分法
elseif s ~= nil then
sIP = tonumber(ipToDecimal(string.sub(ip, 0, s - 1)))
eIP = tonumber(ipToDecimal(string.sub(ip, e + 1, string.len(ip))))
if numIP >= sIP and numIP <= eIP then
return true
end
--掩码划分法
elseif x ~= nil then
local ip_list = split(ip, "/")
if IpBelongToNetwork(IP2bin(cIP),IP2bin(ip_list[1]),ip_list[2]) then
return true
end
end
end
end
return false
end