-
Notifications
You must be signed in to change notification settings - Fork 11
/
guard_dynamic.lua
1652 lines (1514 loc) · 84 KB
/
guard_dynamic.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local Guard = {}
--debug日志
function Guard:debug(data, ip, reqUri)
local isOn = _Conf.dict_system:get("debug_state")
if isOn then
local date = os.date("%Y-%m-%d")
local filename = _Conf.logPath .. "/debug-" .. date .. ".log"
local file = io.open(filename, "a+")
file:write(os.date('%Y-%m-%d %H:%M:%S') .. " [DEBUG] " .. data .. " IP " .. ip .. " GET " .. reqUri .. "\n")
file:close()
end
end
--攻击日志
function Guard:log(data)
local date = os.date("%Y-%m-%d")
local filename = _Conf.logPath .. "/attack-" .. date .. ".log"
local file = io.open(filename, "a+")
file:write(os.date('%Y-%m-%d %H:%M:%S') .. " [WARNING] " .. data .. "\n")
file:close()
end
--获取真实ip
function Guard:getRealIp(remoteIp, headers)
if _Conf.realIpFromHeaderIsOn then
realIp = headers[_Conf.realIpFromHeader.header]
if realIp then
--self:debug(type(realIp).."[==========>] realIpFromHeader is on.return ip "..realIp,remoteIp,"")
--realIp 类型一般为 string
if type(realIp) == "table" then
realIp = realIp[1]
end
--X-Forwarded-For:用户IP, 代理服务器1-IP, 代理服务器2-IP, 代理服务器3-IP, ……
--获取用户IP
local regex = [[\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}]]
--local regex = "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"
local m = ngx.re.match(realIp, regex, "ijo") or false
if m then
realIp = m[0]
else
--get realIp fail, set default ip 0.0.0.7
realIp = "0.0.0.7"
end
--self:debug(realIp.."[==========>] realIpFromHeader is on.return ip "..realIp,remoteIp,"")
self:debug("[getRealIp] realIpFromHeader is on.return ip " .. realIp, remoteIp, "")
return realIp
else
return remoteIp
end
else
return remoteIp
end
end
--byWhite白名单模块
function Guard:ipInByWhiteList(ip)
local isOn = _Conf.dict_system:get("byWhiteIpModules_state")
if isOn then
--判断是否开启白名单模块
--self:debug("[ipInByWhiteList] byWhiteIpModules is on.",ip,"")
if _Conf.dict_byWhiteIp:get(ip) then
self:debug("[ipInByWhiteList] ip " .. ip .. " in byWhite list", ip, "")
return true
else
return false
end
end
return false
end
--byDeny黑名单模块
function Guard:ipInByDenyList(ip)
local isOn = _Conf.dict_system:get("byDenyIpModules_state")
if isOn then
--判断是否开启 byDeny 黑名单模块
--self:debug("[ipInByDenyList] byDenyIpModules is on.",ip,"")
if _Conf.dict_byDenyIp:get(ip) then
self:debug("[ipInByDenyList] ip " .. ip .. " in byDeny list ", ip, "")
return true
else
return false
end
end
return false
end
--黑名单模块
function Guard:blackListModules(ip, reqUri, address, userAgent, httpReferer)
local blackKey = ip .. "black"
if _Conf.dict_black:get(blackKey) then
--判断ip是否存在黑名单字典
self:debug("[blackListModules] ip " .. ip .. " in blacklist", ip, reqUri)
self:takeAction(ip, reqUri, address, userAgent, httpReferer) --存在则执行相应动作
end
end
--限制请求速率模块
function Guard:limitReqModules(ip, reqUri, address, limitModule)
local isOn = _Conf.dict_system:get("limitReqModules_state")
if (isOn and not (limitModule == "off")) or (limitModule == "on") then
local maxReqs = _Conf.dict_system:get("limitReqModules_maxReqs")
local limitUrlProtect = _Conf.dict_system:get("limitUrlProtect")
if ngx.re.match(address, limitUrlProtect, "i") then
self:debug("[limitReqModules] address " .. address .. " match reg " .. limitUrlProtect, ip, reqUri)
local blackKey = ip .. "black"
local limitReqKey = ip .. "limitreqkey" --定义limitreq key
local reqTimes = _Conf.dict_challenge:get(limitReqKey) --获取此ip请求的次数
--增加一次请求记录
if reqTimes then
_Conf.dict_challenge:incr(limitReqKey, 1)
else
local amongTime = _Conf.dict_system:get("limitReqModules_amongTime")
_Conf.dict_challenge:set(limitReqKey, 1, amongTime)
reqTimes = 0
end
local newReqTimes = reqTimes + 1
self:debug("[limitReqModules] newReqTimes " .. newReqTimes, ip, reqUri)
--判断请求数是否大于阀值,大于则添加黑名单
if newReqTimes > maxReqs then
--判断是否请求数大于阀值
self:debug("[limitReqModules] ip " .. ip .. " request exceed " .. maxReqs, ip, reqUri)
local blockTime = _Conf.dict_system:get("blockTime")
if _Conf.limitReqModules.action == 1 then
--添加此ip到黑名单
local blackKey = ip .. "black"
_Conf.dict_black:set(blackKey, 0, blockTime)
self:log("[limitReqModules] IP " .. ip .. " request " .. newReqTimes .. " times, add it to black list")
elseif _Conf.limitReqModules.action == 2 then
--添加此ip到needVerify列表
_Conf.dict_needVerify:set(ip, "limitReqModules", blockTime)
self:log("[limitReqModules] IP " .. ip .. " request " .. newReqTimes .. " times, add it to needVerify list")
elseif _Conf.limitReqModules.action == 3 then
--添加此ip到byDenyIp列表
_Conf.dict_byDenyIp:set(ip, "limitReqModules", blockTime)
self:log("[limitReqModules] IP " .. ip .. " request " .. newReqTimes .. " times, add it to byDenyIp list")
end
end
end
end
end
--302转向模块
function Guard:redirectModules(ip, reqUri, address)
local redirectUrlProtect = _Conf.dict_system:get("redirectUrlProtect")
if ngx.re.match(address, redirectUrlProtect, "ijo") then
self:debug("[redirectModules] address " .. address .. " match reg " .. redirectUrlProtect, ip, reqUri)
local whiteTime = _Conf.dict_system:get("whiteTime")
local blockTime = _Conf.dict_system:get("blockTime")
local keyExpire = _Conf.dict_system:get("keyExpire")
local verifyMaxFail = _Conf.dict_system:get("redirectModules_verifyMaxFail")
local amongTime = _Conf.dict_system:get("redirectModules_amongTime")
local whiteKey = ip .. "white302"
local inWhiteList = _Conf.dict_white:get(whiteKey)
if inWhiteList then
--如果在白名单
self:debug("[redirectModules] in white ip list", ip, reqUri)
return
else
--如果不在白名单,再检测是否有cookie凭证
local now = ngx.time() --当前时间戳
local challengeTimesKey = table.concat({ ip, "challenge302" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
local blackKey = ip .. "black"
local cookie_key = ngx.var["cookie_key302"] --获取cookie密钥
local cookie_expire = ngx.var["cookie_expire302"] --获取cookie密钥过期时间
if cookie_key and cookie_expire then
local key_make = ngx.md5(table.concat({ ip, _Conf.redirectModules.keySecret, cookie_expire }))
local key_make = string.sub(key_make, "1", "10")
--判断cookie是否有效
if tonumber(cookie_expire) > now and cookie_key == key_make then
self:debug("[redirectModules] cookie key is valid.", ip, reqUri)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除验证失败计数器
end
_Conf.dict_white:set(whiteKey, 0, whiteTime) --添加到白名单
if _Conf.dict_black:get(blackKey) then
--如果黑名单中有该IP, 则删除
_Conf.dict_black:delete(blackKey)
end
return
else
self:debug("[redirectModules] cookie key is invalid.", ip, reqUri)
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.redirectModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?key302=[^&]+&?|expire302=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?key302=", key_new, "&expire302=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&key302=", key_new, "&expire302=", expire })
end
else
newUrl = table.concat({ reqUri, "?key302=", key_new, "&expire302=", expire })
end
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[redirectModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[redirectModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
--删除cookie
ngx.header['Set-Cookie'] = { "key302=; path=/", "expire302=; expires=Sat, 01-Jan-2000 00:00:00 GMT; path=/" }
return ngx.redirect(newUrl, 302) --发送302转向
end
else
--如果没有找到cookie,则检测是否带cckey参数
local ccKeyValue = ngx.re.match(reqUri, "key302=([^&]+)", "i")
local expire = ngx.re.match(reqUri, "expire302=([^&]+)", "i")
if ccKeyValue and expire then
--是否有cckey和keyexpire参数
local ccKeyValue = ccKeyValue[1]
local expire = expire[1]
local key_make = ngx.md5(table.concat({ ip, _Conf.redirectModules.keySecret, expire }))
local key_make = string.sub(key_make, "1", "10")
self:debug("[redirectModules] ccKeyValue " .. ccKeyValue, ip, reqUri)
self:debug("[redirectModules] expire " .. expire, ip, reqUri)
self:debug("[redirectModules] key_make " .. key_make, ip, reqUri)
self:debug("[redirectModules] ccKeyValue " .. ccKeyValue, ip, reqUri)
if key_make == ccKeyValue and now < tonumber(expire) then
--判断传过来的cckey参数值是否等于字典记录的值,且没有过期
self:debug("[redirectModules] ip " .. ip .. " arg key302 " .. ccKeyValue .. " is valid.add ip to write list.", ip, reqUri)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除验证失败计数器
end
_Conf.dict_white:set(whiteKey, 0, whiteTime) --添加到白名单
if _Conf.dict_black:get(blackKey) then
--如果黑名单中有该IP, 则删除
_Conf.dict_black:delete(blackKey)
end
ngx.header['Set-Cookie'] = { "key302=" .. key_make .. "; path=/", "expire302=" .. expire .. "; path=/" } --发送cookie凭证
return
else
--如果不相等,则再发送302转向
self:debug("[redirectModules] ip " .. ip .. " arg key302 is invalid.", ip, reqUri)
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.redirectModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[redirectModules] client " .. ip .. " challenge 302key failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[redirectModules] client " .. ip .. " challenge 302key failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?key302=[^&]+&?|expire302=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?key302=", key_new, "&expire302=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&key302=", key_new, "&expire302=", expire })
end
else
newUrl = table.concat({ reqUri, "?key302=", key_new, "&expire302=", expire })
end
return ngx.redirect(newUrl, 302) --发送302转向
end
else
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[redirectModules] client " .. ip .. " challenge 302key failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[redirectModules] client " .. ip .. " challenge 302key failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.redirectModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?key302=[^&]+&?|expire302=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?key302=", key_new, "&expire302=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&key302=", key_new, "&expire302=", expire })
end
else
newUrl = table.concat({ reqUri, "?key302=", key_new, "&expire302=", expire })
end
return ngx.redirect(newUrl, 302) --发送302转向
end
end
end
end
end
--js跳转模块
function Guard:JsJumpModules(ip, reqUri, address)
local JsJumpUrlProtect = _Conf.dict_system:get("JsJumpUrlProtect")
if ngx.re.match(address, JsJumpUrlProtect, "ijo") then
self:debug("[JsJumpModules] address " .. address .. " match reg " .. JsJumpUrlProtect, ip, reqUri)
local whiteTime = _Conf.dict_system:get("whiteTime")
local blockTime = _Conf.dict_system:get("blockTime")
local keyExpire = _Conf.dict_system:get("keyExpire")
local verifyMaxFail = _Conf.dict_system:get("JsJumpModules_verifyMaxFail")
local amongTime = _Conf.dict_system:get("JsJumpModules_amongTime")
local whiteKey = ip .. "whitejs"
local inWhiteList = _Conf.dict_white:get(whiteKey)
if inWhiteList then
--如果在白名单
self:debug("[JsJumpModules] in white ip list", ip, reqUri)
return
else
--如果不在白名单,检测是否有cookie凭证
local cookie_key = ngx.var["cookie_keyjs"] --获取cookie密钥
local cookie_expire = ngx.var["cookie_expirejs"] --获取cookie密钥过期时间
local now = ngx.time() --当前时间戳
local challengeTimesKey = table.concat({ ip, "challengejs" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
local blackKey = ip .. "black"
local cookie_key = ngx.var["cookie_keyjs"] --获取cookie密钥
local cookie_expire = ngx.var["cookie_expirejs"] --获取cookie密钥过期时间
if cookie_key and cookie_expire then
local key_make = ngx.md5(table.concat({ ip, _Conf.JsJumpModules.keySecret, cookie_expire }))
local key_make = string.sub(key_make, "1", "10")
if tonumber(cookie_expire) > now and cookie_key == key_make then
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除验证失败计数器
end
self:debug("[JsJumpModules] cookie key is valid.", ip, reqUri)
_Conf.dict_white:set(whiteKey, 0, whiteTime) --添加ip到白名单
if _Conf.dict_black:get(blackKey) then
--如果黑名单中有该IP, 则删除
_Conf.dict_black:delete(blackKey)
end
return
else
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[JsJumpModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[JsJumpModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
self:debug("[JsJumpModules] cookie key is invalid.", ip, reqUri)
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.JsJumpModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?keyjs=[^&]+&?|expirejs=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?keyjs=", key_new, "&expirejs=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&keyjs=", key_new, "&expirejs=", expire })
end
else
newUrl = table.concat({ reqUri, "?keyjs=", key_new, "&expirejs=", expire })
end
local jsJumpCode = table.concat({ "<script>window.location.href='", newUrl, "';</script>" }) --定义js跳转代码
ngx.header.content_type = "text/html"
--删除cookie
ngx.header['Set-Cookie'] = { "keyjs=; path=/", "expirejs=; expires=Sat, 01-Jan-2000 00:00:00 GMT; path=/" }
ngx.print(jsJumpCode)
ngx.exit(200)
end
else
--如果没有cookie凭证,检测url是否带有cckey参数
local ccKeyValue = ngx.re.match(reqUri, "keyjs=([^&]+)", "i")
local expire = ngx.re.match(reqUri, "expirejs=([^&]+)", "i")
if ccKeyValue and expire then
local ccKeyValue = ccKeyValue[1]
local expire = expire[1]
local key_make = ngx.md5(table.concat({ ip, _Conf.JsJumpModules.keySecret, expire }))
local key_make = string.sub(key_make, "1", "10")
if key_make == ccKeyValue and now < tonumber(expire) then
--判断传过来的cckey参数值是否等于字典记录的值,且没有过期
self:debug("[JsJumpModules] ip " .. ip .. " arg keyjs " .. ccKeyValue .. " is valid.add ip to white list.", ip, reqUri)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除验证失败计数器
end
_Conf.dict_white:set(whiteKey, 0, whiteTime) --添加ip到白名单
if _Conf.dict_black:get(blackKey) then
--如果黑名单中有该IP, 则删除
_Conf.dict_black:delete(blackKey)
end
ngx.header['Set-Cookie'] = { "keyjs=" .. key_make .. "; path=/", "expirejs=" .. expire .. "; path=/" } --发送cookie凭证
return
else
--如果不相等,则再发送302转向
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[JsJumpModules] client " .. ip .. " challenge jskey failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[JsJumpModules] client " .. ip .. " challenge jskey failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
self:debug("[JsJumpModules] ip " .. ip .. " arg keyjs is invalid.", ip, reqUri)
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.JsJumpModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?keyjs=[^&]+&?|expirejs=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?keyjs=", key_new, "&expirejs=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&keyjs=", key_new, "&expirejs=", expire })
end
else
newUrl = table.concat({ reqUri, "?keyjs=", key_new, "&expirejs=", expire })
end
local jsJumpCode = table.concat({ "<script>window.location.href='", newUrl, "';</script>" }) --定义js跳转代码
ngx.header.content_type = "text/html"
ngx.print(jsJumpCode)
ngx.exit(200)
end
else
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[JsJumpModules] client " .. ip .. " challenge jskey failed " .. challengeTimesValue .. " times,add to blacklist.", ip, reqUri)
self:log("[JsJumpModules] client " .. ip .. " challenge jskey failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
--定义转向的url
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.JsJumpModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
--定义转向的url
local newUrl = ''
local newReqUri = ngx.re.match(reqUri, "(.*?)\\?(.+)")
if newReqUri then
local reqUriNoneArgs = newReqUri[1]
local args = newReqUri[2]
--删除cckey和keyexpire
local newArgs = ngx.re.gsub(args, "[&?]?keyjs=[^&]+&?|expirejs=[^&]+&?", "", "i")
if newArgs == "" then
newUrl = table.concat({ reqUriNoneArgs, "?keyjs=", key_new, "&expirejs=", expire })
else
newUrl = table.concat({ reqUriNoneArgs, "?", newArgs, "&keyjs=", key_new, "&expirejs=", expire })
end
else
newUrl = table.concat({ reqUri, "?keyjs=", key_new, "&expirejs=", expire })
end
local jsJumpCode = table.concat({ "<script>window.location.href='", newUrl, "';</script>" }) --定义js跳转代码
ngx.header.content_type = "text/html"
ngx.print(jsJumpCode)
ngx.exit(200)
end
end
end
end
end
--cookie验证模块
function Guard:cookieModules(ip, reqUri, address, userAgent, httpReferer)
local cookieUrlProtect = _Conf.dict_system:get("cookieUrlProtect")
if ngx.re.match(address, cookieUrlProtect, "ijo") then
self:debug("[cookieModules] address " .. address .. " match reg " .. cookieUrlProtect .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
local whiteTime = _Conf.dict_system:get("whiteTime")
local blockTime = _Conf.dict_system:get("blockTime")
local keyExpire = _Conf.dict_system:get("keyExpire")
local verifyMaxFail = _Conf.dict_system:get("cookieModules_verifyMaxFail")
local amongTime = _Conf.dict_system:get("cookieModules_amongTime")
local whiteKey = ip .. "whitecookie"
local inWhiteList = _Conf.dict_white:get(whiteKey)
if inWhiteList then
--如果在白名单
self:debug("[cookieModules] in white ip list." .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
return
else
local cookie_key = ngx.var["cookie_keycookie"] --获取cookie密钥
local cookie_expire = ngx.var["cookie_expirecookie"] --获取cookie密钥过期时间
local now = ngx.time() --当前时间戳
local challengeTimesKey = table.concat({ ip, "challengecookie" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
local blackKey = ip .. "black"
if cookie_key and cookie_expire then
--判断是否有收到cookie
local key_make = ngx.md5(table.concat({ ip, _Conf.cookieModules.keySecret, cookie_expire }))
local key_make = string.sub(key_make, "1", "10")
if tonumber(cookie_expire) > now and cookie_key == key_make then
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除验证失败计数器
end
self:debug("[cookieModules] cookie key is valid.add to white ip list" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
_Conf.dict_white:set(whiteKey, 0, whiteTime) --添加ip到白名单
if _Conf.dict_black:get(blackKey) then
--如果黑名单中有该IP, 则删除
_Conf.dict_black:delete(blackKey)
end
return
else
self:debug("[cookieModules] cookie key is invalid" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[cookieModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist." .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:log("[cookieModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
ngx.header['Set-Cookie'] = { "keycookie=; path=/", "expirecookie=; expires=Sat, 01-Jan-2000 00:00:00 GMT; path=/" } --删除cookie
end
else
--找不到cookie
self:debug("[cookieModules] cookie not found." .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
--验证失败次数加1
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
if challengeTimesValue + 1 > verifyMaxFail then
self:debug("[cookieModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist." .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:log("[cookieModules] client " .. ip .. " challenge cookie failed " .. challengeTimesValue .. " times,add to blacklist.")
_Conf.dict_black:set(blackKey, 0, blockTime) --添加此ip到黑名单
self:black2byDeny(ip, reqUri, address) --判断是否要添加该IP到byDenyIp名单
end
else
_Conf.dict_challenge:set(challengeTimesKey, 1, amongTime)
end
local expire = now + keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.cookieModules.keySecret, expire }))
local key_new = string.sub(key_new, "1", "10")
self:debug("[cookieModules] send cookie to client." .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
ngx.header['Set-Cookie'] = { "keycookie=" .. key_new .. "; path=/", "expirecookie=" .. expire .. "; path=/" } --发送cookie凭证
end
end
end
end
--获取验证码
function Guard:getCaptcha()
--local random = math.random(1,10000) --生成1-10000之间的随机数
local random = math.random(_Conf.randomInteger, (_Conf.randomInteger + 10000)) --生成一个随机数
self:debug("[getCaptcha] get random num " .. random, "", "")
local captchaValue = _Conf.dict_captcha:get(random) --取得字典中的验证码
self:debug("[getCaptcha] get captchaValue " .. captchaValue, "", "")
local captchaImg = _Conf.dict_captcha:get(captchaValue) --取得验证码对应的图片
--返回图片
ngx.status = 298
ngx.header.content_type = "image/jpeg"
ngx.header['Set-Cookie'] = table.concat({ "captchaNum=", random, "; path=/" })
ngx.header['Cache-Control'] = "no-cache"
ngx.print(captchaImg)
ngx.exit(298)
end
--验证验证码
function Guard:verifyCaptcha(ip, reqUri, address)
ngx.req.read_body()
local captchaNum = ngx.var["cookie_captchaNum"] or "NONE" --获取cookie captchaNum值
local preurl = ngx.var["cookie_preurl"] or "/" --获取上次访问url,如果为空则返回首页(返回首页是为了避免用户禁用了 Cookie 而导致无法获取上次访问的URL)
self:debug("[verifyCaptcha] get cookie captchaNum " .. captchaNum, ip, "")
local args = ngx.req.get_post_args() --获取post参数
local postValue = args["response"] or "postValue_NONE" --获取post value参数
postValue = string.lower(postValue)
self:debug("[verifyCaptcha] get post arg response " .. postValue, ip, "")
local captchaValue = _Conf.dict_captcha:get(captchaNum) or "captchaValue_NONE" --从字典获取post value对应的验证码值
--preurl(若上次访问的URL) 中含verify-captcha.do, 则preurl 截到 verify-captcha.do
if ngx.re.match(preurl, "verify-captcha.do", "i") then
local from, to, err = ngx.re.find(preurl, "verify-captcha.do", "i")
preurl = string.sub(preurl, 0, from - 1)
end
--preurl(若上次访问的URL为ico、js、css、图片等则返回preurl为首页)
if ngx.re.match(preurl, _Conf.preurlVerifyCaptcha_regex, "i") then
preurl = "/"
end
if captchaValue == postValue then
--比较验证码是否相等
_Conf.dict_black:delete(ip .. "black") --从黑名单删除
self:debug("[verifyCaptcha] captcha is valid.delete from blacklist", ip, "")
--清除perUrlRateLimit相关记录
self:perUrlRateLimitVerifyOK(ip, reqUri, address)
local oneKeyOpenVerificationOn = _Conf.dict_system:get("oneKeyOpenVerificationOn")
if oneKeyOpenVerificationOn == 1 then
--添加IP到白名单并删除challenge列表中验证失败计数器
local whiteTime = _Conf.dict_system:get("oneKeyOpenVerification_whiteTime")
_Conf.dict_white:set(ip .. "whiteVerification", 0, whiteTime)
return ngx.redirect(preurl)
else
if _Conf.redirectModulesIsOn then
_Conf.dict_white:set(ip .. "white302", 0, _Conf.whiteTime) --添加IP到白名单
local challengeTimesKey = table.concat({ ip, "challenge302" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除challenge列表中验证失败计数器
end
end
if _Conf.JsJumpModulesIsOn then
_Conf.dict_white:set(ip .. "whitejs", 0, _Conf.whiteTime)
local challengeTimesKey = table.concat({ ip, "challengejs" }) --添加IP到白名单
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除challenge列表中验证失败计数器
end
end
if _Conf.cookieModulesIsOn then
_Conf.dict_white:set(ip .. "whitecookie", 0, _Conf.whiteTime)
local challengeTimesKey = table.concat({ ip, "challengecookie" }) --添加IP到白名单
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除challenge列表中验证失败计数器
end
end
end
--local challengeTimesKey = table.concat({ip,"challengecookie"})
--local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
--if challengeTimesValue then
-- _Conf.dict_challenge:delete(challengeTimesKey) --删除challenge列表中验证失败计数器
--end
local expire = ngx.time() + _Conf.keyExpire
local captchaKey = ngx.md5(table.concat({ ip, _Conf.captchaKey, expire }))
local captchaKey = string.sub(captchaKey, "1", "10")
self:debug("[verifyCaptcha] expire " .. expire, ip, "")
self:debug("[verifyCaptcha] captchaKey " .. captchaKey, ip, "")
ngx.header['Set-Cookie'] = { "captchaKey=" .. captchaKey .. "; path=/", "captchaExpire=" .. expire .. "; path=/" }
return ngx.redirect(preurl) --返回上次访问url
else
if _Conf.captcha2clickOn and postValue then
--是否执行captcha2click
local challengeTimesKey = table.concat({ ip, "verifyFail" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue then
_Conf.dict_challenge:incr(challengeTimesKey, 1)
--重新发送验证码页面)
self:reSendCaptch(ip)
else
_Conf.dict_challenge:set(challengeTimesKey, 1, _Conf.captcha2click.amongTime)
--重新发送验证码页面
self:reSendCaptch(ip)
end
else
--重新发送验证码页面
--self:debug("[verifyCaptcha] captcha invalid",ip,"")
self:reSendCaptch(ip)
end
end
end
function Guard:reSendCaptch(ip)
self:debug("[verifyCaptcha] captcha invalid", ip, "")
ngx.status = 298
ngx.header.content_type = "text/html"
ngx.header['Cache-Control'] = "no-cache"
ngx.print(_Conf.reCaptchaPage)
ngx.exit(298)
end
--拒绝访问动作
function Guard:forbiddenAction()
ngx.header.content_type = "text/html"
ngx.exit(299)
end
--展示验证码页面动作
function Guard:captchaAction(ip, reqUri, address)
local captcha2clickOn = _Conf.dict_system:get("captcha2click_state")
local verifyMaxFail = _Conf.dict_system:get("captcha2click_verifyMaxFail")
if captcha2clickOn then
--是否开启captcha2click,当 captcha验证失败 _Conf.captcha2click.verifyMaxFail 次后改用 click验证
local challengeTimesKey = table.concat({ ip, "verifyFail" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue and (challengeTimesValue > verifyMaxFail) then
self:clickAction(ip, reqUri, address)
end
end
if ngx.re.match(reqUri, "^/get-captcha.do", "i") then
self:getCaptcha()
elseif ngx.re.match(reqUri, "^/verify-captcha.do", "i") then
self:verifyCaptcha(ip, reqUri, address)
else
ngx.status = 298
ngx.header.content_type = "text/html"
ngx.header['Set-Cookie'] = table.concat({ "preurl=", reqUri, "; path=/" })
ngx.header['Cache-Control'] = "no-cache"
ngx.print(_Conf.captchaPage)
ngx.exit(298)
end
end
--执行相应动作 (进入Black黑名单且不匹配 byPass 的都要验证)
function Guard:takeAction(ip, reqUri, address, userAgent, httpReferer)
local captchaAction = _Conf.dict_system:get("captchaAction")
local clickAction = _Conf.dict_system:get("clickAction")
local forbiddenAction = _Conf.dict_system:get("forbiddenAction")
local iptablesAction = _Conf.dict_system:get("iptablesAction")
local oneKeyOpenVerificationOn = _Conf.dict_system:get("oneKeyOpenVerificationOn")
if oneKeyOpenVerificationOn == 1 then
self:debug("[takeAction] return captchaAction(oneKeyOpenVerificationOn)" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:captchaAction(ip, reqUri, address)
elseif captchaAction then
self:debug("[takeAction] return captchaAction" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:captchaAction(ip, reqUri, address)
elseif clickAction then
self:debug("[takeAction] return clickAction" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:clickAction(ip, reqUri, address)
elseif forbiddenAction then
self:debug("[takeAction] return forbiddenAction" .. "::" .. userAgent .. "::" .. httpReferer .. "::", ip, reqUri)
self:forbiddenAction()
elseif iptablesAction then
ngx.thread.spawn(Guard.addToIptables, Guard, ip)
end
end
--添加进iptables drop表
function Guard:addToIptables(ip)
local cmd = "echo " .. _Conf.sudoPass .. " | sudo -S /sbin/iptables -I INPUT -p tcp -s " .. ip .. " --dport 80 -j DROP"
os.execute(cmd)
end
--自动开启或关闭防cc功能
function Guard:autoSwitch()
if not _Conf.dict_system:get("monitor") then
local interval = _Conf.dict_system:get("autoEnable_interval")
local normalTimes = _Conf.dict_system:get("autoEnable_normalTimes")
local exceedTimes = _Conf.dict_system:get("autoEnable_exceedTimes")
local maxConnection = _Conf.dict_system:get("autoEnable_maxConnection")
local enableModule = _Conf.dict_system:get("autoEnable_enableModule")
_Conf.dict_system:set("monitor", 0, interval)
local f = io.popen(_Conf.autoEnable.ssCommand .. " -tan state established '( sport = :" .. _Conf.autoEnable.protectPort .. " or dport = :" .. _Conf.autoEnable.protectPort .. " )' | wc -l")
local result = f:read("*all")
local connection = tonumber(result)
Guard:debug("[autoSwitch] current connection for port " .. _Conf.autoEnable.protectPort .. " is " .. connection, "", "")
if enableModule == "redirectModules" then
local redirectOn = _Conf.dict_system:get("redirectOn")
if redirectOn == 1 then
_Conf.dict_system:set("exceedCount", 0) --超限次数清0
--如果当前连接在最大连接之下,为正常次数加1
if connection < maxConnection then
_Conf.dict_system:incr("normalCount", 1)
end
--如果正常次数大于_Conf.autoEnable.normalTimes,关闭redirectModules
local normalCount = _Conf.dict_system:get("normalCount")
if normalCount > normalTimes then
Guard:log("[autoSwitch] turn redirectModules off.")
_Conf.dict_system:set("redirectOn", 0)
end
else
_Conf.dict_system:set("normalCount", 0) --正常次数清0
--如果当前连接在最大连接之上,为超限次数加1
if connection > maxConnection then
_Conf.dict_system:incr("exceedCount", 1)
end
--如果超限次数大于_Conf.autoEnable.exceedTimes,开启redirectModules
local exceedCount = _Conf.dict_system:get("exceedCount")
if exceedCount > exceedTimes then
Guard:log("[autoSwitch] turn redirectModules on.")
_Conf.dict_system:set("redirectOn", 1)
end
end
elseif enableModule == "JsJumpModules" then
local jsOn = _Conf.dict_system:get("jsOn")
if jsOn == 1 then
_Conf.dict_system:set("exceedCount", 0) --超限次数清0
--如果当前连接在最大连接之下,为正常次数加1
if connection < maxConnection then
_Conf.dict_system:incr("normalCount", 1)
end
--如果正常次数大于_Conf.autoEnable.normalTimes,关闭JsJumpModules
local normalCount = _Conf.dict_system:get("normalCount")
if normalCount > normalTimes then
Guard:log("[autoSwitch] turn JsJumpModules off.")
_Conf.dict_system:set("jsOn", 0)
end
else
_Conf.dict_system:set("normalCount", 0) --正常次数清0
--如果当前连接在最大连接之上,为超限次数加1
if connection > maxConnection then
_Conf.dict_system:incr("exceedCount", 1)
end
--如果超限次数大于_Conf.autoEnable.exceedTimes,开启JsJumpModules
local exceedCount = _Conf.dict_system:get("exceedCount")
if exceedCount > exceedTimes then
Guard:log("[autoSwitch] turn JsJumpModules on.")
_Conf.dict_system:set("jsOn", 1)
end
end
elseif enableModule == "cookieModules" then
local cookieOn = _Conf.dict_system:get("cookieOn")
if cookieOn == 1 then
_Conf.dict_system:set("exceedCount", 0) --超限次数清0
--如果当前连接在最大连接之下,为正常次数加1
if connection < maxConnection then
_Conf.dict_system:incr("normalCount", 1)
end
--如果正常次数大于_Conf.autoEnable.normalTimes,关闭cookieModules
local normalCount = _Conf.dict_system:get("normalCount")
if normalCount > normalTimes then
Guard:log("[autoSwitch] turn cookieModules off.")
_Conf.dict_system:set("cookieOn", 0)
end
else
_Conf.dict_system:set("normalCount", 0) --正常次数清0
--如果当前连接在最大连接之上,为超限次数加1
if connection > maxConnection then
_Conf.dict_system:incr("exceedCount", 1)
end
--如果超限次数大于_Conf.autoEnable.exceedTimes,开启cookieModules
local exceedCount = _Conf.dict_system:get("exceedCount")
if exceedCount > exceedTimes then
Guard:log("[autoSwitch] turn cookieModules on.")
_Conf.dict_system:set("cookieOn", 1)
end
end
end
end
end
--click点击验证
function Guard:clickAction(ip, reqUri, address)
if _Conf.captcha2clickOn then
--如果开启了captcha2click, 在用户访问captcha验证页面时显示验证码图片
if ngx.re.match(reqUri, "^/get-captcha.do", "i") then
self:getCaptcha()
end
end
ngx.req.read_body()
local now = ngx.time() --当前时间戳
local preurl = ngx.var["cookie_preurl"] or "/" --获取上次访问url,如果为空则返回首页(返回首页是为了避免用户禁用了 Cookie 而导致无法获取上次访问的URL)
local clickKeyValue = ngx.re.match(reqUri, "keydj=([^&]+)", "i")
local expire = ngx.re.match(reqUri, "expiredj=([^&]+)", "i")
if ngx.re.match(preurl, "verify-captcha.do", "i") then
local from, to, err = ngx.re.find(preurl, "verify-captcha.do", "i")
preurl = string.sub(preurl, 0, from - 1)
end
if clickKeyValue and expire then
--Click验证
local clickKeyValue = clickKeyValue[1]
local expire = expire[1]
local key_make = ngx.md5(table.concat({ ip, _Conf.clickKey, expire }))
local key_make = string.sub(key_make, "1", "10")
if key_make == clickKeyValue and now < tonumber(expire) then
local dict_black = ngx.shared.dict_black
local blackKey = ip .. "black"
dict_black:delete(blackKey) --从黑名单删除该IP
if _Conf.redirectModulesIsOn then
--添加IP到白名单
_Conf.dict_white:set(ip .. "white302", 0, _Conf.whiteTime)
end
if _Conf.JsJumpModulesIsOn then
_Conf.dict_white:set(ip .. "whitejs", 0, _Conf.whiteTime)
end
if _Conf.cookieModulesIsOn then
_Conf.dict_white:set(ip .. "whitecookie", 0, _Conf.whiteTime)
end
local challengeTimesKey = table.concat({ ip, "challengecookie" })
local challengeTimesValue = _Conf.dict_challenge:get(challengeTimesKey)
if challengeTimesValue then
_Conf.dict_challenge:delete(challengeTimesKey) --删除challenge列表中验证失败计数器
end
return ngx.redirect(preurl) --返回上次访问url
else
--如果clickKeyValue expire不合法, 返回click验证页面
local newUrl = ''
local clickCode = 'Error: Click Verify Page is no return'
local expire = now + _Conf.keyExpire
local key_new = ngx.md5(table.concat({ ip, _Conf.clickKey, expire }))
local key_new = string.sub(key_new, "1", "10")
local args = ngx.req.get_uri_args() or {}
local f, t, err = ngx.re.find(reqUri, "\\?&keydj|\\?keydj|&keydj=|keydj=", "ijo")
if f then
--url中是否含 &keydj=或keydj=
reqUri = string.sub(reqUri, 0, f - 1) --url 截断到&keydj=或keydj=
end
if ngx.re.match(reqUri, "\\?$", "ijo") then
newUrl = table.concat({ reqUri, "keydj=", key_new, "&expiredj=", expire })
elseif ngx.re.match(reqUri, "\\?.+", "ijo") then
newUrl = table.concat({ reqUri, "&keydj=", key_new, "&expiredj=", expire })
else
newUrl = table.concat({ reqUri, "?keydj=", key_new, "&expiredj=", expire })
end
--定义click验证页面代码
if _Conf.hiddenClick then
--隐藏click验证页面,自动验证
clickCode = table.concat({ '<meta http-equiv="refresh" content="0; url=', newUrl, '" >' })
--clickCode = table.concat({ '<script>window.location.href="',newUrl,'";</script>' })
else
--click验证页面,倒计时9秒后自动打开目标链接
clickCode = table.concat({ '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" ><title>Click 2 verity</title><style> #content { position:absolute;width:400px;height:200px;left:50%;top:50%;margin-left:-200px;margin-top:-100px;vertical-align:middle;line-height:200px;text-align:center;font-family:"微软雅黑";font-size:16px } </style><script type="text/javascript"> function countDown(secs,tUrl){ var jumpTo = document.getElementById("jumpTo"); jumpTo.innerHTML=secs; if (--secs>0){ setTimeout("countDown("+secs+",', "'", '"+tUrl+"', "'", ')",1000); } else{ window.location.href=tUrl; } } </script></head> <body><div id="content" ><a href="', newUrl, '">点击继续访问</a> <span id="jumpTo">9</span>″ <script type="text/javascript">countDown(9,"', newUrl, '");</script> </div></body></html>' })
end