Repository navigation
Expand file tree
/
Copy pathPlugin.php
More file actions
1251 lines (1088 loc) · 43 KB
/
Copy pathPlugin.php
File metadata and controls
1251 lines (1088 loc) · 43 KB
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
<?php
/**
* 高级IP访问控制 (Advanced IP Blocker)
*
* 一款功能强大的Typecho插件,提供基于IP的黑名单、白名单和智能威胁检测功能,保护您的网站免受恶意访问和攻击。
*
* @package AdvancedBlockIP
* @author 璇
* @version 2.4.1
* @link https://github.com/BXCQ/AdvancedBlockIP
* @update 2025.10.09
*
* 历史版本
* Version 1.0.0 (2014-10-14)
* Version 1.0.1 (2014-10-15)
* Version 2.0.0 (2025-04-05) - 璇
* Version 2.1.0 (2025-05-13) - 璇
* Version 2.2.0 (2025-06-06) - 璇
* Version 2.3.0 (2025-06-23) - 璇
* Version 2.3.1 (2025-07-10) - 璇
* Version 2.3.2 (2025-07-11) - 璇
* Version 2.3.3 (2025-07-22) - 璇
* Version 2.4.0 (2025-08-13) - 璇 - 新增User-Agent白名单功能
* Version 2.4.1 (2025-10-09) - 璇 - 修复误拦截和安全保护机制
*/
namespace TypechoPlugin\AdvancedBlockIP;
// 导入Typecho核心类
use Typecho\Plugin\PluginInterface;
use Typecho\Widget\Helper\Form;
use Typecho\Widget\Helper\Form\Element\Select;
use Typecho\Widget\Helper\Form\Element\Textarea;
use Typecho\Widget\Helper\Form\Element\Checkbox;
use Typecho\Widget\Helper\Form\Element\Text;
use Typecho\Plugin as TypechoPlugin;
use Typecho\Db;
use Typecho\Widget\Exception;
use Typecho\Request;
use Typecho\Widget;
use Typecho\Common;
if (!defined('__TYPECHO_ROOT_DIR__')) exit;
require_once 'adapter.php';
/**
* 高级IP访问控制插件类
*/
class Plugin implements PluginInterface
{
/**
* 激活插件
*/
public static function activate()
{
try {
// 绑定到页面渲染前的钩子
TypechoPlugin::factory('Widget_Archive')->beforeRender = array(__CLASS__, 'checkIPAccess');
// 添加更多钩子以确保拦截功能在所有页面生效
TypechoPlugin::factory('Widget_Archive')->header = array(__CLASS__, 'checkIPAccess');
TypechoPlugin::factory('Widget_Archive')->footer = array(__CLASS__, 'checkIPAccess');
TypechoPlugin::factory('Widget_Archive')->handle = array(__CLASS__, 'checkIPAccess');
TypechoPlugin::factory('index.php')->begin = array(__CLASS__, 'checkIPAccess');
TypechoPlugin::factory('admin/common.php')->begin = array(__CLASS__, 'checkIPAccess');
// 使用全局命名空间的Helper类
\Helper::addPanel(1, 'AdvancedBlockIP/console.php', 'IP防护控制台', 'IP防护控制台', 'administrator');
// 兼容导航菜单钩子
TypechoPlugin::factory('admin/menu.php')->navBar = array(__CLASS__, 'navBar');
// 创建插件数据表(包括表结构更新)
self::createTables();
return "高级IP访问控制插件启用成功!";
} catch (\Exception $e) {
return "插件激活失败: " . $e->getMessage() . " (文件: " . $e->getFile() . ", 行: " . $e->getLine() . ")";
}
}
/**
* 禁用插件
*/
public static function deactivate()
{
// 使用全局命名空间的Helper类
\Helper::removePanel(1, 'AdvancedBlockIP/console.php');
return "高级IP访问控制插件已禁用。";
}
/**
* 添加导航条
*
* @param array $items 导航项目
* @return array $items 返回修改后的导航项目
*/
public static function navBar($items = array())
{
// 最简单的方式添加菜单项
$items['IP防护控制台'] = 'extending.php?panel=AdvancedBlockIP/console.php';
return $items;
}
/**
* 插件配置面板
*/
public static function config(Form $form)
{
try {
// 获取已保存的插件配置
$options = Widget::widget('Widget_Options');
$config = $options->plugin('AdvancedBlockIP');
} catch (\Exception $e) {
// 插件首次激活或无配置时,使用空对象
$config = new \stdClass();
}
// 功能模式选择
$mode = new Select(
'mode',
array(
'blacklist' => '黑名单模式(拦截指定IP)',
'whitelist' => '白名单模式(仅允许指定IP)',
'smart' => '智能模式(自动识别威胁)'
),
isset($config->mode) ? $config->mode : 'smart',
'工作模式',
'选择插件的工作模式,推荐使用智能模式(黑白名单同时生效)'
);
$form->addInput($mode);
// 黑名单处理模式
$blacklistMode = new Select(
'blacklistMode',
array(
'block' => '完全禁止访问',
'limit' => '限制访问频率'
),
isset($config->blacklistMode) ? $config->blacklistMode : 'block',
'黑名单处理模式',
'选择对黑名单IP的处理方式'
);
$form->addInput($blacklistMode);
// IP黑名单配置
$blacklistValue = isset($config->blacklist) ? $config->blacklist : '';
$blacklist = new Textarea(
'blacklist',
null,
$blacklistValue,
'IP黑名单',
'每行一个IP地址或IP段,支持以下格式:<br/>
• 单个IP:192.168.1.100<br/>
• IP范围:192.168.1.1-50<br/>
• 单个通配符:192.168.1.*<br/>
• 多个通配符:192.168.*.*、113.215.*.*<br/>
• 三个通配符:10.*.*.*、172.*.*.*<br/>
• CIDR:192.168.1.0/24<br/>'
);
$form->addInput($blacklist);
// IP白名单配置
$whitelistValue = isset($config->whitelist) ? $config->whitelist : '';
$whitelist = new Textarea(
'whitelist',
null,
$whitelistValue,
'IP白名单',
'管理员和可信任的IP地址列表,格式同黑名单,支持通配符如192.168.*.*'
);
$form->addInput($whitelist);
// User-Agent白名单配置
$uaWhitelistValue = isset($config->uaWhitelist) ? $config->uaWhitelist : '';
$uaWhitelist = new Textarea(
'uaWhitelist',
null,
$uaWhitelistValue,
'User-Agent白名单',
'可信任的User-Agent列表,每行一个,支持完整匹配和部分匹配。在此列表中的User-Agent将不会被智能检测拦截。<br/>'
. '支持格式:<br/>'
. '• 完整User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36<br/>'
. '• 部分匹配:Chrome、Firefox、Safari、Edge<br/>'
. '• 自定义应用:MyApp/1.0、TrustedBot'
);
$form->addInput($uaWhitelist);
// 访问间隔限制
$accessIntervalValue = isset($config->accessInterval) ? $config->accessInterval : '10';
$accessInterval = new Text(
'accessInterval',
null,
$accessIntervalValue,
'访问间隔限制(秒)',
'单个IP两次访问之间的最小间隔时间,0为不限制'
);
$form->addInput($accessInterval);
// 自定义拦截页面
$customMessageValue = isset($config->customMessage) ? $config->customMessage : '抱歉,您的访问被系统安全策略拦截。如需帮助,请联系网站管理员。';
$customMessage = new Textarea(
'customMessage',
null,
$customMessageValue,
'自定义拦截提示',
'自定义显示给被拦截用户的信息,支持HTML'
);
$form->addInput($customMessage);
// 调试模式
$debugMode = new Select(
'debugMode',
array(
'0' => '关闭',
'1' => '开启'
),
isset($config->debugMode) ? $config->debugMode : '0',
'调试模式',
'开启后会记录详细的运行日志到服务器error_log,仅在排查问题时开启'
);
$form->addInput($debugMode);
}
/**
* 个人配置(留空)
*/
public static function personalConfig(Form $form)
{
// 个人配置暂不需要
}
/**
* 主要的IP检查函数
*/
public static function checkIPAccess()
{
try {
// 使用静态变量防止重复执行
static $checked = false;
if ($checked) {
return;
}
$checked = true;
$request = new Request();
$clientIP = self::getRealClientIP($request);
try {
$options = Widget::widget('Widget_Options');
$config = $options->plugin('AdvancedBlockIP');
} catch (\Exception $e) {
// 当插件配置不存在时,提供一个空的默认配置
$config = new \stdClass();
}
// 获取工作模式,默认为智能模式
$mode = isset($config->mode) ? $config->mode : 'smart';
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 检查IP访问 - IP: {$clientIP}, 模式: {$mode}");
}
// 安全保护:如果是管理后台访问,则放行(防止误拦截导致无法访问后台)
$requestUrl = $request->getRequestUrl();
if (self::isAdminArea($requestUrl)) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 管理后台访问,自动放行IP: {$clientIP}");
}
self::recordLastAccess($clientIP, $requestUrl);
return;
}
// 白名单检查始终执行(最高优先级)
if (self::isWhitelisted($clientIP, $config)) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 白名单匹配成功,放行IP: {$clientIP}");
}
self::recordLastAccess($clientIP, $request->getRequestUrl());
return;
}
// 黑名单检查始终执行(第二优先级)
if (self::isBlacklisted($clientIP, $config)) {
$blacklistMode = isset($config->blacklistMode) ? $config->blacklistMode : 'block';
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 黑名单匹配成功,IP: {$clientIP}, 处理模式: {$blacklistMode}");
}
if ($blacklistMode === 'block') {
// 完全禁止访问
self::blockAccess($clientIP, 'blacklisted', $config);
return;
} else {
// 限制访问频率模式
if (self::isAccessTooFrequent($clientIP, $config, true)) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 黑名单IP访问过于频繁,拦截IP: {$clientIP}");
}
self::blockAccess($clientIP, 'blacklist_rate_limit', $config);
return;
}
self::recordLastAccess($clientIP, $request->getRequestUrl());
return;
}
}
// 智能模式处理
if ($mode === 'smart') {
// 智能检测(包含频率异常检测,会自动拉黑)
$smartBlockReasonsArray = self::isSmartBlocked($clientIP, $config);
if (!empty($smartBlockReasonsArray)) {
$combinedSmartReasonComment = implode(', ', $smartBlockReasonsArray);
$reasonForDisplayAndLog = '智能检测:' . $combinedSmartReasonComment;
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 智能拦截触发,IP: {$clientIP}, 原因: {$combinedSmartReasonComment}");
}
// 智能检测到异常,自动加入黑名单并拦截
self::addToBlacklist($clientIP, $config, $combinedSmartReasonComment);
self::blockAccess($clientIP, $reasonForDisplayAndLog, $config);
return;
}
// 智能模式下,非黑名单IP通过智能检测后直接放行
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 智能检测通过,放行IP: {$clientIP}");
}
self::recordLastAccess($clientIP, $request->getRequestUrl());
return;
}
// 其他模式处理
switch ($mode) {
case 'blacklist':
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 黑名单模式,非黑名单IP放行: {$clientIP}");
}
self::recordLastAccess($clientIP, $request->getRequestUrl());
return;
case 'whitelist':
// 白名单模式下,检查白名单是否为空
if (empty($config->whitelist) || trim($config->whitelist) === '') {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 白名单模式但白名单为空,为安全起见放行所有IP: {$clientIP}");
}
// 白名单为空时,记录警告日志,并放行所有访问(防止误拦截)
error_log("AdvancedBlockIP Warning: 白名单模式下白名单配置为空,已自动放行所有IP。请尽快配置白名单!");
self::recordLastAccess($clientIP, $request->getRequestUrl());
return;
}
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 白名单模式,非白名单IP拦截: {$clientIP}");
}
self::blockAccess($clientIP, 'not_whitelisted', $config);
return;
}
// 默认记录访问并放行
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 默认放行IP: {$clientIP}");
}
self::recordLastAccess($clientIP, $request->getRequestUrl());
} catch (\Exception $e) {
error_log("AdvancedBlockIP Error: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
}
}
/**
* 检查是否为管理后台访问
*/
private static function isAdminArea($url)
{
// 检查是否访问管理后台路径
$adminPaths = [
'/admin/',
'admin.php',
'admin/',
'/action/',
'action/',
];
foreach ($adminPaths as $path) {
if (strpos($url, $path) !== false) {
return true;
}
}
return false;
}
/**
* 获取真实客户端IP
*/
private static function getRealClientIP($request)
{
$ipHeaders = array(
'HTTP_X_FORWARDED_FOR',
'HTTP_X_REAL_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
);
foreach ($ipHeaders as $header) {
if (!empty($_SERVER[$header])) {
$ips = explode(',', $_SERVER[$header]);
$ip = trim($ips[0]);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
return $request->getIp();
}
/**
* 检查IP是否在黑名单中
*/
private static function isBlacklisted($ip, $config)
{
$blacklistConfig = '';
if (isset($config->blacklist) && !empty($config->blacklist)) {
$blacklistConfig = $config->blacklist;
} elseif (isset($config->ips) && !empty($config->ips)) {
$blacklistConfig = $config->ips;
}
if (empty($blacklistConfig)) {
return false;
}
return self::matchIPRules($ip, $blacklistConfig, $config);
}
/**
* 检查IP是否在白名单中
*/
private static function isWhitelisted($ip, $config)
{
if (!isset($config->whitelist) || empty($config->whitelist)) {
return false;
}
return self::matchIPRules($ip, $config->whitelist, $config);
}
/**
* 智能检测威胁IP
*/
private static function isSmartBlocked($ip, $config)
{
$reasons = [];
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 开始智能检测 IP: {$ip}");
}
// 频率异常检测
$frequencyAnomaly = self::checkFrequencyAnomaly($ip, $config);
if ($frequencyAnomaly) {
$reasons[] = '频率异常';
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 检测到频率异常 IP: {$ip}");
}
}
// UA异常检测
$uaAnomaly = self::checkUserAgentAnomaly($config);
if ($uaAnomaly) {
$reasons[] = 'UA异常';
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 检测到UA异常 IP: {$ip}, UA: " . $_SERVER['HTTP_USER_AGENT']);
}
}
// 来源异常检测
$refererAnomaly = self::checkRefererAnomaly();
if ($refererAnomaly) {
$reasons[] = '来源异常';
if ($debugMode) {
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '无';
error_log("AdvancedBlockIP Debug: 检测到来源异常 IP: {$ip}, Referer: {$referer}");
}
}
return $reasons;
}
/**
* 检测访问频率异常
*/
private static function checkFrequencyAnomaly($ip, $config)
{
try {
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
$db = Db::get();
$prefix = $db->getPrefix();
$currentTime = time();
// 放宽频率限制,避免误判正常用户
// 检查1秒内访问超过5个不同URL的情况(从2个调整到5个)
$recentAccessCountDifferentURLs = $db->fetchObject(
$db->select('COUNT(DISTINCT url) as count')
->from($prefix . 'blockip_access_log')
->where('ip = ? AND timestamp > ?', $ip, $currentTime - 1)
);
if ($recentAccessCountDifferentURLs && $recentAccessCountDifferentURLs->count >= 5) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 频率异常 - 1秒内访问{$recentAccessCountDifferentURLs->count}个不同URL, IP: {$ip}");
}
return true;
}
// 检查5秒内访问超过10次的情况(从3次调整到10次)
$recentAccessCount5s = $db->fetchObject(
$db->select('COUNT(*) as count')
->from($prefix . 'blockip_access_log')
->where('ip = ? AND timestamp > ?', $ip, $currentTime - 5)
);
if ($recentAccessCount5s && $recentAccessCount5s->count >= 10) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 频率异常 - 5秒内访问{$recentAccessCount5s->count}次, IP: {$ip}");
}
return true;
}
// 检查10秒内访问超过20次的情况(从6次调整到20次)
$recentAccessCount10s = $db->fetchObject(
$db->select('COUNT(*) as count')
->from($prefix . 'blockip_access_log')
->where('ip = ? AND timestamp > ?', $ip, $currentTime - 10)
);
if ($recentAccessCount10s && $recentAccessCount10s->count >= 20) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 频率异常 - 10秒内访问{$recentAccessCount10s->count}次, IP: {$ip}");
}
return true;
}
// 检查60秒内访问超过60次的情况(新增:每秒1次以上)
$recentAccessCount60s = $db->fetchObject(
$db->select('COUNT(*) as count')
->from($prefix . 'blockip_access_log')
->where('ip = ? AND timestamp > ?', $ip, $currentTime - 60)
);
if ($recentAccessCount60s && $recentAccessCount60s->count >= 60) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 频率异常 - 60秒内访问{$recentAccessCount60s->count}次, IP: {$ip}");
}
return true;
}
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 频率检测正常, IP: {$ip}");
}
return false;
} catch (\Exception $e) {
error_log("AdvancedBlockIP Error in checkFrequencyAnomaly: " . $e->getMessage());
return false;
}
}
/**
* 检查User-Agent是否异常
*/
private static function checkUserAgentAnomaly($config = null)
{
$request = new Request();
$userAgent = $request->getAgent();
if (empty($userAgent)) {
return 'UA为空';
}
// 检查User-Agent白名单
if ($config && isset($config->uaWhitelist) && !empty($config->uaWhitelist)) {
if (self::isUserAgentWhitelisted($userAgent, $config->uaWhitelist)) {
return false; // 在白名单中,不进行异常检测
}
}
// 常见的恶意或扫描工具的User-Agent片段
$maliciousUAs = [
'sqlmap',
'nmap',
'nikto',
'wpscan',
'acunetix',
'netsparker',
'havij',
'python-requests',
'go-http-client',
'curl/',
'wget/',
'libwww-perl',
'apachebench',
'httrack',
'indy library'
];
// 排除已知的正常搜索引擎爬虫
$knownGoodBots = [
'googlebot',
'bingbot',
'slurp',
'duckduckbot',
'baiduspider',
'yandexbot',
'sogou web spider',
'applebot'
];
foreach ($knownGoodBots as $goodBot) {
if (stripos($userAgent, $goodBot) !== false) {
return false;
}
}
foreach ($maliciousUAs as $uaPattern) {
if (stripos($userAgent, $uaPattern) !== false) {
return 'UA异常';
}
}
return false;
}
/**
* 检查User-Agent是否在白名单中
*/
private static function isUserAgentWhitelisted($userAgent, $whitelist)
{
if (empty($whitelist) || empty($userAgent)) {
return false;
}
$lines = preg_split('/[\r\n]+/', $whitelist, -1, PREG_SPLIT_NO_EMPTY);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line) || substr($line, 0, 1) === '#') {
continue; // 跳过空行和注释行
}
// 支持完整匹配(不区分大小写)
if (strcasecmp($userAgent, $line) === 0) {
return true;
}
// 支持部分匹配(不区分大小写)
if (stripos($userAgent, $line) !== false) {
return true;
}
}
return false;
}
/**
* 检查Referer是否异常
*/
private static function checkRefererAnomaly()
{
$request = new Request();
$referer = $request->getReferer();
if (empty($referer)) {
return false;
}
$suspiciousReferers = [
'casino',
'poker',
'gambling',
'adult',
'sex',
'seo_service',
'backlink_tool',
'.xyz/'
];
foreach ($suspiciousReferers as $refPattern) {
if (stripos($referer, $refPattern) !== false) {
return '来源异常';
}
}
return false;
}
/**
* 检查IP规则匹配
*/
private static function matchIPRules($ip, $rules, $config)
{
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
if (empty($rules)) {
return false;
}
$lines = preg_split('/[\r\n]+/', $rules, -1, PREG_SPLIT_NO_EMPTY);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line) || substr($line, 0, 1) === '#') {
continue; // 跳过空行和完整注释行
}
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 尝试匹配规则 IP: {$ip}, 规则: {$line}");
}
if (self::matchSingleIPRule($ip, $line, $config)) {
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 规则匹配成功 IP: {$ip}, 规则: {$line}");
}
return true;
}
}
return false;
}
/**
* 匹配单条IP规则
*/
private static function matchSingleIPRule($ip, $rule, $config)
{
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
// 去除规则中的行内注释
if (strpos($rule, '#') !== false) {
$rule = trim(substr($rule, 0, strpos($rule, '#')));
}
if (empty($rule)) {
return false;
}
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 处理规则 IP: {$ip}, 清理后规则: {$rule}");
}
// 检查各种规则格式
if ($rule === $ip) {
return true; // 完全匹配
} elseif (strpos($rule, '*') !== false) {
return self::matchWildcard($ip, $rule); // 通配符匹配
} elseif (strpos($rule, '/') !== false) {
return self::matchCIDR($ip, $rule); // CIDR匹配
} elseif (strpos($rule, '-') !== false) {
return self::matchIPRange($ip, $rule); // IP范围匹配
} elseif (preg_match('/^[A-Z]{2}$/', $rule)) {
// 国家代码匹配(需要GeoIP支持,暂未实现)
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 国家代码匹配暂不支持 IP: {$ip}, 国家代码: {$rule}");
}
return false;
}
return false;
}
/**
* 匹配通配符 - 确保正确实现
*/
private static function matchWildcard($ip, $pattern)
{
$ipParts = explode('.', $ip);
$patternParts = explode('.', $pattern);
if (count($ipParts) != 4 || count($patternParts) != 4) {
return false;
}
for ($i = 0; $i < 4; $i++) {
if ($patternParts[$i] === '*') {
continue;
}
if ($ipParts[$i] !== $patternParts[$i]) {
return false;
}
}
return true;
}
/**
* 匹配CIDR格式
*/
private static function matchCIDR($ip, $cidr)
{
list($network, $mask) = explode('/', $cidr);
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return (ip2long($ip) & ~((1 << (32 - $mask)) - 1)) === ip2long($network);
}
return false;
}
/**
* 匹配IP范围
*/
private static function matchIPRange($ip, $range)
{
$ipParts = explode('.', $ip);
$rangeParts = explode('.', $range);
for ($i = 0; $i < 4; $i++) {
if (strpos($rangeParts[$i], '-') !== false) {
list($start, $end) = explode('-', $rangeParts[$i]);
if ($ipParts[$i] < $start || $ipParts[$i] > $end) {
return false;
}
} else {
if ($ipParts[$i] != $rangeParts[$i]) {
return false;
}
}
}
return true;
}
/**
* 记录最后访问时间
*/
private static function recordLastAccess($ip, $url = '')
{
try {
$db = Db::get();
$prefix = $db->getPrefix();
$currentTime = time();
$request = new Request();
// 检查IP是否已存在
$existingRecord = $db->fetchRow($db->select()
->from($prefix . 'blockip_access_log')
->where('ip = ?', $ip));
if ($existingRecord) {
// 如果记录已存在,则更新
$db->query($db->update($prefix . 'blockip_access_log')
->rows(array(
'url' => $url,
'user_agent' => substr((string)$request->getAgent(), 0, 255),
'last_access' => $currentTime,
'timestamp' => $currentTime
))
->where('ip = ?', $ip));
} else {
// 如果记录不存在,则插入
$db->query($db->insert($prefix . 'blockip_access_log')
->rows(array(
'ip' => $ip,
'url' => $url,
'user_agent' => substr((string)$request->getAgent(), 0, 255),
'last_access' => $currentTime,
'timestamp' => $currentTime
)));
}
// 清理30天前的旧记录
$db->query($db->delete($prefix . 'blockip_access_log')
->where('last_access < ?', $currentTime - 2592000));
} catch (\Exception $e) {
error_log("AdvancedBlockIP recordLastAccess Error: " . $e->getMessage());
}
}
/**
* 检查访问是否过于频繁
*/
private static function isAccessTooFrequent($ip, $config, $isBlacklistCheck = false)
{
$accessInterval = isset($config->accessInterval) ? (int)$config->accessInterval : 10;
if ($accessInterval <= 0) {
return false;
}
if ($isBlacklistCheck) {
$accessInterval = max(1, $accessInterval * 0.1);
}
$lastAccess = self::getLastAccessTime($ip);
if ($lastAccess && (time() - $lastAccess) < $accessInterval) {
return true;
}
return false;
}
/**
* 获取上次访问时间
*/
private static function getLastAccessTime($ip)
{
static $accessCache = array();
if (isset($accessCache[$ip])) {
return $accessCache[$ip];
}
try {
$db = Db::get();
$prefix = $db->getPrefix();
$result = $db->fetchObject($db->select('last_access')
->from($prefix . 'blockip_access_log')
->where('ip = ?', $ip)
->order('last_access', Db::SORT_DESC)
->limit(1));
$lastAccess = $result ? (int)$result->last_access : 0;
$accessCache[$ip] = $lastAccess;
return $lastAccess;
} catch (\Exception $e) {
return 0;
}
}
/**
* 拦截访问
*/
private static function blockAccess($ip, $reason, $config)
{
// 判断是否开启调试模式
$debugMode = isset($config->debugMode) ? (bool)$config->debugMode : false;
$reasonMap = array(
'blacklisted' => '黑名单拦截',
'not_whitelisted' => '非白名单访问',
'access_too_frequent' => '访问过于频繁',
'blacklist_rate_limit' => '黑名单频率限制'
);
$finalReason = isset($reasonMap[$reason]) ? $reasonMap[$reason] : $reason;
if ($debugMode) {
error_log("AdvancedBlockIP Debug: 拦截访问 - IP: {$ip}, 原因: {$finalReason}");
}
self::logBlockedAccess($ip, $finalReason);
$customMessage = isset($config->customMessage) && !empty($config->customMessage) ?
$config->customMessage :
'抱歉,您的访问被系统安全策略拦截。如需帮助,请联系网站管理员。';
http_response_code(403);
header('Content-Type: text/html; charset=UTF-8');
echo '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>访问被拦截</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; background: #f5f5f5; }
.container { max-width: 600px; margin: 0 auto; background: white; padding: 40px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.icon { font-size: 64px; color: #e74c3c; margin-bottom: 20px; }
h1 { color: #2c3e50; margin-bottom: 20px; }
p { color: #7f8c8d; line-height: 1.6; }
.reason { background: #ecf0f1; padding: 10px; border-radius: 5px; margin: 20px 0; font-family: monospace; }
</style>
</head>
<body>
<div class="container">
<div class="icon">🛡️</div>
<h1>访问被拦截</h1>
<p>' . $customMessage . '</p>
<div class="reason">拦截原因: ' . htmlspecialchars($finalReason) . '</div>
<p><small>IP: ' . htmlspecialchars($ip) . ' | 时间: ' . date('Y-m-d H:i:s') . '</small></p>
</div>
</body>
</html>';