-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathnode_quality_filter.py
More file actions
2768 lines (1385 loc) · 70 KB
/
Copy pathnode_quality_filter.py
File metadata and controls
2768 lines (1385 loc) · 70 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
节点质量筛选工具
功能:
1. 测试节点连通性
2. 测试节点延迟
3. 测试下载速度
4. 按协议类型筛选
5. 节点去重
"""
import os
import re
import json
import time
import socket
import base64
import asyncio
import requests
import yaml
import random
import urllib.parse
import httpx
import argparse
from loguru import logger
from tqdm import tqdm
class NodeQualityFilter:
def __init__(self, config_path='config.yaml'):
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.config_path = os.path.join(self.base_dir, config_path)
# 输入输出文件
# 支持两个输入源
self.input_file_collected = os.path.join(self.base_dir, 'collected_nodes.txt') # 裸节点源
self.input_file_all = os.path.join(self.base_dir, 'sub', 'sub_all_url_check.txt') # 完整URL源
# 输出文件放在 sub 文件夹
self.sub_dir = os.path.join(self.base_dir, 'sub')
self.runtime_dir = os.path.join(self.base_dir, 'runtime')
self.output_file = os.path.join(self.sub_dir, 'high_quality_nodes.txt')
self.report_file = os.path.join(self.runtime_dir, 'quality_report.json')
# 确保输出目录存在
if not os.path.exists(self.sub_dir):
os.makedirs(self.sub_dir)
if not os.path.exists(self.runtime_dir):
os.makedirs(self.runtime_dir)
# 默认配置
self.max_workers = 32
self.connect_timeout = 5
self.max_latency = 500 # 最大延迟(ms)
self.min_speed = 0 # 最小速度(KB/s),0表示不测速
# 大规模节点处理配置
self.max_test_nodes = 5000 # 最多测试节点数
self.max_output_nodes = 200 # 最多输出节点数
self.preferred_protocols_only = False # 是否只测试首选协议
self.smart_sampling = True # 智能采样
# 协议优先级 (分数越高越好)
self.protocol_scores = {
'hysteria2': 10,
'vless': 9,
'trojan': 8,
'vmess': 7,
'ss': 6
}
# 首选协议列表
self.preferred_protocols = ['hysteria2', 'vless', 'trojan', 'vmess', 'ss']
# CN probe defaults (optional)
self.cn_probe_enabled = False
self.cn_probe_results_path = os.path.join(self.sub_dir, 'cn_probe.json')
self.cn_probe_url = os.getenv('CN_PROBE_URL', '')
self.cn_probe_token = os.getenv('CN_PROBE_TOKEN', '')
self.cn_probe_weight = 1.0
self.cn_probe_max_latency = 800
self.cn_probe_max_bonus = 6
self.cn_probe_results = {}
self.cn_probe_matched = 0
# Risk/phishing filter defaults (optional)
self.risk_filter_enabled = False
self.risk_filter_mode = 'score'
self.risk_filter_penalty = 6
self.risk_filter_max_penalty = 18
self.risk_filter_max_path_len = 120
self.risk_filter_suspicious_tlds = []
self.risk_filter_phishing_keywords = []
self.risk_filter_allow_sni_domains = []
self.risk_filter_allow_host_domains = []
self.risk_filter_allow_path_keywords = []
self.risk_filter_block_on = {}
self.risk_filter_blocked = 0
self.risk_filter_penalized = 0
# ASN/ISP/ORG filter (ipapi only)
self.asn_filter_enabled = False
self.asn_filter_mode = 'score'
self.asn_filter_penalty = 10
self.asn_filter_asn_blacklist = []
self.asn_filter_org_keywords = []
self.asn_filter_isp_keywords = []
self.asn_filter_blocked = 0
self.asn_filter_penalized = 0
# Dynamic probe head (optional)
self.dynamic_probe_enabled = False
self.dynamic_probe_sample_size = 50
self.dynamic_probe_min_success = 5
self.dynamic_probe_force_proxy = True
self.dynamic_probe_proxy_url = ''
self.dynamic_probe_save_path = os.path.join(self.runtime_dir, 'probe_head.json')
self.dynamic_probe_node = None
self.dynamic_probe_supported_protocols = ['vless', 'trojan', 'vmess', 'ss', 'hysteria2']
# CN test proxy (optional)
self.cn_test_proxy_enabled = False
self.cn_test_proxy_type = 'api'
self.cn_test_proxy_api_url = ''
self.cn_test_proxy_api_token = ''
self.cn_test_proxy_url = ''
self.cn_test_proxy_timeout = 8
self.cn_test_proxy_test_url = 'https://www.google.com/generate_204'
self.cn_test_proxy_expected_status = 204
self.cn_test_proxy_required = True
# Third-party CN probe API (optional)
self.cn_probe_api_enabled = False
self.cn_probe_api_url_template = ''
self.cn_probe_api_method = 'GET'
self.cn_probe_api_timeout = 8
self.cn_probe_api_headers = {}
self.cn_probe_api_success_field = 'success'
self.cn_probe_api_success_values = [True, 'ok', 1]
self.cn_probe_api_locations_path = 'data.locations'
self.cn_probe_api_location_name_field = 'city'
self.cn_probe_api_location_ok_field = 'ok'
self.cn_probe_api_ok_values = [True, 'ok', 1]
self.cn_probe_api_require_locations = ['北京', '上海', '广州']
self.load_config()
def load_config(self):
"""加载配置文件"""
try:
if os.path.exists(self.config_path):
with open(self.config_path, 'r', encoding='utf-8') as f:
config = yaml.safe_load(f)
# 读取质量筛选配置
quality_filter = config.get('quality_filter', {})
self.max_workers = quality_filter.get('max_workers', 32)
self.connect_timeout = quality_filter.get('connect_timeout', 5)
self.max_latency = quality_filter.get('max_latency', 500)
self.min_speed = quality_filter.get('min_speed', 0)
self.preferred_protocols = quality_filter.get('preferred_protocols', self.preferred_protocols)
# 大规模节点处理配置
self.max_test_nodes = quality_filter.get('max_test_nodes', 5000)
self.max_output_nodes = quality_filter.get('max_output_nodes', 200)
self.preferred_protocols_only = quality_filter.get('preferred_protocols_only', False)
self.smart_sampling = quality_filter.get('smart_sampling', True)
# IP风险检测配置
self.ip_risk_config = config.get('ip_risk_check', {})
self.ip_risk_config.setdefault('enabled', False)
self.ip_risk_config.setdefault('check_top_nodes', 50)
self.ip_risk_config.setdefault('max_risk_score', 50)
logger.info(f'已加载配置: 线程数={self.max_workers}, 超时={self.connect_timeout}s, 最大延迟={self.max_latency}ms')
logger.info(f'大规模优化: 最多测试={self.max_test_nodes}, 最多输出={self.max_output_nodes}, 首选协议={self.preferred_protocols_only}')
if self.ip_risk_config['enabled']:
logger.info(f'🛡️ IP风险检测已开启 (Top {self.ip_risk_config["check_top_nodes"]})')
# 读取区域限制配置
self.region_config = quality_filter.get('region_limit', {})
if self.region_config.get('enabled'):
allowed = self.region_config.get('allowed_countries', [])
logger.info(f'🌍 区域限制已开启: 白名单={allowed if allowed else "关闭"}, 策略={self.region_config.get("policy", "filter")}')
# CN probe config
self.cn_probe_config = config.get('cn_probe', {})
self.cn_probe_enabled = bool(self.cn_probe_config.get('enabled', False))
results_path = self.cn_probe_config.get('results_path', self.cn_probe_results_path)
if results_path:
self.cn_probe_results_path = results_path
if not os.path.isabs(self.cn_probe_results_path):
self.cn_probe_results_path = os.path.join(self.base_dir, self.cn_probe_results_path)
self.cn_probe_url = os.getenv('CN_PROBE_URL') or self.cn_probe_config.get('results_url', self.cn_probe_url)
self.cn_probe_token = os.getenv('CN_PROBE_TOKEN') or self.cn_probe_config.get('token', self.cn_probe_token)
self.cn_probe_weight = float(self.cn_probe_config.get('weight', self.cn_probe_weight))
self.cn_probe_max_latency = int(self.cn_probe_config.get('max_latency', self.cn_probe_max_latency))
self.cn_probe_max_bonus = float(self.cn_probe_config.get('max_bonus', self.cn_probe_max_bonus))
self.cn_probe_results = self._load_cn_probe_results()
if self.cn_probe_enabled:
logger.info(f'🇨🇳 CN probe 已启用: 匹配={len(self.cn_probe_results)} 条, 权重={self.cn_probe_weight}')
# Risk/phishing filter config
risk_filter = config.get('risk_filter', {})
self.risk_filter_enabled = bool(risk_filter.get('enabled', False))
self.risk_filter_mode = str(risk_filter.get('mode', self.risk_filter_mode)).lower()
self.risk_filter_penalty = int(risk_filter.get('penalty', self.risk_filter_penalty))
self.risk_filter_max_penalty = int(risk_filter.get('max_penalty', self.risk_filter_max_penalty))
self.risk_filter_max_path_len = int(risk_filter.get('max_path_len', self.risk_filter_max_path_len))
self.risk_filter_suspicious_tlds = [t.lower().lstrip('.') for t in risk_filter.get('suspicious_tlds', [])]
self.risk_filter_phishing_keywords = [k.lower() for k in risk_filter.get('phishing_keywords', [])]
self.risk_filter_allow_sni_domains = [d.lower().lstrip('.') for d in risk_filter.get('allow_sni_domains', [])]
self.risk_filter_allow_host_domains = [d.lower().lstrip('.') for d in risk_filter.get('allow_host_domains', [])]
self.risk_filter_allow_path_keywords = [k.lower() for k in risk_filter.get('allow_path_keywords', [])]
self.risk_filter_block_on = risk_filter.get('block_on', {}) if isinstance(risk_filter.get('block_on', {}), dict) else {}
if self.risk_filter_enabled:
logger.info(f'🛡️ 风险/钓鱼过滤已启用: mode={self.risk_filter_mode}, penalty={self.risk_filter_penalty}')
# ASN filter config (ipapi only)
asn_filter = self.ip_risk_config.get('asn_filter', {}) if isinstance(self.ip_risk_config, dict) else {}
self.asn_filter_enabled = bool(asn_filter.get('enabled', False))
self.asn_filter_mode = str(asn_filter.get('mode', self.asn_filter_mode)).lower()
self.asn_filter_penalty = int(asn_filter.get('penalty', self.asn_filter_penalty))
self.asn_filter_asn_blacklist = [str(a).lower().replace('as', '') for a in asn_filter.get('asn_blacklist', [])]
self.asn_filter_org_keywords = [k.lower() for k in asn_filter.get('org_blacklist_keywords', [])]
self.asn_filter_isp_keywords = [k.lower() for k in asn_filter.get('isp_blacklist_keywords', [])]
if self.asn_filter_enabled:
logger.info(f'🧭 ASN/ORG/ISP 黑名单已启用: mode={self.asn_filter_mode}, penalty={self.asn_filter_penalty}')
# CN test proxy config
cn_test_proxy = config.get('cn_test_proxy', {}) if isinstance(config, dict) else {}
self.cn_test_proxy_enabled = bool(cn_test_proxy.get('enabled', False))
self.cn_test_proxy_type = str(cn_test_proxy.get('type', self.cn_test_proxy_type)).lower()
self.cn_test_proxy_api_url = cn_test_proxy.get('api_url', self.cn_test_proxy_api_url) or ''
self.cn_test_proxy_api_token = cn_test_proxy.get('api_token', self.cn_test_proxy_api_token) or ''
self.cn_test_proxy_url = cn_test_proxy.get('proxy_url', self.cn_test_proxy_url) or ''
self.cn_test_proxy_timeout = int(cn_test_proxy.get('timeout', self.cn_test_proxy_timeout))
self.cn_test_proxy_test_url = cn_test_proxy.get('test_url', self.cn_test_proxy_test_url)
self.cn_test_proxy_expected_status = int(cn_test_proxy.get('expected_status', self.cn_test_proxy_expected_status))
self.cn_test_proxy_required = bool(cn_test_proxy.get('required', self.cn_test_proxy_required))
if self.cn_test_proxy_enabled:
logger.info(f'🇨🇳 CN 测试代理已启用: type={self.cn_test_proxy_type}, required={self.cn_test_proxy_required}')
# CN probe API config (third-party)
cn_probe_api = config.get('cn_probe_api', {}) if isinstance(config, dict) else {}
self.cn_probe_api_enabled = bool(cn_probe_api.get('enabled', False))
self.cn_probe_api_url_template = cn_probe_api.get('url_template', self.cn_probe_api_url_template) or ''
self.cn_probe_api_method = str(cn_probe_api.get('method', self.cn_probe_api_method)).upper()
self.cn_probe_api_timeout = int(cn_probe_api.get('timeout', self.cn_probe_api_timeout))
self.cn_probe_api_headers = cn_probe_api.get('headers', self.cn_probe_api_headers) or {}
self.cn_probe_api_success_field = cn_probe_api.get('success_field', self.cn_probe_api_success_field)
self.cn_probe_api_success_values = cn_probe_api.get('success_values', self.cn_probe_api_success_values)
self.cn_probe_api_locations_path = cn_probe_api.get('locations_path', self.cn_probe_api_locations_path)
self.cn_probe_api_location_name_field = cn_probe_api.get('location_name_field', self.cn_probe_api_location_name_field)
self.cn_probe_api_location_ok_field = cn_probe_api.get('location_ok_field', self.cn_probe_api_location_ok_field)
self.cn_probe_api_ok_values = cn_probe_api.get('ok_values', self.cn_probe_api_ok_values)
self.cn_probe_api_require_locations = cn_probe_api.get('require_locations', self.cn_probe_api_require_locations)
if self.cn_probe_api_enabled:
logger.info('🌏 已启用第三方国内拨测 API')
# Dynamic probe config
dynamic_probe = config.get('dynamic_probe', {}) if isinstance(config, dict) else {}
self.dynamic_probe_enabled = bool(dynamic_probe.get('enabled', False))
self.dynamic_probe_sample_size = int(dynamic_probe.get('sample_size', self.dynamic_probe_sample_size))
self.dynamic_probe_min_success = int(dynamic_probe.get('min_success', self.dynamic_probe_min_success))
self.dynamic_probe_force_proxy = bool(dynamic_probe.get('force_proxy', self.dynamic_probe_force_proxy))
self.dynamic_probe_proxy_url = os.getenv('DYNAMIC_PROBE_PROXY_URL') or dynamic_probe.get('proxy_url', self.dynamic_probe_proxy_url) or ''
supported = dynamic_probe.get('supported_protocols', self.dynamic_probe_supported_protocols)
if isinstance(supported, list) and supported:
self.dynamic_probe_supported_protocols = [str(p).lower() for p in supported]
save_path = dynamic_probe.get('save_path', self.dynamic_probe_save_path)
if save_path:
self.dynamic_probe_save_path = os.path.join(self.base_dir, save_path) if not os.path.isabs(save_path) else save_path
if self.dynamic_probe_enabled:
logger.info(f'🛰️ 动态盲选探测头已启用: sample={self.dynamic_probe_sample_size}, min_success={self.dynamic_probe_min_success}')
except Exception as e:
logger.warning(f'加载配置失败,使用默认配置: {e}')
def _load_cn_probe_results(self):
"""Load CN probe data from URL or local file."""
if not self.cn_probe_enabled:
return {}
data = None
if self.cn_probe_url:
try:
headers = {}
if self.cn_probe_token:
headers['Authorization'] = f'Bearer {self.cn_probe_token}'
response = requests.get(self.cn_probe_url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
else:
logger.warning(f'⚠️ CN probe URL 获取失败: HTTP {response.status_code}')
except Exception as e:
logger.warning(f'⚠️ CN probe URL 读取失败: {e}')
if data is None and os.path.exists(self.cn_probe_results_path):
try:
with open(self.cn_probe_results_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except Exception as e:
logger.warning(f'⚠️ CN probe 文件读取失败: {e}')
if data is None:
logger.info('ℹ️ CN probe 已启用,但未找到结果数据')
return {}
return self._normalize_cn_probe_data(data)
def _normalize_cn_probe_data(self, data):
"""Normalize CN probe data into {key: {latency, score}} format."""
results = {}
if isinstance(data, dict):
if isinstance(data.get('nodes'), list):
items = data.get('nodes', [])
else:
for key, value in data.items():
if key in ('meta', 'nodes'):
continue
entry = self._extract_cn_probe_entry(value)
if entry:
results[key] = entry
return results
elif isinstance(data, list):
items = data
else:
return results
for item in items:
if not isinstance(item, dict):
continue
host = item.get('host') or item.get('ip')
port = item.get('port')
if not host or not port:
continue
key = f"{host}:{port}"
entry = self._extract_cn_probe_entry(item)
if entry:
results[key] = entry
return results
def _extract_cn_probe_entry(self, obj):
if isinstance(obj, (int, float)):
return {'latency': float(obj), 'score': None}
if not isinstance(obj, dict):
return None
latency = None
for key in ('latency_ms', 'latency', 'rtt', 'avg', 'mean'):
if key in obj:
try:
latency = float(obj[key])
except Exception:
latency = None
break
score = None
for key in ('score', 'cn_score'):
if key in obj:
try:
score = float(obj[key])
except Exception:
score = None
break
if latency is None and score is None:
return None
return {'latency': latency, 'score': score}
def _attach_cn_probe(self, nodes):
if not self.cn_probe_enabled or not self.cn_probe_results:
return
matched = 0
for node in nodes:
key = f"{node['host']}:{node['port']}"
entry = self.cn_probe_results.get(key)
if not entry:
continue
if entry.get('latency') is not None:
node['cn_latency'] = entry['latency']
if entry.get('score') is not None:
node['cn_score'] = entry['score']
matched += 1
self.cn_probe_matched = matched
def _cn_probe_bonus(self, node_info):
if not self.cn_probe_enabled:
return None
if 'cn_score' in node_info and node_info.get('cn_score') is not None:
try:
score = float(node_info['cn_score'])
# assume 0-100
return (score / 100.0) * self.cn_probe_max_bonus
except Exception:
pass
if 'cn_latency' not in node_info or node_info.get('cn_latency') is None:
return None
try:
latency = float(node_info['cn_latency'])
except Exception:
return None
if latency < 100:
return self.cn_probe_max_bonus
if latency < 200:
return self.cn_probe_max_bonus * 0.7
if latency < 300:
return self.cn_probe_max_bonus * 0.4
if latency < 500:
return self.cn_probe_max_bonus * 0.2
if latency > self.cn_probe_max_latency:
return -self.cn_probe_max_bonus * 0.5
return 0.0
def _sort_key(self, node):
return (
node.get('final_score', 0),
-node.get('cn_latency', 999),
-node.get('latency', 999)
)
def _get_by_path(self, data, path):
if not path:
return None
current = data
for part in str(path).split('.'):
if isinstance(current, dict) and part in current:
current = current[part]
else:
return None
return current
def _value_matches(self, value, allowed_values):
for allowed in allowed_values or []:
if value == allowed:
return True
if isinstance(value, str) and isinstance(allowed, str) and value.lower() == allowed.lower():
return True
return False
def _normalize_domain(self, value):
if not value:
return ''
text = str(value).strip().lower()
if '://' in text:
try:
text = urllib.parse.urlparse(text).netloc or text
except Exception:
pass
if ',' in text:
text = text.split(',', 1)[0]
if ':' in text:
text = text.split(':', 1)[0]
return text.strip('.')
def _domain_allowed(self, domain, allow_list):
if not domain or not allow_list:
return False
for item in allow_list:
if domain == item or domain.endswith('.' + item):
return True
return False
def _contains_phishing_keyword(self, text):
if not text:
return False
text = str(text).lower()
for kw in self.risk_filter_phishing_keywords:
if kw and kw in text:
return True
return False
def _apply_risk_filter(self, node_info):
"""Return (block, penalty, flags) based on rule heuristics."""
if not self.risk_filter_enabled:
return False, 0, []
flags = []
penalty = 0
block = False
def add_flag(flag_key, should_block=False):
nonlocal penalty, block
flags.append(flag_key)
if should_block or self.risk_filter_mode == 'filter':
block = True
else:
penalty += self.risk_filter_penalty
allow_insecure = node_info.get('allow_insecure')
if allow_insecure:
add_flag('allow_insecure', self.risk_filter_block_on.get('allow_insecure', False))
security = str(node_info.get('security') or '').lower()
tls_val = str(node_info.get('tls') or '').lower()
if security in ('none', 'plain') or tls_val in ('0', 'false', 'none'):
add_flag('security_none', self.risk_filter_block_on.get('security_none', False))
sni = self._normalize_domain(node_info.get('sni'))
host_header = self._normalize_domain(node_info.get('host_header'))
path = str(node_info.get('path') or '')
# suspicious tld
if self.risk_filter_suspicious_tlds:
if sni and any(sni.endswith('.' + tld) or sni == tld for tld in self.risk_filter_suspicious_tlds):
add_flag('sni_suspicious_tld', self.risk_filter_block_on.get('sni_phishing', False))
if host_header and any(host_header.endswith('.' + tld) or host_header == tld for tld in self.risk_filter_suspicious_tlds):
add_flag('host_suspicious_tld', self.risk_filter_block_on.get('host_phishing', False))
# phishing keyword checks with allowlist
if sni and not self._domain_allowed(sni, self.risk_filter_allow_sni_domains):
if self._contains_phishing_keyword(sni):
add_flag('sni_phishing', self.risk_filter_block_on.get('sni_phishing', False))
if sni.startswith('xn--'):
add_flag('sni_punycode', self.risk_filter_block_on.get('sni_phishing', False))
if host_header and not self._domain_allowed(host_header, self.risk_filter_allow_host_domains):
if self._contains_phishing_keyword(host_header):
add_flag('host_phishing', self.risk_filter_block_on.get('host_phishing', False))
if host_header.startswith('xn--'):
add_flag('host_punycode', self.risk_filter_block_on.get('host_phishing', False))
if path:
if self.risk_filter_max_path_len and len(path) > self.risk_filter_max_path_len:
add_flag('path_too_long', self.risk_filter_block_on.get('path_phishing', False))
allow_path = False
for kw in self.risk_filter_allow_path_keywords:
if kw and kw in path.lower():
allow_path = True
break
if not allow_path and self._contains_phishing_keyword(path):
add_flag('path_phishing', self.risk_filter_block_on.get('path_phishing', False))
if penalty > self.risk_filter_max_penalty:
penalty = self.risk_filter_max_penalty
return block, penalty, flags
def _apply_asn_filter(self, node_info, ipapi_data):
"""Apply ASN/ORG/ISP blacklist using ipapi data."""
if not self.asn_filter_enabled or not isinstance(ipapi_data, dict):
return False, 0, []
as_text = str(ipapi_data.get('as', '') or '')
org = str(ipapi_data.get('org', '') or '')
isp = str(ipapi_data.get('isp', '') or '')
asn_num = ''
match = re.search(r'AS(\\d+)', as_text, re.IGNORECASE)
if match:
asn_num = match.group(1)
flags = []
penalty = 0
block = False
def add_flag(flag_key):
nonlocal penalty, block
flags.append(flag_key)
if self.asn_filter_mode == 'filter':
block = True
else:
penalty += self.asn_filter_penalty
if asn_num and asn_num in self.asn_filter_asn_blacklist:
add_flag('asn_blacklist')